{"id": ["cloudnetpy.cloudnetpy.utils.cumsumr", "cloudnetpy.cloudnetpy.categorize.atmos_utils.calc_adiabatic_lwc"], "project": "cloudnetpy", "origin_file": ["cloudnetpy/utils.py", "cloudnetpy/categorize/atmos_utils.py"], "test_list": ["tests/unit/test_atmos_utils.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 1151, "func_start_lineno": 532, "func_end_lineno": 549, "func_code": "def cumsumr(array: np.ndarray, axis: int = 0) -> np.ndarray:\n \"\"\"Finds cumulative sum that resets on 0.\n\n Args:\n array: Input array.\n axis: Axis where the sum is calculated. Default is 0.\n\n Returns:\n Cumulative sum, restarted at 0.\n\n Examples:\n >>> x = np.array([0, 0, 1, 1, 0, 0, 0, 1, 1, 1])\n >>> cumsumr(x)\n [0, 0, 1, 2, 0, 0, 0, 1, 2, 3]\n\n \"\"\"\n cums = array.cumsum(axis=axis)\n return cums - np.maximum.accumulate(cums * (array == 0), axis=axis)"}, {"class_start_lineno": 1, "class_end_lineno": 357, "func_start_lineno": 302, "func_end_lineno": 318, "func_code": "def calc_adiabatic_lwc(lwc_dz: np.ndarray, height: np.ndarray) -> np.ndarray:\n \"\"\"Calculates adiabatic liquid water content (kg m-3).\n\n Args:\n lwc_dz: Liquid water content change rate (kg m-3 m-1) calculated at the\n base of each cloud and filled to that cloud.\n height: Height vector (m).\n\n Returns:\n Liquid water content (kg m-3).\n\n \"\"\"\n is_cloud = lwc_dz != 0\n cloud_indices = utils.cumsumr(is_cloud, axis=1)\n dz = utils.path_lengths_from_ground(height) * np.ones_like(lwc_dz)\n dz[cloud_indices < 1] = 0\n return utils.cumsumr(dz, axis=1) * lwc_dz"}], "type": ["function_empty"], "node": ["cloudnetpy.utils.cumsumr", "cloudnetpy.categorize.atmos_utils.calc_adiabatic_lwc"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 5, "base_passed_num": 4}} {"id": ["cloudnetpy.cloudnetpy.utils.binvec", "cloudnetpy.cloudnetpy.utils.rebin_1d", "cloudnetpy.cloudnetpy.utils.rebin_2d", "cloudnetpy.cloudnetpy.cloudnetarray.CloudnetArray::rebin_data"], "project": "cloudnetpy", "origin_file": ["cloudnetpy/utils.py", "cloudnetpy/utils.py", "cloudnetpy/utils.py", "cloudnetpy/cloudnetarray.py"], "test_list": ["tests/unit/test_categorize.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 1151, "func_start_lineno": 124, "func_end_lineno": 140, "func_code": "def binvec(x: np.ndarray | list) -> np.ndarray:\n \"\"\"Converts 1-D center points to bins with even spacing.\n\n Args:\n x: 1-D array of N real values.\n\n Returns:\n ndarray: N + 1 edge values.\n\n Examples:\n >>> binvec([1, 2, 3])\n [0.5, 1.5, 2.5, 3.5]\n\n \"\"\"\n edge1 = x[0] - (x[1] - x[0]) / 2\n edge2 = x[-1] + (x[-1] - x[-2]) / 2\n return np.linspace(edge1, edge2, len(x) + 1)"}, {"class_start_lineno": 1, "class_end_lineno": 1151, "func_start_lineno": 195, "func_end_lineno": 231, "func_code": "def rebin_1d(\n x_in: np.ndarray,\n array: np.ndarray | ma.MaskedArray,\n x_new: np.ndarray,\n statistic: str = \"mean\",\n *,\n mask_zeros: bool = True,\n) -> ma.MaskedArray:\n \"\"\"Rebins 1D array.\n\n Args:\n x_in: 1-D array with shape (n,).\n array: 1-D input data with shape (m,).\n x_new: 1-D target vector (center points) with shape (N,).\n statistic: Statistic to be calculated. Possible statistics are 'mean', 'std'.\n Default is 'mean'.\n mask_zeros: Whether to mask 0 values in the returned array. Default is True.\n\n Returns:\n Re-binned data with shape (N,).\n\n \"\"\"\n edges = binvec(x_new)\n result = np.zeros(len(x_new))\n array_screened = ma.masked_invalid(array, copy=True) # data may contain nan-values\n mask = ~array_screened.mask\n if ma.any(array_screened[mask]):\n result, _, _ = stats.binned_statistic(\n x_in[mask],\n array_screened[mask],\n statistic=statistic,\n bins=edges,\n )\n result[~np.isfinite(result)] = 0\n if mask_zeros:\n return ma.masked_equal(result, 0)\n return ma.array(result)"}, {"class_start_lineno": 1, "class_end_lineno": 1151, "func_start_lineno": 143, "func_end_lineno": 192, "func_code": "def rebin_2d(\n x_in: np.ndarray,\n array: ma.MaskedArray,\n x_new: np.ndarray,\n statistic: Literal[\"mean\", \"std\"] = \"mean\",\n n_min: int = 1,\n *,\n mask_zeros: bool = True,\n) -> tuple[ma.MaskedArray, list]:\n \"\"\"Rebins 2-D data in one dimension.\n\n Args:\n x_in: 1-D array with shape (n,).\n array: 2-D input data with shape (n, m).\n x_new: 1-D target vector (center points) with shape (N,).\n statistic: Statistic to be calculated. Possible statistics are 'mean', 'std'.\n Default is 'mean'.\n n_min: Minimum number of points to have good statistics in a bin. Default is 1.\n mask_zeros: Whether to mask 0 values in the returned array. Default is True.\n\n Returns:\n tuple: Rebinned data with shape (N, m) and indices of bins without enough data.\n \"\"\"\n edges = binvec(x_new)\n result = np.zeros((len(x_new), array.shape[1]))\n array_screened = ma.masked_invalid(array, copy=True) # data may contain nan-values\n for ind, values in enumerate(array_screened.T):\n mask = ~values.mask\n if ma.any(values[mask]):\n result[:, ind], _, _ = stats.binned_statistic(\n x_in[mask],\n values[mask],\n statistic=statistic,\n bins=edges,\n )\n result[~np.isfinite(result)] = 0\n if mask_zeros is True:\n masked_result = ma.masked_equal(result, 0)\n else:\n masked_result = ma.array(result)\n\n # Fill bins with not enough profiles\n x_hist, _ = np.histogram(x_in, bins=edges)\n empty_mask = x_hist < n_min\n masked_result[empty_mask, :] = ma.masked\n empty_indices = list(np.nonzero(empty_mask)[0])\n if len(empty_indices) > 0:\n logging.debug(\"No data in %s bins\", len(empty_indices))\n\n return masked_result, empty_indices"}, {"class_start_lineno": 14, "class_end_lineno": 211, "func_start_lineno": 61, "func_end_lineno": 84, "func_code": " def rebin_data(\n self, time: np.ndarray, time_new: np.ndarray, *, mask_zeros: bool = True\n ) -> list:\n \"\"\"Rebins `data` in time.\n\n Args:\n time: 1D time array.\n time_new: 1D new time array.\n mask_zeros: Whether to mask 0 values in the returned array. Default is True.\n\n Returns:\n Time indices without data.\n\n \"\"\"\n if self.data.ndim == 1:\n self.data = utils.rebin_1d(time, self.data, time_new, mask_zeros=mask_zeros)\n bad_indices = list(np.where(self.data == ma.masked)[0])\n else:\n if not isinstance(self.data, ma.MaskedArray):\n self.data = ma.masked_array(self.data)\n self.data, bad_indices = utils.rebin_2d(\n time, self.data, time_new, mask_zeros=mask_zeros\n )\n return bad_indices"}], "type": ["function_empty"], "node": ["cloudnetpy.utils.binvec", "cloudnetpy.utils.rebin_1d", "cloudnetpy.utils.rebin_2d", "cloudnetpy.cloudnetarray.CloudnetArray.rebin_data"], "language": "Python", "toolfunc_count": 4, "func_count": 4, "pytest_info": {"total_num": 4, "base_passed_num": 0}} {"id": ["cloudnetpy.cloudnetpy.utils.binvec", "cloudnetpy.cloudnetpy.utils.rebin_2d", "cloudnetpy.cloudnetpy.cloudnetarray.CloudnetArray::rebin_data"], "project": "cloudnetpy", "origin_file": ["cloudnetpy/utils.py", "cloudnetpy/utils.py", "cloudnetpy/cloudnetarray.py"], "test_list": ["tests/unit/test_cloudnetarray.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 1151, "func_start_lineno": 124, "func_end_lineno": 140, "func_code": "def binvec(x: np.ndarray | list) -> np.ndarray:\n \"\"\"Converts 1-D center points to bins with even spacing.\n\n Args:\n x: 1-D array of N real values.\n\n Returns:\n ndarray: N + 1 edge values.\n\n Examples:\n >>> binvec([1, 2, 3])\n [0.5, 1.5, 2.5, 3.5]\n\n \"\"\"\n edge1 = x[0] - (x[1] - x[0]) / 2\n edge2 = x[-1] + (x[-1] - x[-2]) / 2\n return np.linspace(edge1, edge2, len(x) + 1)"}, {"class_start_lineno": 1, "class_end_lineno": 1151, "func_start_lineno": 143, "func_end_lineno": 192, "func_code": "def rebin_2d(\n x_in: np.ndarray,\n array: ma.MaskedArray,\n x_new: np.ndarray,\n statistic: Literal[\"mean\", \"std\"] = \"mean\",\n n_min: int = 1,\n *,\n mask_zeros: bool = True,\n) -> tuple[ma.MaskedArray, list]:\n \"\"\"Rebins 2-D data in one dimension.\n\n Args:\n x_in: 1-D array with shape (n,).\n array: 2-D input data with shape (n, m).\n x_new: 1-D target vector (center points) with shape (N,).\n statistic: Statistic to be calculated. Possible statistics are 'mean', 'std'.\n Default is 'mean'.\n n_min: Minimum number of points to have good statistics in a bin. Default is 1.\n mask_zeros: Whether to mask 0 values in the returned array. Default is True.\n\n Returns:\n tuple: Rebinned data with shape (N, m) and indices of bins without enough data.\n \"\"\"\n edges = binvec(x_new)\n result = np.zeros((len(x_new), array.shape[1]))\n array_screened = ma.masked_invalid(array, copy=True) # data may contain nan-values\n for ind, values in enumerate(array_screened.T):\n mask = ~values.mask\n if ma.any(values[mask]):\n result[:, ind], _, _ = stats.binned_statistic(\n x_in[mask],\n values[mask],\n statistic=statistic,\n bins=edges,\n )\n result[~np.isfinite(result)] = 0\n if mask_zeros is True:\n masked_result = ma.masked_equal(result, 0)\n else:\n masked_result = ma.array(result)\n\n # Fill bins with not enough profiles\n x_hist, _ = np.histogram(x_in, bins=edges)\n empty_mask = x_hist < n_min\n masked_result[empty_mask, :] = ma.masked\n empty_indices = list(np.nonzero(empty_mask)[0])\n if len(empty_indices) > 0:\n logging.debug(\"No data in %s bins\", len(empty_indices))\n\n return masked_result, empty_indices"}, {"class_start_lineno": 14, "class_end_lineno": 211, "func_start_lineno": 61, "func_end_lineno": 84, "func_code": " def rebin_data(\n self, time: np.ndarray, time_new: np.ndarray, *, mask_zeros: bool = True\n ) -> list:\n \"\"\"Rebins `data` in time.\n\n Args:\n time: 1D time array.\n time_new: 1D new time array.\n mask_zeros: Whether to mask 0 values in the returned array. Default is True.\n\n Returns:\n Time indices without data.\n\n \"\"\"\n if self.data.ndim == 1:\n self.data = utils.rebin_1d(time, self.data, time_new, mask_zeros=mask_zeros)\n bad_indices = list(np.where(self.data == ma.masked)[0])\n else:\n if not isinstance(self.data, ma.MaskedArray):\n self.data = ma.masked_array(self.data)\n self.data, bad_indices = utils.rebin_2d(\n time, self.data, time_new, mask_zeros=mask_zeros\n )\n return bad_indices"}], "type": ["function_empty"], "node": ["cloudnetpy.utils.binvec", "cloudnetpy.utils.rebin_2d", "cloudnetpy.cloudnetarray.CloudnetArray.rebin_data"], "language": "Python", "toolfunc_count": 3, "func_count": 3, "pytest_info": {"total_num": 17, "base_passed_num": 15}} {"id": ["cloudnetpy.cloudnetpy.concat_lib._Concat::_write_initial_data", "cloudnetpy.cloudnetpy.concat_lib._Concat::concat_data"], "project": "cloudnetpy", "origin_file": ["cloudnetpy/concat_lib.py", "cloudnetpy/concat_lib.py"], "test_list": ["tests/unit/test_concat_lib.py", "tests/unit/test_copernicus.py", "tests/unit/test_galileo.py", "tests/unit/test_mira.py"], "prob_info": [{"class_start_lineno": 122, "class_end_lineno": 253, "func_start_lineno": 173, "func_end_lineno": 202, "func_code": " def _write_initial_data(self, variables: list | None, ignore: list | None) -> None:\n for key in self.first_file.variables:\n if (\n variables is not None\n and key not in variables\n and key not in self.common_variables\n and key != self.concat_dimension\n ):\n continue\n if ignore and key in ignore:\n continue\n\n auto_scale = False\n self.first_file[key].set_auto_scale(auto_scale)\n array = self.first_file[key][:]\n dimensions = self.first_file[key].dimensions\n fill_value = getattr(self.first_file[key], \"_FillValue\", None)\n var = self.concatenated_file.createVariable(\n key,\n array.dtype,\n dimensions,\n zlib=True,\n complevel=3,\n shuffle=False,\n fill_value=fill_value,\n )\n auto_scale = False\n var.set_auto_scale(auto_scale)\n var[:] = array\n _copy_attributes(self.first_file[key], var)"}, {"class_start_lineno": 122, "class_end_lineno": 253, "func_start_lineno": 151, "func_end_lineno": 171, "func_code": " def concat_data(\n self,\n variables: list | None,\n ignore: list | None,\n allow_vary: list | None,\n ) -> list:\n \"\"\"Concatenates data arrays.\"\"\"\n self._write_initial_data(variables, ignore)\n output = [self.first_filename]\n if len(self.filenames) > 1:\n for filename in self.filenames[1:]:\n try:\n self._append_data(filename, allow_vary)\n except RuntimeError as e:\n if \"NetCDF: HDF error\" in str(e):\n msg = f\"Caught a NetCDF HDF error. Skipping file '{filename}'.\"\n logging.exception(msg)\n continue\n raise\n output.append(filename)\n return output"}], "type": ["Development"], "node": ["cloudnetpy.concat_lib._Concat._write_initial_data", "cloudnetpy.concat_lib._Concat.concat_data"], "language": "Python", "toolfunc_count": 0, "func_count": 2, "pytest_info": {"total_num": 71, "base_passed_num": 32}} {"id": ["cloudnetpy.cloudnetpy.datasource.DataSource::getvar", "cloudnetpy.cloudnetpy.datasource.DataSource::_init_time"], "project": "cloudnetpy", "origin_file": ["cloudnetpy/datasource.py", "cloudnetpy/datasource.py"], "test_list": ["tests/unit/test_datasource.py"], "prob_info": [{"class_start_lineno": 16, "class_end_lineno": 236, "func_start_lineno": 60, "func_end_lineno": 80, "func_code": " def getvar(self, *args) -> np.ndarray:\n \"\"\"Returns data array from the source file variables.\n\n Returns just the data (and no attributes) from the original\n variables dictionary, fetched from the input netCDF file.\n\n Args:\n *args: possible names of the variable. The first match is returned.\n\n Returns:\n ndarray: The actual data.\n\n Raises:\n RuntimeError: The variable is not found.\n\n \"\"\"\n for arg in args:\n if arg in self.dataset.variables:\n return self.dataset.variables[arg][:]\n msg = f\"Missing variable {args[0]} in the input file.\"\n raise RuntimeError(msg)"}, {"class_start_lineno": 16, "class_end_lineno": 236, "func_start_lineno": 152, "func_end_lineno": 160, "func_code": " def _init_time(self) -> np.ndarray:\n time = self.getvar(\"time\")\n if len(time) == 0:\n msg = \"Empty time vector\"\n raise ValidTimeStampError(msg)\n if max(time) > 25:\n logging.debug(\"Assuming time as seconds, converting to fraction hour\")\n time = utils.seconds2hours(time)\n return time"}], "type": ["function_empty", "Development"], "node": ["cloudnetpy.datasource.DataSource.getvar", "cloudnetpy.datasource.DataSource._init_time"], "language": "Python", "toolfunc_count": 1, "func_count": 2, "pytest_info": {"total_num": 9, "base_passed_num": 6}} {"id": ["cloudnetpy.cloudnetpy.instruments.disdrometer.parsivel._read_fmi", "cloudnetpy.cloudnetpy.instruments.disdrometer.parsivel.parsivel2nc"], "project": "cloudnetpy", "origin_file": ["cloudnetpy/instruments/disdrometer/parsivel.py", "cloudnetpy/instruments/disdrometer/parsivel.py"], "test_list": ["tests/unit/test_disdrometer.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 713, "func_start_lineno": 618, "func_end_lineno": 657, "func_code": "def _read_fmi(content: str):\n r\"\"\"Read format used by Finnish Meteorological Institute and University of\n Helsinki.\n\n Format consists of sequence of the following:\n - \"[YYYY-MM-DD HH:MM:SS\\n\"\n - output of \"CS/PA\" command without non-printable characters at the end\n - \"]\\n\"\n \"\"\"\n output: dict[str, list] = {\"_datetime\": []}\n for m in re.finditer(\n r\"\\[(?P\\d+)-(?P\\d+)-(?P\\d+) \"\n r\"(?P\\d+):(?P\\d+):(?P\\d+)\"\n r\"(?P[^\\]]*)\\]\",\n content,\n ):\n try:\n record = _read_typ_op4a(m[\"output\"].splitlines())\n except ValueError:\n continue\n\n for key, value in record.items():\n if key not in output:\n output[key] = [None] * len(output[\"_datetime\"])\n output[key].append(value)\n for key in output:\n if key not in record and key != \"_datetime\":\n output[key].append(None)\n\n output[\"_datetime\"].append(\n datetime.datetime(\n int(m[\"year\"]),\n int(m[\"month\"]),\n int(m[\"day\"]),\n int(m[\"hour\"]),\n int(m[\"minute\"]),\n int(m[\"second\"]),\n )\n )\n return output"}, {"class_start_lineno": 1, "class_end_lineno": 713, "func_start_lineno": 23, "func_end_lineno": 77, "func_code": "def parsivel2nc(\n disdrometer_file: str | PathLike | Iterable[str | PathLike],\n output_file: str,\n site_meta: dict,\n uuid: str | None = None,\n date: str | datetime.date | None = None,\n telegram: Sequence[int | None] | None = None,\n timestamps: Sequence[datetime.datetime] | None = None,\n) -> str:\n \"\"\"Converts OTT Parsivel-2 disdrometer data into Cloudnet Level 1b netCDF\n file.\n\n Args:\n disdrometer_file: Filename of disdrometer file or list of filenames.\n output_file: Output filename.\n site_meta: Dictionary containing information about the site. Required key\n is `name`.\n uuid: Set specific UUID for the file.\n date: Expected date of the measurements as YYYY-MM-DD.\n telegram: List of measured value numbers as specified in section 11.2 of\n the instrument's operating instructions. Unknown values are indicated\n with None. Telegram is required if the input file doesn't contain a\n header.\n timestamps: Specify list of timestamps if they are missing in the input file.\n\n Returns:\n UUID of the generated file.\n\n Raises:\n DisdrometerDataError: Timestamps do not match the expected date, or unable\n to read the disdrometer file.\n\n Examples:\n >>> from cloudnetpy.instruments import parsivel2nc\n >>> site_meta = {'name': 'Lindenberg', 'altitude': 104, 'latitude': 52.2,\n 'longitude': 14.1}\n >>> uuid = parsivel2nc('parsivel.log', 'parsivel.nc', site_meta)\n\n \"\"\"\n if isinstance(date, str):\n date = datetime.date.fromisoformat(date)\n if isinstance(disdrometer_file, str | PathLike):\n disdrometer_file = [disdrometer_file]\n disdrometer = Parsivel(disdrometer_file, site_meta, telegram, date, timestamps)\n disdrometer.sort_timestamps()\n disdrometer.remove_duplicate_timestamps()\n disdrometer.mask_invalid_values()\n if len(disdrometer.data[\"time\"].data) < 2:\n msg = \"Too few data points\"\n raise DisdrometerDataError(msg)\n disdrometer.convert_units()\n disdrometer.add_meta()\n attributes = output.add_time_attribute(ATTRIBUTES, disdrometer.date)\n output.update_attributes(disdrometer.data, attributes)\n return output.save_level1b(disdrometer, output_file, uuid)"}], "type": ["function_empty"], "node": ["cloudnetpy.instruments.disdrometer.parsivel._read_fmi", "cloudnetpy.instruments.disdrometer.parsivel.parsivel2nc"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 54, "base_passed_num": 0}} {"id": ["cloudnetpy.cloudnetpy.utils.l2norm_weighted", "cloudnetpy.cloudnetpy.products.drizzle_error._calc_error"], "project": "cloudnetpy", "origin_file": ["cloudnetpy/utils.py", "cloudnetpy/products/drizzle_error.py"], "test_list": ["tests/unit/test_drizzle.py", "tests/unit/test_drizzle_error.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 1151, "func_start_lineno": 504, "func_end_lineno": 529, "func_code": "def l2norm_weighted(\n values: tuple,\n overall_scale: float,\n term_weights: tuple,\n) -> ma.MaskedArray:\n \"\"\"Calculates scaled and weighted Euclidean distance.\n\n Calculated distance is of form: scale * sqrt((a1*a)**2 + (b1*b)**2 + ...)\n where a, b, ... are terms to be summed and a1, a2, ... are optional weights\n for the terms.\n\n Args:\n values: Tuple containing the values.\n overall_scale: Scale factor for the calculated Euclidean distance.\n term_weights: Weights for the terms. Must be single float or a list of numbers\n (one per term).\n\n Returns:\n Scaled and weighted Euclidean distance.\n\n TODO: Use masked arrays instead of tuples.\n\n \"\"\"\n generic_values = ma.array(values, dtype=object)\n weighted_values = ma.multiply(generic_values, term_weights)\n return overall_scale * l2norm(*weighted_values)"}, {"class_start_lineno": 1, "class_end_lineno": 188, "func_start_lineno": 140, "func_end_lineno": 153, "func_code": "def _calc_error(\n scale: float,\n weights: tuple,\n error_input: tuple,\n *,\n add_mu: bool = False,\n add_mu_small: bool = False,\n) -> ma.MaskedArray:\n error = utils.l2norm_weighted(error_input, scale, weights)\n if add_mu is True:\n error = utils.l2norm(error, MU_ERROR)\n if add_mu_small is True:\n error = utils.l2norm(error, MU_ERROR_SMALL)\n return error"}], "type": ["function_empty", "Development"], "node": ["cloudnetpy.utils.l2norm_weighted", "cloudnetpy.products.drizzle_error._calc_error"], "language": "Python", "toolfunc_count": 1, "func_count": 2, "pytest_info": {"total_num": 103, "base_passed_num": 70}} {"id": ["cloudnetpy.cloudnetpy.categorize.droplet.interpolate_lwp", "cloudnetpy.cloudnetpy.categorize.droplet.find_liquid"], "project": "cloudnetpy", "origin_file": ["cloudnetpy/categorize/droplet.py", "cloudnetpy/categorize/droplet.py"], "test_list": ["tests/unit/test_droplet.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 245, "func_start_lineno": 225, "func_end_lineno": 238, "func_code": "def interpolate_lwp(obs: ClassData) -> np.ndarray:\n \"\"\"Linear interpolation of liquid water path to fill masked values.\n\n Args:\n obs: The :class:`ClassData` instance.\n\n Returns:\n Liquid water path where the masked values are filled by interpolation.\n\n \"\"\"\n if obs.lwp.all() is ma.masked:\n return np.zeros(obs.time.shape)\n ind = ma.where(obs.lwp)\n return np.interp(obs.time, obs.time[ind], obs.lwp[ind])"}, {"class_start_lineno": 1, "class_end_lineno": 245, "func_start_lineno": 52, "func_end_lineno": 121, "func_code": "def find_liquid(\n obs: ClassData,\n peak_amp: float = 1e-6,\n max_width: float = 300,\n min_points: int = 3,\n min_top_der: float = 1e-7,\n min_lwp: float = 0,\n min_alt: float = 100,\n) -> np.ndarray:\n \"\"\"Estimate liquid layers from SNR-screened attenuated backscatter.\n\n Args:\n obs: The :class:`ClassData` instance.\n peak_amp: Minimum value of peak. Default is 1e-6.\n max_width: Maximum width of peak. Default is 300 (m).\n min_points: Minimum number of valid points in peak. Default is 3.\n min_top_der: Minimum derivative above peak, defined as\n (beta_peak-beta_top) / (alt_top-alt_peak). Default is 1e-7.\n min_lwp: Minimum value from linearly interpolated lwp (kg m-2)\n measured by the mwr. Default is 0.\n min_alt: Minimum altitude of the peak from the ground. Default is 100 (m).\n\n Returns:\n 2-D boolean array denoting liquid layers.\n\n References:\n The method is based on Tuononen, M. et.al, 2019,\n https://acp.copernicus.org/articles/19/1985/2019/.\n\n \"\"\"\n\n def _is_proper_peak() -> bool:\n conditions = (\n npoints >= min_points,\n peak_width < max_width,\n top_der > min_top_der,\n is_positive_lwp,\n peak_alt > min_alt,\n )\n return all(conditions)\n\n lwp_int = interpolate_lwp(obs)\n beta = ma.copy(obs.beta)\n height = obs.height\n\n is_liquid = np.zeros(beta.shape, dtype=bool)\n base_below_peak = utils.n_elements(height, 200)\n top_above_peak = utils.n_elements(height, 150)\n difference = ma.array(np.diff(beta, axis=1))\n beta_diff = difference.filled(0)\n beta = beta.filled(0)\n peak_indices = _find_strong_peaks(beta, peak_amp)\n\n for n, peak in zip(*peak_indices, strict=True):\n lprof = beta[n, :]\n dprof = beta_diff[n, :]\n try:\n base = ind_base(dprof, peak, base_below_peak, 4)\n top = ind_top(dprof, peak, height.shape[0], top_above_peak, 4)\n except IndexError:\n continue\n npoints = np.count_nonzero(lprof[base : top + 1])\n peak_width = height[top] - height[base]\n peak_alt = height[peak] - height[0]\n top_der = (lprof[peak] - lprof[top]) / (height[top] - height[peak])\n is_positive_lwp = lwp_int[n] >= min_lwp\n if _is_proper_peak():\n is_liquid[n, base : top + 1] = True\n\n return is_liquid"}], "type": ["function_empty", "Development"], "node": ["cloudnetpy.categorize.droplet.interpolate_lwp", "cloudnetpy.categorize.droplet.find_liquid"], "language": "Python", "toolfunc_count": 1, "func_count": 2, "pytest_info": {"total_num": 18, "base_passed_num": 15}} {"id": ["cloudnetpy.cloudnetpy.categorize.atmos_utils.fill_clouds_with_lwc_dz", "cloudnetpy.cloudnetpy.products.lwc.Lwc::_init_lwc_adiabatic", "cloudnetpy.cloudnetpy.categorize.atmos_utils.calc_saturation_vapor_pressure", "cloudnetpy.cloudnetpy.categorize.atmos_utils.calc_mixing_ratio", "cloudnetpy.cloudnetpy.categorize.atmos_utils.calc_lwc_change_rate"], "project": "cloudnetpy", "origin_file": ["cloudnetpy/categorize/atmos_utils.py", "cloudnetpy/products/lwc.py", "cloudnetpy/products/lwc.py", "cloudnetpy/categorize/atmos_utils.py", "cloudnetpy/categorize/atmos_utils.py", "cloudnetpy/categorize/atmos_utils.py"], "test_list": ["tests/unit/test_lwc.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 357, "func_start_lineno": 154, "func_end_lineno": 172, "func_code": "def fill_clouds_with_lwc_dz(\n temperature: np.ndarray, pressure: np.ndarray, is_liquid: np.ndarray\n) -> np.ndarray:\n \"\"\"Fills liquid clouds with lwc change rate at the cloud bases.\n\n Args:\n temperature: 2D temperature array (K).\n pressure: 2D pressure array (Pa).\n is_liquid: Boolean array indicating presence of liquid clouds.\n\n Returns:\n Liquid water content change rate (kg m-3 m-1), so that for each cloud the base\n value is filled for the whole cloud.\n\n \"\"\"\n lwc_dz = get_lwc_change_rate_at_bases(temperature, pressure, is_liquid)\n lwc_dz_filled = ma.zeros(lwc_dz.shape)\n lwc_dz_filled[is_liquid] = utils.ffill(lwc_dz[is_liquid])\n return lwc_dz_filled"}, {"class_start_lineno": 120, "class_end_lineno": 167, "func_start_lineno": 146, "func_end_lineno": 152, "func_code": " def _init_lwc_adiabatic(self) -> np.ndarray:\n \"\"\"Returns theoretical adiabatic lwc in liquid clouds (kg/m3).\"\"\"\n lwc_dz = atmos_utils.fill_clouds_with_lwc_dz(\n *self.lwc_source.atmosphere,\n self.is_liquid,\n )\n return atmos_utils.calc_adiabatic_lwc(lwc_dz, self.height)"}, {"class_start_lineno": 120, "class_end_lineno": 167, "func_start_lineno": 134, "func_end_lineno": 140, "func_code": " def __init__(self, lwc_source: LwcSource):\n self.lwc_source = lwc_source\n self.height = lwc_source.getvar(\"height\")\n self.is_liquid = self._get_liquid()\n self.lwc_adiabatic = self._init_lwc_adiabatic()\n self.lwc = self._adiabatic_lwc_to_lwc()\n self._mask_rain()"}, {"class_start_lineno": 1, "class_end_lineno": 357, "func_start_lineno": 245, "func_end_lineno": 266, "func_code": "def calc_saturation_vapor_pressure(temperature: np.ndarray) -> np.ndarray:\n \"\"\"Goff-Gratch formula for saturation vapor pressure over water adopted by WMO.\n\n Args:\n temperature: Temperature (K).\n\n Returns:\n Saturation vapor pressure (Pa).\n\n \"\"\"\n ratio = con.T0 / temperature\n inv_ratio = ratio**-1\n return (\n 10\n ** (\n 10.79574 * (1 - ratio)\n - 5.028 * np.log10(inv_ratio)\n + 1.50475e-4 * (1 - (10 ** (-8.2969 * (inv_ratio - 1))))\n + 0.42873e-3 * (10 ** (4.76955 * (1 - ratio)) - 1)\n + 0.78614\n )\n ) * con.HPA_TO_PA"}, {"class_start_lineno": 1, "class_end_lineno": 357, "func_start_lineno": 269, "func_end_lineno": 280, "func_code": "def calc_mixing_ratio(vapor_pressure: np.ndarray, pressure: np.ndarray) -> np.ndarray:\n \"\"\"Calculates mixing ratio from partial vapor pressure and pressure.\n\n Args:\n vapor_pressure: Partial pressure of water vapor (Pa).\n pressure: Atmospheric pressure (Pa).\n\n Returns:\n Mixing ratio (kg kg-1).\n\n \"\"\"\n return con.MW_RATIO * vapor_pressure / (pressure - vapor_pressure)"}, {"class_start_lineno": 1, "class_end_lineno": 357, "func_start_lineno": 201, "func_end_lineno": 242, "func_code": "def calc_lwc_change_rate(temperature: np.ndarray, pressure: np.ndarray) -> np.ndarray:\n \"\"\"Returns rate of change of condensable water (LWC).\n\n Calculates the theoretical adiabatic rate of increase of LWC\n with height, given the cloud base temperature and pressure.\n\n Args:\n temperature: Temperature of cloud base (K).\n pressure: Pressure of cloud base (Pa).\n\n Returns:\n dlwc/dz (kg m-3 m-1)\n\n References:\n Brenguier, 1991, https://doi.org/10.1175/1520-0469(1991)048<0264:POTCPA>2.0.CO;2\n\n \"\"\"\n svp = calc_saturation_vapor_pressure(temperature)\n svp_mixing_ratio = calc_mixing_ratio(svp, pressure)\n air_density = calc_air_density(pressure, temperature, svp_mixing_ratio)\n\n e = 0.622\n Cp = 1004 # J kg-1 K-1\n Lv = 2.45e6 # J kg-1 = Pa m3 kg-1\n qs = svp_mixing_ratio # kg kg-1\n pa = air_density # kg m-3\n es = svp # Pa\n P = pressure # Pa\n T = temperature # K\n\n # See Appendix B in Brenguier (1991) for the derivation of the following equation\n dqs_dp = (\n -(1 - (Cp * T) / (e * Lv))\n * (((Cp * T) / (e * Lv)) + ((Lv * qs * pa) / (P - es))) ** -1\n * (e * es)\n * (P - es) ** -2\n )\n\n # Using hydrostatic equation to convert dqs_dp to dqs_dz\n dqs_dz = dqs_dp * air_density * -scipy.constants.g\n\n return dqs_dz * air_density"}], "type": ["function_empty", "Development"], "node": ["cloudnetpy.categorize.atmos_utils.fill_clouds_with_lwc_dz", "cloudnetpy.products.lwc.Lwc._init_lwc_adiabatic", "cloudnetpy.products.lwc.Lwc.__init__", "cloudnetpy.categorize.atmos_utils.calc_saturation_vapor_pressure", "cloudnetpy.categorize.atmos_utils.calc_mixing_ratio", "cloudnetpy.categorize.atmos_utils.calc_lwc_change_rate"], "language": "Python", "toolfunc_count": 3, "func_count": 5, "pytest_info": {"total_num": 37, "base_passed_num": 0}} {"id": ["cloudnetpy.cloudnetpy.utils.rebin_1d", "cloudnetpy.cloudnetpy.cloudnetarray.CloudnetArray::rebin_data", "cloudnetpy.cloudnetpy.utils.binvec"], "project": "cloudnetpy", "origin_file": ["cloudnetpy/utils.py", "cloudnetpy/cloudnetarray.py", "cloudnetpy/categorize/mwr.py", "cloudnetpy/utils.py"], "test_list": ["tests/unit/test_mwr.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 1151, "func_start_lineno": 195, "func_end_lineno": 231, "func_code": "def rebin_1d(\n x_in: np.ndarray,\n array: np.ndarray | ma.MaskedArray,\n x_new: np.ndarray,\n statistic: str = \"mean\",\n *,\n mask_zeros: bool = True,\n) -> ma.MaskedArray:\n \"\"\"Rebins 1D array.\n\n Args:\n x_in: 1-D array with shape (n,).\n array: 1-D input data with shape (m,).\n x_new: 1-D target vector (center points) with shape (N,).\n statistic: Statistic to be calculated. Possible statistics are 'mean', 'std'.\n Default is 'mean'.\n mask_zeros: Whether to mask 0 values in the returned array. Default is True.\n\n Returns:\n Re-binned data with shape (N,).\n\n \"\"\"\n edges = binvec(x_new)\n result = np.zeros(len(x_new))\n array_screened = ma.masked_invalid(array, copy=True) # data may contain nan-values\n mask = ~array_screened.mask\n if ma.any(array_screened[mask]):\n result, _, _ = stats.binned_statistic(\n x_in[mask],\n array_screened[mask],\n statistic=statistic,\n bins=edges,\n )\n result[~np.isfinite(result)] = 0\n if mask_zeros:\n return ma.masked_equal(result, 0)\n return ma.array(result)"}, {"class_start_lineno": 14, "class_end_lineno": 211, "func_start_lineno": 61, "func_end_lineno": 84, "func_code": " def rebin_data(\n self, time: np.ndarray, time_new: np.ndarray, *, mask_zeros: bool = True\n ) -> list:\n \"\"\"Rebins `data` in time.\n\n Args:\n time: 1D time array.\n time_new: 1D new time array.\n mask_zeros: Whether to mask 0 values in the returned array. Default is True.\n\n Returns:\n Time indices without data.\n\n \"\"\"\n if self.data.ndim == 1:\n self.data = utils.rebin_1d(time, self.data, time_new, mask_zeros=mask_zeros)\n bad_indices = list(np.where(self.data == ma.masked)[0])\n else:\n if not isinstance(self.data, ma.MaskedArray):\n self.data = ma.masked_array(self.data)\n self.data, bad_indices = utils.rebin_2d(\n time, self.data, time_new, mask_zeros=mask_zeros\n )\n return bad_indices"}, {"class_start_lineno": 11, "class_end_lineno": 50, "func_start_lineno": 24, "func_end_lineno": 32, "func_code": " def rebin_to_grid(self, time_grid: np.ndarray) -> None:\n \"\"\"Approximates lwp and its error in a grid using mean.\n\n Args:\n time_grid: 1D target time grid.\n\n \"\"\"\n for array in self.data.values():\n array.rebin_data(self.time, time_grid)"}, {"class_start_lineno": 1, "class_end_lineno": 1151, "func_start_lineno": 124, "func_end_lineno": 140, "func_code": "def binvec(x: np.ndarray | list) -> np.ndarray:\n \"\"\"Converts 1-D center points to bins with even spacing.\n\n Args:\n x: 1-D array of N real values.\n\n Returns:\n ndarray: N + 1 edge values.\n\n Examples:\n >>> binvec([1, 2, 3])\n [0.5, 1.5, 2.5, 3.5]\n\n \"\"\"\n edge1 = x[0] - (x[1] - x[0]) / 2\n edge2 = x[-1] + (x[-1] - x[-2]) / 2\n return np.linspace(edge1, edge2, len(x) + 1)"}], "type": ["function_empty"], "node": ["cloudnetpy.utils.rebin_1d", "cloudnetpy.cloudnetarray.CloudnetArray.rebin_data", "cloudnetpy.categorize.mwr.Mwr.rebin_to_grid", "cloudnetpy.utils.binvec"], "language": "Python", "toolfunc_count": 3, "func_count": 3, "pytest_info": {"total_num": 4, "base_passed_num": 3}} {"id": ["cloudnetpy.cloudnetpy.utils.append_data", "cloudnetpy.cloudnetpy.instruments.radiometrics.RadiometricsCombined::__init__"], "project": "cloudnetpy", "origin_file": ["cloudnetpy/utils.py", "cloudnetpy/instruments/radiometrics.py"], "test_list": ["tests/unit/test_radiometrics.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 1151, "func_start_lineno": 911, "func_end_lineno": 925, "func_code": "def append_data(data_in: dict, key: str, array: np.ndarray) -> dict:\n \"\"\"Appends data to a dictionary field (creates the field if not yet present).\n\n Args:\n data_in: Dictionary where data will be appended.\n key: Key of the field.\n array: Numpy array to be appended to data_in[key].\n\n \"\"\"\n data = data_in.copy()\n if key not in data:\n data[key] = array\n else:\n data[key] = ma.concatenate((data[key], array))\n return data"}, {"class_start_lineno": 227, "class_end_lineno": 289, "func_start_lineno": 233, "func_end_lineno": 246, "func_code": " def __init__(self, objs: list[Radiometrics], site_meta: dict):\n self.site_meta = site_meta\n self.data = {}\n self.date = None\n for obj in objs:\n if obj.ranges != objs[0].ranges:\n msg = \"Inconsistent range between files\"\n raise InconsistentDataError(msg)\n for key in obj.data:\n self.data = utils.append_data(self.data, key, obj.data[key])\n ranges = [float(x) for x in objs[0].ranges]\n self.data[\"range\"] = np.array(ranges) * 1000 # m => km\n self.data[\"height\"] = self.data[\"range\"] + self.site_meta[\"altitude\"]\n self.instrument = instruments.RADIOMETRICS"}], "type": ["function_empty", "Development"], "node": ["cloudnetpy.utils.append_data", "cloudnetpy.instruments.radiometrics.RadiometricsCombined.__init__"], "language": "Python", "toolfunc_count": 1, "func_count": 2, "pytest_info": {"total_num": 17, "base_passed_num": 0}} {"id": ["cloudnetpy.cloudnetpy.utils.binvec", "cloudnetpy.cloudnetpy.utils.rebin_2d", "cloudnetpy.cloudnetpy.utils.rebin_1d"], "project": "cloudnetpy", "origin_file": ["cloudnetpy/utils.py", "cloudnetpy/utils.py", "cloudnetpy/utils.py"], "test_list": ["tests/unit/test_utils.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 1151, "func_start_lineno": 124, "func_end_lineno": 140, "func_code": "def binvec(x: np.ndarray | list) -> np.ndarray:\n \"\"\"Converts 1-D center points to bins with even spacing.\n\n Args:\n x: 1-D array of N real values.\n\n Returns:\n ndarray: N + 1 edge values.\n\n Examples:\n >>> binvec([1, 2, 3])\n [0.5, 1.5, 2.5, 3.5]\n\n \"\"\"\n edge1 = x[0] - (x[1] - x[0]) / 2\n edge2 = x[-1] + (x[-1] - x[-2]) / 2\n return np.linspace(edge1, edge2, len(x) + 1)"}, {"class_start_lineno": 1, "class_end_lineno": 1151, "func_start_lineno": 143, "func_end_lineno": 192, "func_code": "def rebin_2d(\n x_in: np.ndarray,\n array: ma.MaskedArray,\n x_new: np.ndarray,\n statistic: Literal[\"mean\", \"std\"] = \"mean\",\n n_min: int = 1,\n *,\n mask_zeros: bool = True,\n) -> tuple[ma.MaskedArray, list]:\n \"\"\"Rebins 2-D data in one dimension.\n\n Args:\n x_in: 1-D array with shape (n,).\n array: 2-D input data with shape (n, m).\n x_new: 1-D target vector (center points) with shape (N,).\n statistic: Statistic to be calculated. Possible statistics are 'mean', 'std'.\n Default is 'mean'.\n n_min: Minimum number of points to have good statistics in a bin. Default is 1.\n mask_zeros: Whether to mask 0 values in the returned array. Default is True.\n\n Returns:\n tuple: Rebinned data with shape (N, m) and indices of bins without enough data.\n \"\"\"\n edges = binvec(x_new)\n result = np.zeros((len(x_new), array.shape[1]))\n array_screened = ma.masked_invalid(array, copy=True) # data may contain nan-values\n for ind, values in enumerate(array_screened.T):\n mask = ~values.mask\n if ma.any(values[mask]):\n result[:, ind], _, _ = stats.binned_statistic(\n x_in[mask],\n values[mask],\n statistic=statistic,\n bins=edges,\n )\n result[~np.isfinite(result)] = 0\n if mask_zeros is True:\n masked_result = ma.masked_equal(result, 0)\n else:\n masked_result = ma.array(result)\n\n # Fill bins with not enough profiles\n x_hist, _ = np.histogram(x_in, bins=edges)\n empty_mask = x_hist < n_min\n masked_result[empty_mask, :] = ma.masked\n empty_indices = list(np.nonzero(empty_mask)[0])\n if len(empty_indices) > 0:\n logging.debug(\"No data in %s bins\", len(empty_indices))\n\n return masked_result, empty_indices"}, {"class_start_lineno": 1, "class_end_lineno": 1151, "func_start_lineno": 195, "func_end_lineno": 231, "func_code": "def rebin_1d(\n x_in: np.ndarray,\n array: np.ndarray | ma.MaskedArray,\n x_new: np.ndarray,\n statistic: str = \"mean\",\n *,\n mask_zeros: bool = True,\n) -> ma.MaskedArray:\n \"\"\"Rebins 1D array.\n\n Args:\n x_in: 1-D array with shape (n,).\n array: 1-D input data with shape (m,).\n x_new: 1-D target vector (center points) with shape (N,).\n statistic: Statistic to be calculated. Possible statistics are 'mean', 'std'.\n Default is 'mean'.\n mask_zeros: Whether to mask 0 values in the returned array. Default is True.\n\n Returns:\n Re-binned data with shape (N,).\n\n \"\"\"\n edges = binvec(x_new)\n result = np.zeros(len(x_new))\n array_screened = ma.masked_invalid(array, copy=True) # data may contain nan-values\n mask = ~array_screened.mask\n if ma.any(array_screened[mask]):\n result, _, _ = stats.binned_statistic(\n x_in[mask],\n array_screened[mask],\n statistic=statistic,\n bins=edges,\n )\n result[~np.isfinite(result)] = 0\n if mask_zeros:\n return ma.masked_equal(result, 0)\n return ma.array(result)"}], "type": ["function_empty"], "node": ["cloudnetpy.utils.binvec", "cloudnetpy.utils.rebin_2d", "cloudnetpy.utils.rebin_1d"], "language": "Python", "toolfunc_count": 3, "func_count": 3, "pytest_info": {"total_num": 160, "base_passed_num": 151}} {"id": ["d3rlpy.d3rlpy.models.encoders.DefaultEncoderFactory::create", "d3rlpy.d3rlpy.models.builders.create_discrete_q_function"], "project": "d3rlpy", "origin_file": ["d3rlpy/models/encoders.py", "d3rlpy/models/builders.py"], "test_list": ["tests_copy/envs/test_wrappers.py", "tests_copy/models/test_builders.py"], "prob_info": [{"class_start_lineno": 209, "class_end_lineno": 265, "func_start_lineno": 224, "func_end_lineno": 238, "func_code": " def create(self, observation_shape: Shape) -> Encoder:\n factory: Union[PixelEncoderFactory, VectorEncoderFactory]\n if len(observation_shape) == 3:\n factory = PixelEncoderFactory(\n activation=self.activation,\n use_batch_norm=self.use_batch_norm,\n dropout_rate=self.dropout_rate,\n )\n else:\n factory = VectorEncoderFactory(\n activation=self.activation,\n use_batch_norm=self.use_batch_norm,\n dropout_rate=self.dropout_rate,\n )\n return factory.create(observation_shape)"}, {"class_start_lineno": 1, "class_end_lineno": 403, "func_start_lineno": 47, "func_end_lineno": 82, "func_code": "def create_discrete_q_function(\n observation_shape: Shape,\n action_size: int,\n encoder_factory: EncoderFactory,\n q_func_factory: QFunctionFactory,\n device: str,\n enable_ddp: bool,\n n_ensembles: int = 1,\n) -> tuple[nn.ModuleList, DiscreteEnsembleQFunctionForwarder]:\n if q_func_factory.share_encoder:\n encoder = encoder_factory.create(observation_shape)\n hidden_size = compute_output_size([observation_shape], encoder)\n # normalize gradient scale by ensemble size\n for p in cast(nn.Module, encoder).parameters():\n p.register_hook(lambda grad: grad / n_ensembles)\n\n q_funcs = []\n forwarders = []\n for _ in range(n_ensembles):\n if not q_func_factory.share_encoder:\n encoder = encoder_factory.create(observation_shape)\n hidden_size = compute_output_size([observation_shape], encoder)\n q_func, forwarder = q_func_factory.create_discrete(\n encoder, hidden_size, action_size\n )\n q_func.to(device)\n if enable_ddp:\n q_func = wrap_model_by_ddp(q_func)\n forwarder.set_q_func(q_func)\n q_funcs.append(q_func)\n forwarders.append(forwarder)\n q_func_modules = nn.ModuleList(q_funcs)\n ensemble_forwarder = DiscreteEnsembleQFunctionForwarder(\n forwarders, action_size\n )\n return q_func_modules, ensemble_forwarder"}], "type": ["Development"], "node": ["d3rlpy.models.encoders.DefaultEncoderFactory.create", "d3rlpy.models.builders.create_discrete_q_function"], "language": "Python", "toolfunc_count": 0, "func_count": 2, "pytest_info": {"total_num": 42, "base_passed_num": 15}} {"id": ["d3rlpy.d3rlpy.dataset.transition_pickers.BasicTransitionPicker::__call__", "d3rlpy.d3rlpy.metrics.evaluators.make_batches", "d3rlpy.d3rlpy.metrics.evaluators.TDErrorEvaluator::__call__", "d3rlpy.d3rlpy.models.encoders.DefaultEncoderFactory::create", "d3rlpy.d3rlpy.models.builders.create_discrete_q_function"], "project": "d3rlpy", "origin_file": ["d3rlpy/dataset/transition_pickers.py", "d3rlpy/metrics/evaluators.py", "d3rlpy/metrics/evaluators.py", "d3rlpy/models/encoders.py", "d3rlpy/models/builders.py"], "test_list": ["tests_copy/metrics/test_evaluators.py"], "prob_info": [{"class_start_lineno": 43, "class_end_lineno": 72, "func_start_lineno": 49, "func_end_lineno": 72, "func_code": " def __call__(self, episode: EpisodeBase, index: int) -> Transition:\n _validate_index(episode, index)\n\n observation = retrieve_observation(episode.observations, index)\n is_terminal = episode.terminated and index == episode.size() - 1\n if is_terminal:\n next_observation = create_zero_observation(observation)\n next_action = np.zeros_like(episode.actions[index])\n else:\n next_observation = retrieve_observation(\n episode.observations, index + 1\n )\n next_action = episode.actions[index + 1]\n\n return Transition(\n observation=observation,\n action=episode.actions[index],\n reward=episode.rewards[index],\n next_observation=next_observation,\n next_action=next_action,\n terminal=float(is_terminal),\n interval=1,\n rewards_to_go=episode.rewards[index:],\n )"}, {"class_start_lineno": 1, "class_end_lineno": 548, "func_start_lineno": 52, "func_end_lineno": 68, "func_code": "def make_batches(\n episode: EpisodeBase,\n window_size: int,\n transition_picker: TransitionPickerProtocol,\n) -> Iterator[TransitionMiniBatch]:\n n_batches = len(episode) // window_size\n if len(episode) % window_size != 0:\n n_batches += 1\n for i in range(n_batches):\n head_index = i * window_size\n last_index = min(head_index + window_size, episode.transition_count)\n transitions = [\n transition_picker(episode, index)\n for index in range(head_index, last_index)\n ]\n batch = TransitionMiniBatch.from_transitions(transitions)\n yield batch"}, {"class_start_lineno": 71, "class_end_lineno": 121, "func_start_lineno": 93, "func_end_lineno": 121, "func_code": " def __call__(\n self,\n algo: QLearningAlgoProtocol,\n dataset: ReplayBufferBase,\n ) -> float:\n total_errors = []\n episodes = self._episodes if self._episodes else dataset.episodes\n for episode in episodes:\n for batch in make_batches(\n episode, WINDOW_SIZE, dataset.transition_picker\n ):\n # estimate values for current observations\n values = algo.predict_value(batch.observations, batch.actions)\n\n # estimate values for next observations\n next_actions = algo.predict(batch.next_observations)\n next_values = algo.predict_value(\n batch.next_observations, next_actions\n )\n\n # calculate td errors\n mask = (1.0 - batch.terminals).reshape(-1)\n rewards = np.asarray(batch.rewards).reshape(-1)\n if algo.reward_scaler:\n rewards = algo.reward_scaler.transform_numpy(rewards)\n y = rewards + algo.gamma * next_values * mask\n total_errors += ((values - y) ** 2).tolist()\n\n return float(np.mean(total_errors))"}, {"class_start_lineno": 209, "class_end_lineno": 265, "func_start_lineno": 224, "func_end_lineno": 238, "func_code": " def create(self, observation_shape: Shape) -> Encoder:\n factory: Union[PixelEncoderFactory, VectorEncoderFactory]\n if len(observation_shape) == 3:\n factory = PixelEncoderFactory(\n activation=self.activation,\n use_batch_norm=self.use_batch_norm,\n dropout_rate=self.dropout_rate,\n )\n else:\n factory = VectorEncoderFactory(\n activation=self.activation,\n use_batch_norm=self.use_batch_norm,\n dropout_rate=self.dropout_rate,\n )\n return factory.create(observation_shape)"}, {"class_start_lineno": 1, "class_end_lineno": 403, "func_start_lineno": 47, "func_end_lineno": 82, "func_code": "def create_discrete_q_function(\n observation_shape: Shape,\n action_size: int,\n encoder_factory: EncoderFactory,\n q_func_factory: QFunctionFactory,\n device: str,\n enable_ddp: bool,\n n_ensembles: int = 1,\n) -> tuple[nn.ModuleList, DiscreteEnsembleQFunctionForwarder]:\n if q_func_factory.share_encoder:\n encoder = encoder_factory.create(observation_shape)\n hidden_size = compute_output_size([observation_shape], encoder)\n # normalize gradient scale by ensemble size\n for p in cast(nn.Module, encoder).parameters():\n p.register_hook(lambda grad: grad / n_ensembles)\n\n q_funcs = []\n forwarders = []\n for _ in range(n_ensembles):\n if not q_func_factory.share_encoder:\n encoder = encoder_factory.create(observation_shape)\n hidden_size = compute_output_size([observation_shape], encoder)\n q_func, forwarder = q_func_factory.create_discrete(\n encoder, hidden_size, action_size\n )\n q_func.to(device)\n if enable_ddp:\n q_func = wrap_model_by_ddp(q_func)\n forwarder.set_q_func(q_func)\n q_funcs.append(q_func)\n forwarders.append(forwarder)\n q_func_modules = nn.ModuleList(q_funcs)\n ensemble_forwarder = DiscreteEnsembleQFunctionForwarder(\n forwarders, action_size\n )\n return q_func_modules, ensemble_forwarder"}], "type": ["Development"], "node": ["d3rlpy.dataset.transition_pickers.BasicTransitionPicker.__call__", "d3rlpy.metrics.evaluators.make_batches", "d3rlpy.metrics.evaluators.TDErrorEvaluator.__call__", "d3rlpy.models.encoders.DefaultEncoderFactory.create", "d3rlpy.models.builders.create_discrete_q_function"], "language": "Python", "toolfunc_count": 0, "func_count": 5, "pytest_info": {"total_num": 19, "base_passed_num": 0}} {"id": ["d3rlpy.d3rlpy.models.torch.q_functions.ensemble_q_function._gather_quantiles_by_indices", "d3rlpy.d3rlpy.models.torch.q_functions.ensemble_q_function._reduce_quantile_ensemble", "d3rlpy.d3rlpy.models.torch.q_functions.mean_q_function.DiscreteMeanQFunctionForwarder::compute_error", "d3rlpy.d3rlpy.models.torch.q_functions.iqn_q_function.DiscreteIQNQFunctionForwarder::compute_error", "d3rlpy.d3rlpy.models.torch.q_functions.ensemble_q_function.compute_ensemble_q_function_error"], "project": "d3rlpy", "origin_file": ["d3rlpy/models/torch/q_functions/ensemble_q_function.py", "d3rlpy/models/torch/q_functions/ensemble_q_function.py", "d3rlpy/models/torch/q_functions/mean_q_function.py", "d3rlpy/models/torch/q_functions/iqn_q_function.py", "d3rlpy/models/torch/q_functions/ensemble_q_function.py", "d3rlpy/models/torch/q_functions/ensemble_q_function.py"], "test_list": ["tests_copy/models/torch/q_functions/test_ensemble_q_function.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 367, "func_start_lineno": 35, "func_end_lineno": 52, "func_code": "def _gather_quantiles_by_indices(\n y: torch.Tensor, indices: torch.Tensor\n) -> torch.Tensor:\n # TODO: implement this in general case\n if y.dim() == 3:\n # (N, batch, n_quantiles) -> (batch, n_quantiles)\n return y.transpose(0, 1)[torch.arange(y.shape[1]), indices]\n elif y.dim() == 4:\n # (N, batch, action, n_quantiles) -> (batch, action, N, n_quantiles)\n transposed_y = y.transpose(0, 1).transpose(1, 2)\n # (batch, action, N, n_quantiles) -> (batch * action, N, n_quantiles)\n flat_y = transposed_y.reshape(-1, y.shape[0], y.shape[3])\n head_indices = torch.arange(y.shape[1] * y.shape[2])\n # (batch * action, N, n_quantiles) -> (batch * action, n_quantiles)\n gathered_y = flat_y[head_indices, indices.view(-1)]\n # (batch * action, n_quantiles) -> (batch, action, n_quantiles)\n return gathered_y.view(y.shape[1], y.shape[2], -1)\n raise ValueError"}, {"class_start_lineno": 1, "class_end_lineno": 367, "func_start_lineno": 55, "func_end_lineno": 74, "func_code": "def _reduce_quantile_ensemble(\n y: torch.Tensor, reduction: str = \"min\", dim: int = 0, lam: float = 0.75\n) -> torch.Tensor:\n # reduction beased on expectation\n mean = y.mean(dim=-1)\n if reduction == \"min\":\n indices = mean.min(dim=dim).indices\n return _gather_quantiles_by_indices(y, indices)\n elif reduction == \"max\":\n indices = mean.max(dim=dim).indices\n return _gather_quantiles_by_indices(y, indices)\n elif reduction == \"none\":\n return y\n elif reduction == \"mix\":\n min_indices = mean.min(dim=dim).indices\n max_indices = mean.max(dim=dim).indices\n min_values = _gather_quantiles_by_indices(y, min_indices)\n max_values = _gather_quantiles_by_indices(y, max_indices)\n return lam * min_values + (1.0 - lam) * max_values\n raise ValueError"}, {"class_start_lineno": 47, "class_end_lineno": 86, "func_start_lineno": 58, "func_end_lineno": 74, "func_code": " def compute_error(\n self,\n observations: TorchObservation,\n actions: torch.Tensor,\n rewards: torch.Tensor,\n target: torch.Tensor,\n terminals: torch.Tensor,\n gamma: Union[float, torch.Tensor] = 0.99,\n reduction: str = \"mean\",\n ) -> torch.Tensor:\n one_hot = F.one_hot(actions.view(-1), num_classes=self._action_size)\n value = (self._q_func(observations).q_value * one_hot.float()).sum(\n dim=1, keepdim=True\n )\n y = rewards + gamma * target * (1 - terminals)\n loss = compute_huber_loss(value, y)\n return compute_reduce(loss, reduction)"}, {"class_start_lineno": 122, "class_end_lineno": 174, "func_start_lineno": 133, "func_end_lineno": 162, "func_code": " def compute_error(\n self,\n observations: TorchObservation,\n actions: torch.Tensor,\n rewards: torch.Tensor,\n target: torch.Tensor,\n terminals: torch.Tensor,\n gamma: Union[float, torch.Tensor] = 0.99,\n reduction: str = \"mean\",\n ) -> torch.Tensor:\n batch_size = get_batch_size(observations)\n assert target.shape == (batch_size, self._n_quantiles)\n\n # extraect quantiles corresponding to act_t\n output = self._q_func(observations)\n taus = output.taus\n all_quantiles = output.quantiles\n assert taus is not None and all_quantiles is not None\n quantiles = pick_quantile_value_by_action(all_quantiles, actions)\n\n loss = compute_quantile_loss(\n quantiles=quantiles,\n rewards=rewards,\n target=target,\n terminals=terminals,\n taus=taus,\n gamma=gamma,\n )\n\n return compute_reduce(loss, reduction)"}, {"class_start_lineno": 1, "class_end_lineno": 367, "func_start_lineno": 77, "func_end_lineno": 109, "func_code": "def compute_ensemble_q_function_error(\n forwarders: Union[\n Sequence[DiscreteQFunctionForwarder],\n Sequence[ContinuousQFunctionForwarder],\n ],\n observations: TorchObservation,\n actions: torch.Tensor,\n rewards: torch.Tensor,\n target: torch.Tensor,\n terminals: torch.Tensor,\n gamma: Union[float, torch.Tensor] = 0.99,\n masks: Optional[torch.Tensor] = None,\n) -> torch.Tensor:\n assert target.ndim == 2\n td_sum = torch.tensor(\n 0.0,\n dtype=torch.float32,\n device=get_device(observations),\n )\n for forwarder in forwarders:\n loss = forwarder.compute_error(\n observations=observations,\n actions=actions,\n rewards=rewards,\n target=target,\n terminals=terminals,\n gamma=gamma,\n reduction=\"none\",\n )\n if masks is not None:\n loss = loss * masks\n td_sum += loss.mean()\n return td_sum"}, {"class_start_lineno": 150, "class_end_lineno": 218, "func_start_lineno": 179, "func_end_lineno": 198, "func_code": " def compute_error(\n self,\n observations: TorchObservation,\n actions: torch.Tensor,\n rewards: torch.Tensor,\n target: torch.Tensor,\n terminals: torch.Tensor,\n gamma: Union[float, torch.Tensor] = 0.99,\n masks: Optional[torch.Tensor] = None,\n ) -> torch.Tensor:\n return compute_ensemble_q_function_error(\n forwarders=self._forwarders,\n observations=observations,\n actions=actions,\n rewards=rewards,\n target=target,\n terminals=terminals,\n gamma=gamma,\n masks=masks,\n )"}], "type": ["Development"], "node": ["d3rlpy.models.torch.q_functions.ensemble_q_function._gather_quantiles_by_indices", "d3rlpy.models.torch.q_functions.ensemble_q_function._reduce_quantile_ensemble", "d3rlpy.models.torch.q_functions.mean_q_function.DiscreteMeanQFunctionForwarder.compute_error", "d3rlpy.models.torch.q_functions.iqn_q_function.DiscreteIQNQFunctionForwarder.compute_error", "d3rlpy.models.torch.q_functions.ensemble_q_function.compute_ensemble_q_function_error", "d3rlpy.models.torch.q_functions.ensemble_q_function.DiscreteEnsembleQFunctionForwarder.compute_error"], "language": "Python", "toolfunc_count": 0, "func_count": 5, "pytest_info": {"total_num": 30, "base_passed_num": 4}} {"id": ["d3rlpy.d3rlpy.models.torch.q_functions.iqn_q_function.DiscreteIQNQFunction::forward", "d3rlpy.d3rlpy.models.torch.q_functions.iqn_q_function.DiscreteIQNQFunctionForwarder::compute_error"], "project": "d3rlpy", "origin_file": ["d3rlpy/models/torch/q_functions/iqn_q_function.py", "d3rlpy/models/torch/q_functions/base.py", "d3rlpy/models/torch/q_functions/iqn_q_function.py"], "test_list": ["tests_copy/models/torch/q_functions/test_iqn_q_function.py"], "prob_info": [{"class_start_lineno": 65, "class_end_lineno": 119, "func_start_lineno": 92, "func_end_lineno": 115, "func_code": " def forward(self, x: TorchObservation) -> QFunctionOutput:\n h = self._encoder(x)\n\n if self.training:\n n_quantiles = self._n_quantiles\n else:\n n_quantiles = self._n_greedy_quantiles\n taus = _make_taus(\n batch_size=get_batch_size(x),\n n_quantiles=n_quantiles,\n training=self.training,\n device=torch.device(get_device(x)),\n )\n\n # (batch, quantile, feature)\n prod = compute_iqn_feature(h, taus, self._embed, self._embed_size)\n # (batch, quantile, action) -> (batch, action, quantile)\n quantiles = self._fc(prod).transpose(1, 2)\n\n return QFunctionOutput(\n q_value=quantiles.mean(dim=2),\n quantiles=quantiles,\n taus=taus,\n )"}, {"class_start_lineno": null, "class_end_lineno": null, "func_start_lineno": null, "func_end_lineno": null, "func_code": "未找到 DiscreteIQNQFunction::__call__"}, {"class_start_lineno": 122, "class_end_lineno": 174, "func_start_lineno": 133, "func_end_lineno": 162, "func_code": " def compute_error(\n self,\n observations: TorchObservation,\n actions: torch.Tensor,\n rewards: torch.Tensor,\n target: torch.Tensor,\n terminals: torch.Tensor,\n gamma: Union[float, torch.Tensor] = 0.99,\n reduction: str = \"mean\",\n ) -> torch.Tensor:\n batch_size = get_batch_size(observations)\n assert target.shape == (batch_size, self._n_quantiles)\n\n # extraect quantiles corresponding to act_t\n output = self._q_func(observations)\n taus = output.taus\n all_quantiles = output.quantiles\n assert taus is not None and all_quantiles is not None\n quantiles = pick_quantile_value_by_action(all_quantiles, actions)\n\n loss = compute_quantile_loss(\n quantiles=quantiles,\n rewards=rewards,\n target=target,\n terminals=terminals,\n taus=taus,\n gamma=gamma,\n )\n\n return compute_reduce(loss, reduction)"}], "type": ["Development"], "node": ["d3rlpy.models.torch.q_functions.iqn_q_function.DiscreteIQNQFunction.forward", "d3rlpy.models.torch.q_functions.base.DiscreteIQNQFunction.__call__", "d3rlpy.models.torch.q_functions.iqn_q_function.DiscreteIQNQFunctionForwarder.compute_error"], "language": "Python", "toolfunc_count": 0, "func_count": 2, "pytest_info": {"total_num": 8, "base_passed_num": 4}} {"id": ["datachain.src.datachain.lib.convert.python_to_sql.python_to_sql", "datachain.src.datachain.lib.signal_schema.SignalSchema::get_column_type", "datachain.src.datachain.lib.dc.DataChain::mutate", "datachain.src.datachain.lib.signal_schema.SignalSchema::mutate"], "project": "datachain", "origin_file": ["datachain/lib/convert/python_to_sql.py", "datachain/func/func.py", "datachain/lib/signal_schema.py", "datachain/func/func.py", "datachain/lib/dc.py", "datachain/lib/signal_schema.py"], "test_list": ["tests/unit/test_func.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 117, "func_start_lineno": 37, "func_end_lineno": 82, "func_code": "def python_to_sql(typ): # noqa: PLR0911\n if inspect.isclass(typ):\n if issubclass(typ, SQLType):\n return typ\n if issubclass(typ, Enum):\n return str\n\n res = PYTHON_TO_SQL.get(typ)\n if res:\n return res\n\n orig = get_origin(typ)\n\n if orig in (Literal, LiteralEx):\n return String\n\n args = get_args(typ)\n if inspect.isclass(orig) and (issubclass(list, orig) or issubclass(tuple, orig)):\n if args is None:\n raise TypeError(f\"Cannot resolve type '{typ}' for flattening features\")\n\n args0 = args[0]\n if ModelStore.is_pydantic(args0):\n return Array(JSON())\n\n list_type = list_of_args_to_type(args)\n return Array(list_type)\n\n if orig is Annotated:\n # Ignoring annotations\n return python_to_sql(args[0])\n\n if inspect.isclass(orig) and issubclass(dict, orig):\n return JSON\n\n if orig == Union:\n if len(args) == 2 and (type(None) in args):\n return python_to_sql(args[0])\n\n if _is_union_str_literal(orig, args):\n return String\n\n if _is_json_inside_union(orig, args):\n return JSON\n\n raise TypeError(f\"Cannot recognize type {typ}\")"}, {"class_start_lineno": 29, "class_end_lineno": 422, "func_start_lineno": 375, "func_end_lineno": 422, "func_code": " def get_column(\n self,\n signals_schema: Optional[\"SignalSchema\"] = None,\n label: Optional[str] = None,\n table: Optional[\"TableClause\"] = None,\n ) -> Column:\n col_type = self.get_result_type(signals_schema)\n sql_type = python_to_sql(col_type)\n\n def get_col(col: ColT, string_as_literal=False) -> ColT:\n # string_as_literal is used only for conditionals like `case()` where\n # literals are nested inside ColT as we have tuples of condition - values\n # and if user wants to set some case value as column, explicit `C(\"col\")`\n # syntax must be used to distinguish from literals\n if isinstance(col, tuple):\n return tuple(get_col(x, string_as_literal=True) for x in col)\n if isinstance(col, Func):\n return col.get_column(signals_schema, table=table)\n if isinstance(col, str) and not string_as_literal:\n column = Column(col, sql_type)\n column.table = table\n return column\n return col\n\n cols = [get_col(col) for col in self._db_cols]\n kwargs = {k: get_col(v, string_as_literal=True) for k, v in self.kwargs.items()}\n func_col = self.inner(*cols, *self.args, **kwargs)\n\n if self.is_window:\n if not self.window:\n raise DataChainParamsError(\n f\"Window function {self} requires over() clause with a window spec\",\n )\n func_col = func_col.over(\n partition_by=self.window.partition_by,\n order_by=(\n desc(self.window.order_by)\n if self.window.desc\n else self.window.order_by\n ),\n )\n\n func_col.type = sql_type() if inspect.isclass(sql_type) else sql_type\n\n if col_name := self.get_col_name(label):\n func_col = func_col.label(col_name)\n\n return func_col"}, {"class_start_lineno": 135, "class_end_lineno": 751, "func_start_lineno": 464, "func_end_lineno": 479, "func_code": " def get_column_type(self, col_name: str, with_subtree: bool = False) -> DataType:\n \"\"\"\n Returns column type by column name.\n\n If `with_subtree` is True, then it will return the type of the column\n even if it has a subtree (e.g. model with nested fields), otherwise it will\n return the type of the column (standard type field, not the model).\n\n If column is not found, raises `SignalResolvingError`.\n \"\"\"\n for path, _type, has_subtree, _ in self.get_flat_tree():\n if (with_subtree or not has_subtree) and DEFAULT_DELIMITER.join(\n path\n ) == col_name:\n return _type\n raise SignalResolvingError([col_name], \"is not found\")"}, {"class_start_lineno": 1, "class_end_lineno": 449, "func_start_lineno": 425, "func_end_lineno": 438, "func_code": "def get_db_col_type(signals_schema: \"SignalSchema\", col: ColT) -> \"DataType\":\n if isinstance(col, tuple):\n # we can only get tuple from case statement where the first tuple item\n # is condition, and second one is value which type is important\n col = col[1]\n if isinstance(col, Func):\n return col.get_result_type(signals_schema)\n\n if isinstance(col, ColumnElement) and not hasattr(col, \"name\"):\n return sql_to_python(col)\n\n return signals_schema.get_column_type(\n col.name if isinstance(col, ColumnElement) else col # type: ignore[arg-type]\n )"}, {"class_start_lineno": 174, "class_end_lineno": 2625, "func_start_lineno": 1136, "func_end_lineno": 1215, "func_code": " def mutate(self, **kwargs) -> \"Self\":\n \"\"\"Create new signals based on existing signals.\n\n This method cannot modify existing columns. If you need to modify an\n existing column, use a different name for the new column and then use\n `select()` to choose which columns to keep.\n\n This method is vectorized and more efficient compared to map(), and it does not\n extract or download any data from the internal database. However, it can only\n utilize predefined built-in functions and their combinations.\n\n The supported functions:\n Numerical: +, -, *, /, rand(), avg(), count(), func(),\n greatest(), least(), max(), min(), sum()\n String: length(), split(), replace(), regexp_replace()\n Filename: name(), parent(), file_stem(), file_ext()\n Array: length(), sip_hash_64(), euclidean_distance(),\n cosine_distance()\n Window: row_number(), rank(), dense_rank(), first()\n\n Example:\n ```py\n dc.mutate(\n area=Column(\"image.height\") * Column(\"image.width\"),\n extension=file_ext(Column(\"file.name\")),\n dist=cosine_distance(embedding_text, embedding_image)\n )\n ```\n\n Window function example:\n ```py\n window = func.window(partition_by=\"file.parent\", order_by=\"file.size\")\n dc.mutate(\n row_number=func.row_number().over(window),\n )\n ```\n\n This method can be also used to rename signals. If the Column(\"name\") provided\n as value for the new signal - the old column will be dropped. Otherwise a new\n column is created.\n\n Example:\n ```py\n dc.mutate(\n newkey=Column(\"oldkey\")\n )\n ```\n \"\"\"\n primitives = (bool, str, int, float)\n\n for col_name, expr in kwargs.items():\n if not isinstance(expr, (*primitives, Column, Func)) and isinstance(\n expr.type, NullType\n ):\n raise DataChainColumnError(\n col_name, f\"Cannot infer type with expression {expr}\"\n )\n\n mutated = {}\n schema = self.signals_schema\n for name, value in kwargs.items():\n if isinstance(value, Column):\n # renaming existing column\n for signal in schema.db_signals(name=value.name, as_columns=True):\n mutated[signal.name.replace(value.name, name, 1)] = signal # type: ignore[union-attr]\n elif isinstance(value, Func):\n # adding new signal\n mutated[name] = value.get_column(schema)\n elif isinstance(value, primitives):\n # adding simple python constant primitives like str, int, float, bool\n val = literal(value)\n val.type = python_to_sql(type(value))()\n mutated[name] = val # type: ignore[assignment]\n else:\n # adding new signal\n mutated[name] = value\n\n return self._evolve(\n query=self._query.mutate(**mutated), signal_schema=schema.mutate(kwargs)\n )"}, {"class_start_lineno": 135, "class_end_lineno": 751, "func_start_lineno": 557, "func_end_lineno": 585, "func_code": " def mutate(self, args_map: dict) -> \"SignalSchema\":\n new_values = self.values.copy()\n\n for name, value in args_map.items():\n if isinstance(value, Column) and value.name in self.values:\n # renaming existing signal\n del new_values[value.name]\n new_values[name] = self.values[value.name]\n continue\n if isinstance(value, Column):\n # adding new signal from existing signal field\n try:\n new_values[name] = self.get_column_type(\n value.name, with_subtree=True\n )\n continue\n except SignalResolvingError:\n pass\n if isinstance(value, Func):\n # adding new signal with function\n new_values[name] = value.get_result_type(self)\n continue\n if isinstance(value, ColumnElement):\n # adding new signal\n new_values[name] = sql_to_python(value)\n continue\n new_values[name] = value\n\n return SignalSchema(new_values)"}], "type": ["function_empty", "Development"], "node": ["datachain.lib.convert.python_to_sql.python_to_sql", "datachain.func.func.Func.get_column", "datachain.lib.signal_schema.SignalSchema.get_column_type", "datachain.func.func.get_db_col_type", "datachain.lib.dc.DataChain.mutate", "datachain.lib.signal_schema.SignalSchema.mutate"], "language": "Python", "toolfunc_count": 1, "func_count": 4, "pytest_info": {"total_num": 94, "base_passed_num": 39}} {"id": ["datachain.src.datachain.query.session.Session::_cleanup_temp_datasets", "datachain.src.datachain.query.session.Session::__exit__"], "project": "datachain", "origin_file": ["datachain/query/session.py", "datachain/query/session.py"], "test_list": ["tests/unit/test_listing.py", "tests/unit/test_session.py"], "prob_info": [{"class_start_lineno": 19, "class_end_lineno": 195, "func_start_lineno": 103, "func_end_lineno": 110, "func_code": " def _cleanup_temp_datasets(self) -> None:\n prefix = self.get_temp_prefix()\n try:\n for dataset in list(self.catalog.metastore.list_datasets_by_prefix(prefix)):\n self.catalog.remove_dataset(dataset.name, force=True)\n # suppress error when metastore has been reset during testing\n except TableMissingError:\n pass"}, {"class_start_lineno": 19, "class_end_lineno": 195, "func_start_lineno": 80, "func_end_lineno": 90, "func_code": " def __exit__(self, exc_type, exc_val, exc_tb):\n if exc_type:\n self._cleanup_created_versions()\n\n self._cleanup_temp_datasets()\n if self.is_new_catalog:\n self.catalog.metastore.close_on_exit()\n self.catalog.warehouse.close_on_exit()\n\n if Session.SESSION_CONTEXTS:\n Session.SESSION_CONTEXTS.pop()"}], "type": ["Development"], "node": ["datachain.query.session.Session._cleanup_temp_datasets", "datachain.query.session.Session.__exit__"], "language": "Python", "toolfunc_count": 0, "func_count": 2, "pytest_info": {"total_num": 24, "base_passed_num": 7}} {"id": ["datachain.src.datachain.lib.signal_schema.SignalSchema::_get_flat_tree", "datachain.src.datachain.lib.convert.python_to_sql.python_to_sql", "datachain.src.datachain.lib.signal_schema.SignalSchema::db_signals", "datachain.src.datachain.query.session.Session::_cleanup_temp_datasets", "datachain.src.datachain.query.session.Session::__exit__"], "project": "datachain", "origin_file": ["datachain/lib/signal_schema.py", "datachain/lib/signal_schema.py", "datachain/lib/convert/python_to_sql.py", "datachain/lib/signal_schema.py", "datachain/query/session.py", "datachain/query/session.py"], "test_list": ["tests/unit/lib/test_arrow.py"], "prob_info": [{"class_start_lineno": 135, "class_end_lineno": 751, "func_start_lineno": 630, "func_end_lineno": 639, "func_code": " def _get_flat_tree(\n self, tree: dict, prefix: list[str], depth: int\n ) -> Iterator[tuple[list[str], DataType, bool, int]]:\n for name, (type_, substree) in tree.items():\n suffix = name.split(\".\")\n new_prefix = prefix + suffix\n has_subtree = substree is not None\n yield new_prefix, type_, has_subtree, depth\n if substree is not None:\n yield from self._get_flat_tree(substree, new_prefix, depth + 1)"}, {"class_start_lineno": 135, "class_end_lineno": 751, "func_start_lineno": 627, "func_end_lineno": 628, "func_code": " def get_flat_tree(self) -> Iterator[tuple[list[str], DataType, bool, int]]:\n yield from self._get_flat_tree(self.tree, [], 0)"}, {"class_start_lineno": 1, "class_end_lineno": 117, "func_start_lineno": 37, "func_end_lineno": 82, "func_code": "def python_to_sql(typ): # noqa: PLR0911\n if inspect.isclass(typ):\n if issubclass(typ, SQLType):\n return typ\n if issubclass(typ, Enum):\n return str\n\n res = PYTHON_TO_SQL.get(typ)\n if res:\n return res\n\n orig = get_origin(typ)\n\n if orig in (Literal, LiteralEx):\n return String\n\n args = get_args(typ)\n if inspect.isclass(orig) and (issubclass(list, orig) or issubclass(tuple, orig)):\n if args is None:\n raise TypeError(f\"Cannot resolve type '{typ}' for flattening features\")\n\n args0 = args[0]\n if ModelStore.is_pydantic(args0):\n return Array(JSON())\n\n list_type = list_of_args_to_type(args)\n return Array(list_type)\n\n if orig is Annotated:\n # Ignoring annotations\n return python_to_sql(args[0])\n\n if inspect.isclass(orig) and issubclass(dict, orig):\n return JSON\n\n if orig == Union:\n if len(args) == 2 and (type(None) in args):\n return python_to_sql(args[0])\n\n if _is_union_str_literal(orig, args):\n return String\n\n if _is_json_inside_union(orig, args):\n return JSON\n\n raise TypeError(f\"Cannot recognize type {typ}\")"}, {"class_start_lineno": 135, "class_end_lineno": 751, "func_start_lineno": 481, "func_end_lineno": 503, "func_code": " def db_signals(\n self, name: Optional[str] = None, as_columns=False\n ) -> Union[list[str], list[Column]]:\n \"\"\"\n Returns DB columns as strings or Column objects with proper types\n Optionally, it can filter results by specific object, returning only his signals\n \"\"\"\n signals = [\n DEFAULT_DELIMITER.join(path)\n if not as_columns\n else Column(DEFAULT_DELIMITER.join(path), python_to_sql(_type))\n for path, _type, has_subtree, _ in self.get_flat_tree()\n if not has_subtree\n ]\n\n if name:\n signals = [\n s\n for s in signals\n if str(s) == name or str(s).startswith(f\"{name}{DEFAULT_DELIMITER}\")\n ]\n\n return signals # type: ignore[return-value]"}, {"class_start_lineno": 19, "class_end_lineno": 195, "func_start_lineno": 103, "func_end_lineno": 110, "func_code": " def _cleanup_temp_datasets(self) -> None:\n prefix = self.get_temp_prefix()\n try:\n for dataset in list(self.catalog.metastore.list_datasets_by_prefix(prefix)):\n self.catalog.remove_dataset(dataset.name, force=True)\n # suppress error when metastore has been reset during testing\n except TableMissingError:\n pass"}, {"class_start_lineno": 19, "class_end_lineno": 195, "func_start_lineno": 80, "func_end_lineno": 90, "func_code": " def __exit__(self, exc_type, exc_val, exc_tb):\n if exc_type:\n self._cleanup_created_versions()\n\n self._cleanup_temp_datasets()\n if self.is_new_catalog:\n self.catalog.metastore.close_on_exit()\n self.catalog.warehouse.close_on_exit()\n\n if Session.SESSION_CONTEXTS:\n Session.SESSION_CONTEXTS.pop()"}], "type": ["function_empty", "Development"], "node": ["datachain.lib.signal_schema.SignalSchema._get_flat_tree", "datachain.lib.signal_schema.SignalSchema.get_flat_tree", "datachain.lib.convert.python_to_sql.python_to_sql", "datachain.lib.signal_schema.SignalSchema.db_signals", "datachain.query.session.Session._cleanup_temp_datasets", "datachain.query.session.Session.__exit__"], "language": "Python", "toolfunc_count": 1, "func_count": 5, "pytest_info": {"total_num": 32, "base_passed_num": 31}} {"id": ["datachain.src.datachain.lib.image.convert_image", "datachain.src.datachain.lib.image.convert_images"], "project": "datachain", "origin_file": ["datachain/lib/image.py", "datachain/lib/image.py"], "test_list": ["tests/unit/lib/test_clip.py", "tests/unit/lib/test_image.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 81, "func_start_lineno": 7, "func_end_lineno": 46, "func_code": "def convert_image(\n img: Image.Image,\n mode: str = \"RGB\",\n size: Optional[tuple[int, int]] = None,\n transform: Optional[Callable] = None,\n encoder: Optional[Callable] = None,\n device: Optional[Union[str, torch.device]] = None,\n) -> Union[Image.Image, torch.Tensor]:\n \"\"\"\n Resize, transform, and otherwise convert an image.\n\n Args:\n img (Image): PIL.Image object.\n mode (str): PIL.Image mode.\n size (tuple[int, int]): Size in (width, height) pixels for resizing.\n transform (Callable): Torchvision transform or huggingface processor to apply.\n encoder (Callable): Encode image using model.\n device (str or torch.device): Device to use.\n \"\"\"\n if mode:\n img = img.convert(mode)\n if size:\n img = img.resize(size)\n if transform:\n img = transform(img)\n\n try:\n from transformers.image_processing_utils import BaseImageProcessor\n\n if isinstance(transform, BaseImageProcessor):\n img = torch.as_tensor(img.pixel_values[0]).clone().detach() # type: ignore[assignment,attr-defined]\n except ImportError:\n pass\n if device:\n img = img.to(device) # type: ignore[attr-defined]\n if encoder:\n img = img.unsqueeze(0) # type: ignore[attr-defined]\n if encoder:\n img = encoder(img)\n return img"}, {"class_start_lineno": 1, "class_end_lineno": 81, "func_start_lineno": 49, "func_end_lineno": 81, "func_code": "def convert_images(\n images: Union[Image.Image, list[Image.Image]],\n mode: str = \"RGB\",\n size: Optional[tuple[int, int]] = None,\n transform: Optional[Callable] = None,\n encoder: Optional[Callable] = None,\n device: Optional[Union[str, torch.device]] = None,\n) -> Union[list[Image.Image], torch.Tensor]:\n \"\"\"\n Resize, transform, and otherwise convert one or more images.\n\n Args:\n images (Image, list[Image]): PIL.Image object or list of objects.\n mode (str): PIL.Image mode.\n size (tuple[int, int]): Size in (width, height) pixels for resizing.\n transform (Callable): Torchvision transform or huggingface processor to apply.\n encoder (Callable): Encode image using model.\n device (str or torch.device): Device to use.\n \"\"\"\n if isinstance(images, Image.Image):\n images = [images]\n\n converted = [\n convert_image(img, mode, size, transform, device=device) for img in images\n ]\n\n if isinstance(converted[0], torch.Tensor):\n converted = torch.stack(converted) # type: ignore[assignment,arg-type]\n\n if encoder:\n converted = encoder(converted)\n\n return converted # type: ignore[return-value]"}], "type": ["function_empty"], "node": ["datachain.lib.image.convert_image", "datachain.lib.image.convert_images"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 41, "base_passed_num": 13}} {"id": ["datachain.src.datachain.lib.file.File::get_destination_path", "datachain.src.datachain.lib.file.File::export", "datachain.src.datachain.lib.file.File::ensure_cached", "datachain.src.datachain.lib.file.File::_symlink_to"], "project": "datachain", "origin_file": ["datachain/lib/file.py", "datachain/lib/file.py", "datachain/lib/file.py", "datachain/lib/file.py"], "test_list": ["tests/unit/lib/test_file.py"], "prob_info": [{"class_start_lineno": 125, "class_end_lineno": 468, "func_start_lineno": 396, "func_end_lineno": 414, "func_code": " def get_destination_path(self, output: str, placement: ExportPlacement) -> str:\n \"\"\"\n Returns full destination path of a file for exporting to some output\n based on export placement\n \"\"\"\n if placement == \"filename\":\n path = unquote(self.name)\n elif placement == \"etag\":\n path = f\"{self.etag}{self.get_file_suffix()}\"\n elif placement == \"fullpath\":\n path = unquote(self.get_full_name())\n source = urlparse(self.source)\n if source.scheme and source.scheme != \"file\":\n path = posixpath.join(source.netloc, path)\n elif placement == \"checksum\":\n raise NotImplementedError(\"Checksum placement not implemented yet\")\n else:\n raise ValueError(f\"Unsupported file export placement: {placement}\")\n return posixpath.join(output, path) # type: ignore[union-attr]"}, {"class_start_lineno": 125, "class_end_lineno": 468, "func_start_lineno": 297, "func_end_lineno": 319, "func_code": " def export(\n self,\n output: str,\n placement: ExportPlacement = \"fullpath\",\n use_cache: bool = True,\n link_type: Literal[\"copy\", \"symlink\"] = \"copy\",\n ) -> None:\n \"\"\"Export file to new location.\"\"\"\n if use_cache:\n self._caching_enabled = use_cache\n dst = self.get_destination_path(output, placement)\n dst_dir = os.path.dirname(dst)\n client: Client = self._catalog.get_client(dst_dir)\n client.fs.makedirs(dst_dir, exist_ok=True)\n\n if link_type == \"symlink\":\n try:\n return self._symlink_to(dst)\n except OSError as exc:\n if exc.errno not in (errno.ENOTSUP, errno.EXDEV, errno.ENOSYS):\n raise\n\n self.save(dst)"}, {"class_start_lineno": 125, "class_end_lineno": 468, "func_start_lineno": 331, "func_end_lineno": 337, "func_code": " def ensure_cached(self) -> None:\n if self._catalog is None:\n raise RuntimeError(\n \"cannot download file to cache because catalog is not setup\"\n )\n client = self._catalog.get_client(self.source)\n client.download(self, callback=self._download_cb)"}, {"class_start_lineno": 125, "class_end_lineno": 468, "func_start_lineno": 282, "func_end_lineno": 295, "func_code": " def _symlink_to(self, destination: str):\n if self.location:\n raise OSError(errno.ENOTSUP, \"Symlinking virtual file is not supported\")\n\n if self._caching_enabled:\n self.ensure_cached()\n source = self.get_local_path()\n assert source, \"File was not cached\"\n elif self.source.startswith(\"file://\"):\n source = self.get_path()\n else:\n raise OSError(errno.EXDEV, \"can't link across filesystems\")\n\n return os.symlink(source, destination)"}], "type": ["function_empty", "Development"], "node": ["datachain.lib.file.File.get_destination_path", "datachain.lib.file.File.export", "datachain.lib.file.File.ensure_cached", "datachain.lib.file.File._symlink_to"], "language": "Python", "toolfunc_count": 1, "func_count": 4, "pytest_info": {"total_num": 33, "base_passed_num": 14}} {"id": ["datachain.src.datachain.query.session.Session::_cleanup_temp_datasets", "datachain.src.datachain.query.session.Session::__exit__", "datachain.src.datachain.lib.signal_schema.SignalSchema::_get_flat_tree", "datachain.src.datachain.lib.convert.python_to_sql.python_to_sql", "datachain.src.datachain.lib.signal_schema.SignalSchema::db_signals"], "project": "datachain", "origin_file": ["datachain/query/session.py", "datachain/query/session.py", "datachain/lib/signal_schema.py", "datachain/lib/signal_schema.py", "datachain/lib/convert/python_to_sql.py", "datachain/lib/signal_schema.py"], "test_list": ["tests/unit/lib/test_signal_schema.py"], "prob_info": [{"class_start_lineno": 19, "class_end_lineno": 195, "func_start_lineno": 103, "func_end_lineno": 110, "func_code": " def _cleanup_temp_datasets(self) -> None:\n prefix = self.get_temp_prefix()\n try:\n for dataset in list(self.catalog.metastore.list_datasets_by_prefix(prefix)):\n self.catalog.remove_dataset(dataset.name, force=True)\n # suppress error when metastore has been reset during testing\n except TableMissingError:\n pass"}, {"class_start_lineno": 19, "class_end_lineno": 195, "func_start_lineno": 80, "func_end_lineno": 90, "func_code": " def __exit__(self, exc_type, exc_val, exc_tb):\n if exc_type:\n self._cleanup_created_versions()\n\n self._cleanup_temp_datasets()\n if self.is_new_catalog:\n self.catalog.metastore.close_on_exit()\n self.catalog.warehouse.close_on_exit()\n\n if Session.SESSION_CONTEXTS:\n Session.SESSION_CONTEXTS.pop()"}, {"class_start_lineno": 135, "class_end_lineno": 751, "func_start_lineno": 630, "func_end_lineno": 639, "func_code": " def _get_flat_tree(\n self, tree: dict, prefix: list[str], depth: int\n ) -> Iterator[tuple[list[str], DataType, bool, int]]:\n for name, (type_, substree) in tree.items():\n suffix = name.split(\".\")\n new_prefix = prefix + suffix\n has_subtree = substree is not None\n yield new_prefix, type_, has_subtree, depth\n if substree is not None:\n yield from self._get_flat_tree(substree, new_prefix, depth + 1)"}, {"class_start_lineno": 135, "class_end_lineno": 751, "func_start_lineno": 627, "func_end_lineno": 628, "func_code": " def get_flat_tree(self) -> Iterator[tuple[list[str], DataType, bool, int]]:\n yield from self._get_flat_tree(self.tree, [], 0)"}, {"class_start_lineno": 1, "class_end_lineno": 117, "func_start_lineno": 37, "func_end_lineno": 82, "func_code": "def python_to_sql(typ): # noqa: PLR0911\n if inspect.isclass(typ):\n if issubclass(typ, SQLType):\n return typ\n if issubclass(typ, Enum):\n return str\n\n res = PYTHON_TO_SQL.get(typ)\n if res:\n return res\n\n orig = get_origin(typ)\n\n if orig in (Literal, LiteralEx):\n return String\n\n args = get_args(typ)\n if inspect.isclass(orig) and (issubclass(list, orig) or issubclass(tuple, orig)):\n if args is None:\n raise TypeError(f\"Cannot resolve type '{typ}' for flattening features\")\n\n args0 = args[0]\n if ModelStore.is_pydantic(args0):\n return Array(JSON())\n\n list_type = list_of_args_to_type(args)\n return Array(list_type)\n\n if orig is Annotated:\n # Ignoring annotations\n return python_to_sql(args[0])\n\n if inspect.isclass(orig) and issubclass(dict, orig):\n return JSON\n\n if orig == Union:\n if len(args) == 2 and (type(None) in args):\n return python_to_sql(args[0])\n\n if _is_union_str_literal(orig, args):\n return String\n\n if _is_json_inside_union(orig, args):\n return JSON\n\n raise TypeError(f\"Cannot recognize type {typ}\")"}, {"class_start_lineno": 135, "class_end_lineno": 751, "func_start_lineno": 481, "func_end_lineno": 503, "func_code": " def db_signals(\n self, name: Optional[str] = None, as_columns=False\n ) -> Union[list[str], list[Column]]:\n \"\"\"\n Returns DB columns as strings or Column objects with proper types\n Optionally, it can filter results by specific object, returning only his signals\n \"\"\"\n signals = [\n DEFAULT_DELIMITER.join(path)\n if not as_columns\n else Column(DEFAULT_DELIMITER.join(path), python_to_sql(_type))\n for path, _type, has_subtree, _ in self.get_flat_tree()\n if not has_subtree\n ]\n\n if name:\n signals = [\n s\n for s in signals\n if str(s) == name or str(s).startswith(f\"{name}{DEFAULT_DELIMITER}\")\n ]\n\n return signals # type: ignore[return-value]"}], "type": ["function_empty", "Development"], "node": ["datachain.query.session.Session._cleanup_temp_datasets", "datachain.query.session.Session.__exit__", "datachain.lib.signal_schema.SignalSchema._get_flat_tree", "datachain.lib.signal_schema.SignalSchema.get_flat_tree", "datachain.lib.convert.python_to_sql.python_to_sql", "datachain.lib.signal_schema.SignalSchema.db_signals"], "language": "Python", "toolfunc_count": 1, "func_count": 5, "pytest_info": {"total_num": 58, "base_passed_num": 36}} {"id": ["datachain.src.datachain.lib.webdataset.Builder::add", "datachain.src.datachain.lib.webdataset.get_tar_groups"], "project": "datachain", "origin_file": ["datachain/lib/webdataset.py", "datachain/lib/webdataset.py"], "test_list": ["tests/unit/lib/test_webdataset.py"], "prob_info": [{"class_start_lineno": 104, "class_end_lineno": 194, "func_start_lineno": 134, "func_end_lineno": 171, "func_code": " def add(self, file: tarfile.TarInfo):\n fstream = File(path=file.name)\n ext = fstream.get_file_ext()\n stem = fstream.get_file_stem()\n\n if self.state.stem is not None and self.state.stem != stem:\n raise StopIteration\n\n if self.state.stem is None:\n self.state.stem = stem\n\n if ext in self._core_extensions:\n if self.state.core_file is not None:\n raise CoreFileDuplicationError(\n self._tar_stream, file.name, self.state.core_file.name\n )\n self.state.core_file = file\n elif ext in self.state.data:\n raise WDSError(\n self._tar_stream,\n f\"file with extension '.{ext}' already exists in the archive\",\n )\n else:\n type_ = self._get_type(ext)\n if type_ is None:\n raise UnknownFileExtensionError(self._tar_stream, fstream.name, ext)\n\n if issubclass(type_, WDSReadableSubclass):\n reader = type_._reader\n else:\n reader = self.DEFAULT_TYPES_READERS.get(type_, None)\n\n if reader is None:\n raise WDSError(\n self._tar_stream,\n f\"unable to find a reader for type {type_}, extension .{ext}\",\n )\n self.state.data[ext] = reader(self, file)"}, {"class_start_lineno": 1, "class_end_lineno": 220, "func_start_lineno": 197, "func_end_lineno": 209, "func_code": "def get_tar_groups(stream, tar, core_extensions, spec, encoding=\"utf-8\"):\n builder = Builder(stream, core_extensions, spec, tar, encoding)\n\n for item in sorted(tar.getmembers(), key=lambda m: Path(m.name).stem):\n if not item.isfile():\n continue\n try:\n builder.add(item)\n except StopIteration:\n yield builder.produce()\n builder.add(item)\n if builder.state.stem is not None:\n yield builder.produce()"}], "type": ["Development"], "node": ["datachain.lib.webdataset.Builder.add", "datachain.lib.webdataset.get_tar_groups"], "language": "Python", "toolfunc_count": 0, "func_count": 2, "pytest_info": {"total_num": 7, "base_passed_num": 0}} {"id": ["datachain.src.datachain.func.conditional.case", "datachain.src.datachain.func.conditional.ifelse"], "project": "datachain", "origin_file": ["datachain/func/conditional.py", "datachain/func/conditional.py"], "test_list": ["tests/unit/sql/test_conditional.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 270, "func_start_lineno": 93, "func_end_lineno": 158, "func_code": "def case(\n *args: tuple[Union[ColumnElement, Func, bool], CaseT], else_: Optional[CaseT] = None\n) -> Func:\n \"\"\"\n Returns the case function that produces case expression which has a list of\n conditions and corresponding results. Results can be python primitives like string,\n numbers or booleans but can also be other nested functions (including case function)\n or columns.\n Result type is inferred from condition results.\n\n Args:\n args tuple((ColumnElement | Func | bool),(str | int | float | complex | bool, Func, ColumnElement)):\n Tuple of condition and values pair.\n else_ (str | int | float | complex | bool, Func): optional else value in case\n expression. If omitted, and no case conditions are satisfied, the result\n will be None (NULL in DB).\n\n Returns:\n Func: A Func object that represents the case function.\n\n Example:\n ```py\n dc.mutate(\n res=func.case((C(\"num\") > 0, \"P\"), (C(\"num\") < 0, \"N\"), else_=\"Z\"),\n )\n ```\n \"\"\" # noqa: E501\n supported_types = [int, float, complex, str, bool]\n\n def _get_type(val):\n from enum import Enum\n\n if isinstance(val, Func):\n # nested functions\n return val.result_type\n if isinstance(val, Column):\n # at this point we cannot know what is the type of a column\n return None\n if isinstance(val, Enum):\n return type(val.value)\n return type(val)\n\n if not args:\n raise DataChainParamsError(\"Missing statements\")\n\n type_ = _get_type(else_) if else_ is not None else None\n\n for arg in args:\n arg_type = _get_type(arg[1])\n if arg_type is None:\n # we couldn't figure out the type of case value\n continue\n if type_ and arg_type != type_:\n raise DataChainParamsError(\n f\"Statement values must be of the same type, got {type_} and {arg_type}\"\n )\n type_ = arg_type\n\n if type_ is not None and type_ not in supported_types:\n raise DataChainParamsError(\n f\"Only python literals ({supported_types}) are supported for values\"\n )\n\n kwargs = {\"else_\": else_}\n\n return Func(\"case\", inner=sql_case, cols=args, kwargs=kwargs, result_type=type_)"}, {"class_start_lineno": 1, "class_end_lineno": 270, "func_start_lineno": 161, "func_end_lineno": 187, "func_code": "def ifelse(\n condition: Union[ColumnElement, Func], if_val: CaseT, else_val: CaseT\n) -> Func:\n \"\"\"\n Returns the ifelse function that produces if expression which has a condition\n and values for true and false outcome. Results can be one of python primitives\n like string, numbers or booleans, but can also be nested functions or columns.\n Result type is inferred from the values.\n\n Args:\n condition (ColumnElement, Func): Condition which is evaluated.\n if_val (str | int | float | complex | bool, Func, ColumnElement): Value for true\n condition outcome.\n else_val (str | int | float | complex | bool, Func, ColumnElement): Value for\n false condition outcome.\n\n Returns:\n Func: A Func object that represents the ifelse function.\n\n Example:\n ```py\n dc.mutate(\n res=func.ifelse(isnone(\"col\"), \"EMPTY\", \"NOT_EMPTY\")\n )\n ```\n \"\"\"\n return case((condition, if_val), else_=else_val)"}], "type": ["function_empty", "Development"], "node": ["datachain.func.conditional.case", "datachain.func.conditional.ifelse"], "language": "Python", "toolfunc_count": 1, "func_count": 2, "pytest_info": {"total_num": 34, "base_passed_num": 2}} {"id": ["haystack.haystack.components.builders.prompt_builder.PromptBuilder::_validate_variables", "haystack.haystack.components.builders.prompt_builder.PromptBuilder::run", "haystack.haystack.core.type_utils._strict_types_are_compatible", "haystack.haystack.core.type_utils._types_are_compatible"], "project": "haystack", "origin_file": ["haystack/components/builders/prompt_builder.py", "haystack/components/builders/prompt_builder.py", "haystack/core/type_utils.py", "haystack/core/type_utils.py"], "test_list": ["test/components/builders/test_prompt_builder.py"], "prob_info": [{"class_start_lineno": 17, "class_end_lineno": 266, "func_start_lineno": 247, "func_end_lineno": 266, "func_code": " def _validate_variables(self, provided_variables: Set[str]):\n \"\"\"\n Checks if all the required template variables are provided.\n\n :param provided_variables:\n A set of provided template variables.\n :raises ValueError:\n If any of the required template variables is not provided.\n \"\"\"\n if self.required_variables == \"*\":\n required_variables = sorted(self.variables)\n else:\n required_variables = self.required_variables\n missing_variables = [var for var in required_variables if var not in provided_variables]\n if missing_variables:\n missing_vars_str = \", \".join(missing_variables)\n raise ValueError(\n f\"Missing required input variables in PromptBuilder: {missing_vars_str}. \"\n f\"Required variables: {required_variables}. Provided variables: {provided_variables}.\"\n )"}, {"class_start_lineno": 17, "class_end_lineno": 266, "func_start_lineno": 213, "func_end_lineno": 245, "func_code": " def run(self, template: Optional[str] = None, template_variables: Optional[Dict[str, Any]] = None, **kwargs):\n \"\"\"\n Renders the prompt template with the provided variables.\n\n It applies the template variables to render the final prompt. You can provide variables via pipeline kwargs.\n In order to overwrite the default template, you can set the `template` parameter.\n In order to overwrite pipeline kwargs, you can set the `template_variables` parameter.\n\n :param template:\n An optional string template to overwrite PromptBuilder's default template. If None, the default template\n provided at initialization is used.\n :param template_variables:\n An optional dictionary of template variables to overwrite the pipeline variables.\n :param kwargs:\n Pipeline variables used for rendering the prompt.\n\n :returns: A dictionary with the following keys:\n - `prompt`: The updated prompt text after rendering the prompt template.\n\n :raises ValueError:\n If any of the required template variables is not provided.\n \"\"\"\n kwargs = kwargs or {}\n template_variables = template_variables or {}\n template_variables_combined = {**kwargs, **template_variables}\n self._validate_variables(set(template_variables_combined.keys()))\n\n compiled_template = self.template\n if template is not None:\n compiled_template = self._env.from_string(template)\n\n result = compiled_template.render(template_variables_combined)\n return {\"prompt\": result}"}, {"class_start_lineno": 1, "class_end_lineno": 105, "func_start_lineno": 29, "func_end_lineno": 76, "func_code": "def _strict_types_are_compatible(sender, receiver): # pylint: disable=too-many-return-statements\n \"\"\"\n Checks whether the sender type is equal to or a subtype of the receiver type under strict validation.\n\n Note: this method has no pretense to perform proper type matching. It especially does not deal with aliasing of\n typing classes such as `List` or `Dict` to their runtime counterparts `list` and `dict`. It also does not deal well\n with \"bare\" types, so `List` is treated differently from `List[Any]`, even though they should be the same.\n Consider simplifying the typing of your components if you observe unexpected errors during component connection.\n\n :param sender: The sender type.\n :param receiver: The receiver type.\n :return: True if the sender type is strictly compatible with the receiver type, False otherwise.\n \"\"\"\n if sender == receiver or receiver is Any:\n return True\n\n if sender is Any:\n return False\n\n try:\n if issubclass(sender, receiver):\n return True\n except TypeError: # typing classes can't be used with issubclass, so we deal with them below\n pass\n\n sender_origin = get_origin(sender)\n receiver_origin = get_origin(receiver)\n\n if sender_origin is not Union and receiver_origin is Union:\n return any(_strict_types_are_compatible(sender, union_arg) for union_arg in get_args(receiver))\n\n # Both must have origins and they must be equal\n if not (sender_origin and receiver_origin and sender_origin == receiver_origin):\n return False\n\n # Compare generic type arguments\n sender_args = get_args(sender)\n receiver_args = get_args(receiver)\n\n # Handle bare types\n if not sender_args and sender_origin:\n sender_args = (Any,)\n if not receiver_args and receiver_origin:\n receiver_args = (Any,) * (len(sender_args) if sender_args else 1)\n if len(sender_args) > len(receiver_args):\n return False\n\n return all(_strict_types_are_compatible(*args) for args in zip(sender_args, receiver_args))"}, {"class_start_lineno": 1, "class_end_lineno": 105, "func_start_lineno": 14, "func_end_lineno": 26, "func_code": "def _types_are_compatible(sender, receiver, type_validation: bool = True) -> bool:\n \"\"\"\n Determines if two types are compatible based on the specified validation mode.\n\n :param sender: The sender type.\n :param receiver: The receiver type.\n :param type_validation: Whether to perform strict type validation.\n :return: True if the types are compatible, False otherwise.\n \"\"\"\n if type_validation:\n return _strict_types_are_compatible(sender, receiver)\n else:\n return True"}], "type": ["function_empty"], "node": ["haystack.components.builders.prompt_builder.PromptBuilder._validate_variables", "haystack.components.builders.prompt_builder.PromptBuilder.run", "haystack.core.type_utils._strict_types_are_compatible", "haystack.core.type_utils._types_are_compatible"], "language": "Python", "toolfunc_count": 4, "func_count": 4, "pytest_info": {"total_num": 29, "base_passed_num": 7}} {"id": ["haystack.haystack.core.type_utils._strict_types_are_compatible", "haystack.haystack.core.type_utils._types_are_compatible", "haystack.haystack.document_stores.in_memory.document_store.InMemoryDocumentStore::to_dict", "haystack.haystack.components.retrievers.in_memory.bm25_retriever.InMemoryBM25Retriever::to_dict", "haystack.haystack.core.serialization.component_to_dict"], "project": "haystack", "origin_file": ["haystack/core/type_utils.py", "haystack/core/type_utils.py", "haystack/document_stores/in_memory/document_store.py", "haystack/components/retrievers/in_memory/bm25_retriever.py", "haystack/core/serialization.py"], "test_list": ["test/components/classifiers/test_zero_shot_document_classifier.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 105, "func_start_lineno": 29, "func_end_lineno": 76, "func_code": "def _strict_types_are_compatible(sender, receiver): # pylint: disable=too-many-return-statements\n \"\"\"\n Checks whether the sender type is equal to or a subtype of the receiver type under strict validation.\n\n Note: this method has no pretense to perform proper type matching. It especially does not deal with aliasing of\n typing classes such as `List` or `Dict` to their runtime counterparts `list` and `dict`. It also does not deal well\n with \"bare\" types, so `List` is treated differently from `List[Any]`, even though they should be the same.\n Consider simplifying the typing of your components if you observe unexpected errors during component connection.\n\n :param sender: The sender type.\n :param receiver: The receiver type.\n :return: True if the sender type is strictly compatible with the receiver type, False otherwise.\n \"\"\"\n if sender == receiver or receiver is Any:\n return True\n\n if sender is Any:\n return False\n\n try:\n if issubclass(sender, receiver):\n return True\n except TypeError: # typing classes can't be used with issubclass, so we deal with them below\n pass\n\n sender_origin = get_origin(sender)\n receiver_origin = get_origin(receiver)\n\n if sender_origin is not Union and receiver_origin is Union:\n return any(_strict_types_are_compatible(sender, union_arg) for union_arg in get_args(receiver))\n\n # Both must have origins and they must be equal\n if not (sender_origin and receiver_origin and sender_origin == receiver_origin):\n return False\n\n # Compare generic type arguments\n sender_args = get_args(sender)\n receiver_args = get_args(receiver)\n\n # Handle bare types\n if not sender_args and sender_origin:\n sender_args = (Any,)\n if not receiver_args and receiver_origin:\n receiver_args = (Any,) * (len(sender_args) if sender_args else 1)\n if len(sender_args) > len(receiver_args):\n return False\n\n return all(_strict_types_are_compatible(*args) for args in zip(sender_args, receiver_args))"}, {"class_start_lineno": 1, "class_end_lineno": 105, "func_start_lineno": 14, "func_end_lineno": 26, "func_code": "def _types_are_compatible(sender, receiver, type_validation: bool = True) -> bool:\n \"\"\"\n Determines if two types are compatible based on the specified validation mode.\n\n :param sender: The sender type.\n :param receiver: The receiver type.\n :param type_validation: Whether to perform strict type validation.\n :return: True if the types are compatible, False otherwise.\n \"\"\"\n if type_validation:\n return _strict_types_are_compatible(sender, receiver)\n else:\n return True"}, {"class_start_lineno": 58, "class_end_lineno": 738, "func_start_lineno": 344, "func_end_lineno": 358, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serializes the component to a dictionary.\n\n :returns:\n Dictionary with serialized data.\n \"\"\"\n return default_to_dict(\n self,\n bm25_tokenization_regex=self.bm25_tokenization_regex,\n bm25_algorithm=self.bm25_algorithm,\n bm25_parameters=self.bm25_parameters,\n embedding_similarity_function=self.embedding_similarity_function,\n index=self.index,\n )"}, {"class_start_lineno": 13, "class_end_lineno": 203, "func_start_lineno": 88, "func_end_lineno": 103, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serializes the component to a dictionary.\n\n :returns:\n Dictionary with serialized data.\n \"\"\"\n docstore = self.document_store.to_dict()\n return default_to_dict(\n self,\n document_store=docstore,\n filters=self.filters,\n top_k=self.top_k,\n scale_score=self.scale_score,\n filter_policy=self.filter_policy.value,\n )"}, {"class_start_lineno": 1, "class_end_lineno": 264, "func_start_lineno": 36, "func_end_lineno": 82, "func_code": "def component_to_dict(obj: Any, name: str) -> Dict[str, Any]:\n \"\"\"\n Converts a component instance into a dictionary.\n\n If a `to_dict` method is present in the component instance, that will be used instead of the default method.\n\n :param obj:\n The component to be serialized.\n :param name:\n The name of the component.\n :returns:\n A dictionary representation of the component.\n\n :raises SerializationError:\n If the component doesn't have a `to_dict` method.\n If the values of the init parameters can't be determined.\n If a non-basic Python type is used in the serialized data.\n \"\"\"\n if hasattr(obj, \"to_dict\"):\n data = obj.to_dict()\n else:\n init_parameters = {}\n for param_name, param in inspect.signature(obj.__init__).parameters.items():\n # Ignore `args` and `kwargs`, used by the default constructor\n if param_name in (\"args\", \"kwargs\"):\n continue\n try:\n # This only works if the Component constructor assigns the init\n # parameter to an instance variable or property with the same name\n param_value = getattr(obj, param_name)\n except AttributeError as e:\n # If the parameter doesn't have a default value, raise an error\n if param.default is param.empty:\n raise SerializationError(\n f\"Cannot determine the value of the init parameter '{param_name}' \"\n f\"for the class {obj.__class__.__name__}.\"\n f\"You can fix this error by assigning 'self.{param_name} = {param_name}' or adding a \"\n f\"custom serialization method 'to_dict' to the class.\"\n ) from e\n # In case the init parameter was not assigned, we use the default value\n param_value = param.default\n init_parameters[param_name] = param_value\n\n data = default_to_dict(obj, **init_parameters)\n\n _validate_component_to_dict_output(obj, name, data)\n return data"}], "type": ["function_empty", "Development"], "node": ["haystack.core.type_utils._strict_types_are_compatible", "haystack.core.type_utils._types_are_compatible", "haystack.document_stores.in_memory.document_store.InMemoryDocumentStore.to_dict", "haystack.components.retrievers.in_memory.bm25_retriever.InMemoryBM25Retriever.to_dict", "haystack.core.serialization.component_to_dict"], "language": "Python", "toolfunc_count": 4, "func_count": 5, "pytest_info": {"total_num": 10, "base_passed_num": 9}} {"id": ["haystack.haystack.core.serialization.default_to_dict", "haystack.haystack.core.serialization.component_to_dict"], "project": "haystack", "origin_file": ["haystack/core/serialization.py", "haystack/components/connectors/openapi_service.py", "haystack/core/serialization.py"], "test_list": ["test/components/connectors/test_openapi_service.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 264, "func_start_lineno": 172, "func_end_lineno": 210, "func_code": "def default_to_dict(obj: Any, **init_parameters) -> Dict[str, Any]:\n \"\"\"\n Utility function to serialize an object to a dictionary.\n\n This is mostly necessary for components but can be used by any object.\n `init_parameters` are parameters passed to the object class `__init__`.\n They must be defined explicitly as they'll be used when creating a new\n instance of `obj` with `from_dict`. Omitting them might cause deserialisation\n errors or unexpected behaviours later, when calling `from_dict`.\n\n An example usage:\n\n ```python\n class MyClass:\n def __init__(self, my_param: int = 10):\n self.my_param = my_param\n\n def to_dict(self):\n return default_to_dict(self, my_param=self.my_param)\n\n\n obj = MyClass(my_param=1000)\n data = obj.to_dict()\n assert data == {\n \"type\": \"MyClass\",\n \"init_parameters\": {\n \"my_param\": 1000,\n },\n }\n ```\n\n :param obj:\n The object to be serialized.\n :param init_parameters:\n The parameters used to create a new instance of the class.\n :returns:\n A dictionary representation of the instance.\n \"\"\"\n return {\"type\": generate_qualified_class_name(type(obj)), \"init_parameters\": init_parameters}"}, {"class_start_lineno": 149, "class_end_lineno": 399, "func_start_lineno": 265, "func_end_lineno": 272, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serializes the component to a dictionary.\n\n :returns:\n Dictionary with serialized data.\n \"\"\"\n return default_to_dict(self, ssl_verify=self.ssl_verify)"}, {"class_start_lineno": 1, "class_end_lineno": 264, "func_start_lineno": 36, "func_end_lineno": 82, "func_code": "def component_to_dict(obj: Any, name: str) -> Dict[str, Any]:\n \"\"\"\n Converts a component instance into a dictionary.\n\n If a `to_dict` method is present in the component instance, that will be used instead of the default method.\n\n :param obj:\n The component to be serialized.\n :param name:\n The name of the component.\n :returns:\n A dictionary representation of the component.\n\n :raises SerializationError:\n If the component doesn't have a `to_dict` method.\n If the values of the init parameters can't be determined.\n If a non-basic Python type is used in the serialized data.\n \"\"\"\n if hasattr(obj, \"to_dict\"):\n data = obj.to_dict()\n else:\n init_parameters = {}\n for param_name, param in inspect.signature(obj.__init__).parameters.items():\n # Ignore `args` and `kwargs`, used by the default constructor\n if param_name in (\"args\", \"kwargs\"):\n continue\n try:\n # This only works if the Component constructor assigns the init\n # parameter to an instance variable or property with the same name\n param_value = getattr(obj, param_name)\n except AttributeError as e:\n # If the parameter doesn't have a default value, raise an error\n if param.default is param.empty:\n raise SerializationError(\n f\"Cannot determine the value of the init parameter '{param_name}' \"\n f\"for the class {obj.__class__.__name__}.\"\n f\"You can fix this error by assigning 'self.{param_name} = {param_name}' or adding a \"\n f\"custom serialization method 'to_dict' to the class.\"\n ) from e\n # In case the init parameter was not assigned, we use the default value\n param_value = param.default\n init_parameters[param_name] = param_value\n\n data = default_to_dict(obj, **init_parameters)\n\n _validate_component_to_dict_output(obj, name, data)\n return data"}], "type": ["function_empty", "Development"], "node": ["haystack.core.serialization.default_to_dict", "haystack.components.connectors.openapi_service.OpenAPIServiceConnector.to_dict", "haystack.core.serialization.component_to_dict"], "language": "Python", "toolfunc_count": 1, "func_count": 2, "pytest_info": {"total_num": 12, "base_passed_num": 10}} {"id": ["haystack.haystack.core.serialization.default_to_dict", "haystack.haystack.components.converters.json.JSONConverter::to_dict", "haystack.haystack.components.converters.utils.normalize_metadata", "haystack.haystack.components.converters.json.JSONConverter::run"], "project": "haystack", "origin_file": ["haystack/core/serialization.py", "haystack/components/converters/json.py", "haystack/components/converters/utils.py", "haystack/components/converters/json.py"], "test_list": ["test/components/converters/test_json.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 264, "func_start_lineno": 172, "func_end_lineno": 210, "func_code": "def default_to_dict(obj: Any, **init_parameters) -> Dict[str, Any]:\n \"\"\"\n Utility function to serialize an object to a dictionary.\n\n This is mostly necessary for components but can be used by any object.\n `init_parameters` are parameters passed to the object class `__init__`.\n They must be defined explicitly as they'll be used when creating a new\n instance of `obj` with `from_dict`. Omitting them might cause deserialisation\n errors or unexpected behaviours later, when calling `from_dict`.\n\n An example usage:\n\n ```python\n class MyClass:\n def __init__(self, my_param: int = 10):\n self.my_param = my_param\n\n def to_dict(self):\n return default_to_dict(self, my_param=self.my_param)\n\n\n obj = MyClass(my_param=1000)\n data = obj.to_dict()\n assert data == {\n \"type\": \"MyClass\",\n \"init_parameters\": {\n \"my_param\": 1000,\n },\n }\n ```\n\n :param obj:\n The object to be serialized.\n :param init_parameters:\n The parameters used to create a new instance of the class.\n :returns:\n A dictionary representation of the instance.\n \"\"\"\n return {\"type\": generate_qualified_class_name(type(obj)), \"init_parameters\": init_parameters}"}, {"class_start_lineno": 22, "class_end_lineno": 291, "func_start_lineno": 152, "func_end_lineno": 165, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serializes the component to a dictionary.\n\n :returns:\n Dictionary with serialized data.\n \"\"\"\n return default_to_dict(\n self,\n jq_schema=self._jq_schema,\n content_key=self._content_key,\n extra_meta_fields=self._meta_fields,\n store_full_path=self._store_full_path,\n )"}, {"class_start_lineno": 1, "class_end_lineno": 51, "func_start_lineno": 30, "func_end_lineno": 51, "func_code": "def normalize_metadata(\n meta: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]], sources_count: int\n) -> List[Dict[str, Any]]:\n \"\"\"\n Normalize the metadata input for a converter.\n\n Given all the possible value of the meta input for a converter (None, dictionary or list of dicts),\n makes sure to return a list of dictionaries of the correct length for the converter to use.\n\n :param meta: the meta input of the converter, as-is\n :param sources_count: the number of sources the converter received\n :returns: a list of dictionaries of the make length as the sources list\n \"\"\"\n if meta is None:\n return [{}] * sources_count\n if isinstance(meta, dict):\n return [meta] * sources_count\n if isinstance(meta, list):\n if sources_count != len(meta):\n raise ValueError(\"The length of the metadata list must match the number of sources.\")\n return meta\n raise ValueError(\"meta must be either None, a dictionary or a list of dictionaries.\")"}, {"class_start_lineno": 22, "class_end_lineno": 291, "func_start_lineno": 250, "func_end_lineno": 291, "func_code": " def run(\n self,\n sources: List[Union[str, Path, ByteStream]],\n meta: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None,\n ):\n \"\"\"\n Converts a list of JSON files to documents.\n\n :param sources:\n A list of file paths or ByteStream objects.\n :param meta:\n Optional metadata to attach to the documents.\n This value can be either a list of dictionaries or a single dictionary.\n If it's a single dictionary, its content is added to the metadata of all produced documents.\n If it's a list, the length of the list must match the number of sources.\n If `sources` contain ByteStream objects, their `meta` will be added to the output documents.\n\n :returns:\n A dictionary with the following keys:\n - `documents`: A list of created documents.\n \"\"\"\n documents = []\n meta_list = normalize_metadata(meta=meta, sources_count=len(sources))\n\n for source, metadata in zip(sources, meta_list):\n try:\n bytestream = get_bytestream_from_source(source)\n except Exception as exc:\n logger.warning(\"Could not read {source}. Skipping it. Error: {error}\", source=source, error=exc)\n continue\n\n data = self._get_content_and_meta(bytestream)\n\n for text, extra_meta in data:\n merged_metadata = {**bytestream.meta, **metadata, **extra_meta}\n\n if not self._store_full_path and (file_path := bytestream.meta.get(\"file_path\")):\n merged_metadata[\"file_path\"] = os.path.basename(file_path)\n document = Document(content=text, meta=merged_metadata)\n documents.append(document)\n\n return {\"documents\": documents}"}], "type": ["function_empty", "Development"], "node": ["haystack.core.serialization.default_to_dict", "haystack.components.converters.json.JSONConverter.to_dict", "haystack.components.converters.utils.normalize_metadata", "haystack.components.converters.json.JSONConverter.run"], "language": "Python", "toolfunc_count": 3, "func_count": 4, "pytest_info": {"total_num": 19, "base_passed_num": 5}} {"id": ["haystack.haystack.components.converters.openapi_functions.OpenAPIServiceToFunctions::_parse_openapi_spec", "haystack.haystack.components.converters.openapi_functions.OpenAPIServiceToFunctions::run", "haystack.haystack.components.converters.openapi_functions.OpenAPIServiceToFunctions::_parse_property_attributes", "haystack.haystack.components.converters.openapi_functions.OpenAPIServiceToFunctions::_parse_endpoint_spec", "haystack.haystack.components.converters.openapi_functions.OpenAPIServiceToFunctions::_openapi_to_functions"], "project": "haystack", "origin_file": ["haystack/components/converters/openapi_functions.py", "haystack/components/converters/openapi_functions.py", "haystack/components/converters/openapi_functions.py", "haystack/components/converters/openapi_functions.py", "haystack/components/converters/openapi_functions.py"], "test_list": ["test/components/converters/test_openapi_functions.py"], "prob_info": [{"class_start_lineno": 23, "class_end_lineno": 257, "func_start_lineno": 232, "func_end_lineno": 257, "func_code": " def _parse_openapi_spec(self, content: str) -> Dict[str, Any]:\n \"\"\"\n Parses OpenAPI specification content, supporting both JSON and YAML formats.\n\n :param content: The content of the OpenAPI specification.\n :return: The parsed OpenAPI specification.\n \"\"\"\n open_api_spec_content = None\n try:\n open_api_spec_content = json.loads(content)\n return jsonref.replace_refs(open_api_spec_content)\n except json.JSONDecodeError as json_error:\n # heuristic to confirm that the content is likely malformed JSON\n if content.strip().startswith((\"{\", \"[\")):\n raise json_error\n\n try:\n open_api_spec_content = yaml.safe_load(content)\n except yaml.YAMLError:\n error_message = (\n \"Failed to parse the OpenAPI specification. The content does not appear to be valid JSON or YAML.\\n\\n\"\n )\n raise RuntimeError(error_message, content)\n\n # Replace references in the object with their resolved values, if any\n return jsonref.replace_refs(open_api_spec_content)"}, {"class_start_lineno": 23, "class_end_lineno": 257, "func_start_lineno": 56, "func_end_lineno": 115, "func_code": " def run(self, sources: List[Union[str, Path, ByteStream]]) -> Dict[str, Any]:\n \"\"\"\n Converts OpenAPI definitions in OpenAI function calling format.\n\n :param sources:\n File paths or ByteStream objects of OpenAPI definitions (in JSON or YAML format).\n\n :returns:\n A dictionary with the following keys:\n - functions: Function definitions in JSON object format\n - openapi_specs: OpenAPI specs in JSON/YAML object format with resolved references\n\n :raises RuntimeError:\n If the OpenAPI definitions cannot be downloaded or processed.\n :raises ValueError:\n If the source type is not recognized or no functions are found in the OpenAPI definitions.\n \"\"\"\n all_extracted_fc_definitions: List[Dict[str, Any]] = []\n all_openapi_specs = []\n for source in sources:\n openapi_spec_content = None\n if isinstance(source, (str, Path)):\n if os.path.exists(source):\n try:\n with open(source, \"r\") as f:\n openapi_spec_content = f.read()\n except IOError as e:\n logger.warning(\n \"IO error reading OpenAPI specification file: {source}. Error: {e}\", source=source, e=e\n )\n else:\n logger.warning(f\"OpenAPI specification file not found: {source}\")\n elif isinstance(source, ByteStream):\n openapi_spec_content = source.data.decode(\"utf-8\")\n if not openapi_spec_content:\n logger.warning(\n \"Invalid OpenAPI specification content provided: {openapi_spec_content}\",\n openapi_spec_content=openapi_spec_content,\n )\n else:\n logger.warning(\n \"Invalid source type {source}. Only str, Path, and ByteStream are supported.\", source=type(source)\n )\n continue\n\n if openapi_spec_content:\n try:\n service_openapi_spec = self._parse_openapi_spec(openapi_spec_content)\n functions: List[Dict[str, Any]] = self._openapi_to_functions(service_openapi_spec)\n all_extracted_fc_definitions.extend(functions)\n all_openapi_specs.append(service_openapi_spec)\n except Exception as e:\n logger.error(\n \"Error processing OpenAPI specification from source {source}: {error}\", source=source, error=e\n )\n\n if not all_extracted_fc_definitions:\n logger.warning(\"No OpenAI function definitions extracted from the provided OpenAPI specification sources.\")\n\n return {\"functions\": all_extracted_fc_definitions, \"openapi_specs\": all_openapi_specs}"}, {"class_start_lineno": 23, "class_end_lineno": 257, "func_start_lineno": 193, "func_end_lineno": 230, "func_code": " def _parse_property_attributes(\n self, property_schema: Dict[str, Any], include_attributes: Optional[List[str]] = None\n ) -> Dict[str, Any]:\n \"\"\"\n Parses the attributes of a property schema.\n\n Recursively parses the attributes of a property schema, including nested objects and arrays,\n and includes specified attributes like description, pattern, etc.\n\n :param property_schema: The schema of the property to parse.\n :param include_attributes: The list of attributes to include in the parsed schema.\n :return: The parsed schema of the property including the specified attributes.\n \"\"\"\n include_attributes = include_attributes or [\"description\", \"pattern\", \"enum\"]\n\n schema_type = property_schema.get(\"type\")\n\n parsed_schema = {\"type\": schema_type} if schema_type else {}\n for attr in include_attributes:\n if attr in property_schema:\n parsed_schema[attr] = property_schema[attr]\n\n if schema_type == \"object\":\n properties = property_schema.get(\"properties\", {})\n parsed_properties = {\n prop_name: self._parse_property_attributes(prop, include_attributes)\n for prop_name, prop in properties.items()\n }\n parsed_schema[\"properties\"] = parsed_properties\n\n if \"required\" in property_schema:\n parsed_schema[\"required\"] = property_schema[\"required\"]\n\n elif schema_type == \"array\":\n items = property_schema.get(\"items\", {})\n parsed_schema[\"items\"] = self._parse_property_attributes(items, include_attributes)\n\n return parsed_schema"}, {"class_start_lineno": 23, "class_end_lineno": 257, "func_start_lineno": 153, "func_end_lineno": 191, "func_code": " def _parse_endpoint_spec(self, resolved_spec: Dict[str, Any]) -> Optional[Dict[str, Any]]:\n if not isinstance(resolved_spec, dict):\n logger.warning(\"Invalid OpenAPI spec format provided. Could not extract function.\")\n return {}\n\n function_name = resolved_spec.get(\"operationId\")\n description = resolved_spec.get(\"description\") or resolved_spec.get(\"summary\", \"\")\n\n schema: Dict[str, Any] = {\"type\": \"object\", \"properties\": {}}\n\n # requestBody section\n req_body_schema = (\n resolved_spec.get(\"requestBody\", {}).get(\"content\", {}).get(\"application/json\", {}).get(\"schema\", {})\n )\n if \"properties\" in req_body_schema:\n for prop_name, prop_schema in req_body_schema[\"properties\"].items():\n schema[\"properties\"][prop_name] = self._parse_property_attributes(prop_schema)\n\n if \"required\" in req_body_schema:\n schema.setdefault(\"required\", []).extend(req_body_schema[\"required\"])\n\n # parameters section\n for param in resolved_spec.get(\"parameters\", []):\n if \"schema\" in param:\n schema_dict = self._parse_property_attributes(param[\"schema\"])\n # these attributes are not in param[schema] level but on param level\n useful_attributes = [\"description\", \"pattern\", \"enum\"]\n schema_dict.update({key: param[key] for key in useful_attributes if param.get(key)})\n schema[\"properties\"][param[\"name\"]] = schema_dict\n if param.get(\"required\", False):\n schema.setdefault(\"required\", []).append(param[\"name\"])\n\n if function_name and description and schema[\"properties\"]:\n return {\"name\": function_name, \"description\": description, \"parameters\": schema}\n else:\n logger.warning(\n \"Invalid OpenAPI spec format provided. Could not extract function from {spec}\", spec=resolved_spec\n )\n return {}"}, {"class_start_lineno": 23, "class_end_lineno": 257, "func_start_lineno": 117, "func_end_lineno": 151, "func_code": " def _openapi_to_functions(self, service_openapi_spec: Dict[str, Any]) -> List[Dict[str, Any]]:\n \"\"\"\n OpenAPI to OpenAI function conversion.\n\n Extracts functions from the OpenAPI specification of the service and converts them into a format\n suitable for OpenAI function calling.\n\n :param service_openapi_spec: The OpenAPI specification from which functions are to be extracted.\n :type service_openapi_spec: Dict[str, Any]\n :return: A list of dictionaries, each representing a function. Each dictionary includes the function's\n name, description, and a schema of its parameters.\n :rtype: List[Dict[str, Any]]\n \"\"\"\n\n # Doesn't enforce rigid spec validation because that would require a lot of dependencies\n # We check the version and require minimal fields to be present, so we can extract functions\n spec_version = service_openapi_spec.get(\"openapi\")\n if not spec_version:\n raise ValueError(f\"Invalid OpenAPI spec provided. Could not extract version from {service_openapi_spec}\")\n service_openapi_spec_version = int(spec_version.split(\".\")[0])\n\n # Compare the versions\n if service_openapi_spec_version < OpenAPIServiceToFunctions.MIN_REQUIRED_OPENAPI_SPEC_VERSION:\n raise ValueError(\n f\"Invalid OpenAPI spec version {service_openapi_spec_version}. Must be \"\n f\"at least {OpenAPIServiceToFunctions.MIN_REQUIRED_OPENAPI_SPEC_VERSION}.\"\n )\n\n functions: List[Dict[str, Any]] = []\n for paths in service_openapi_spec[\"paths\"].values():\n for path_spec in paths.values():\n function_dict = self._parse_endpoint_spec(path_spec)\n if function_dict:\n functions.append(function_dict)\n return functions"}], "type": ["function_empty", "Development"], "node": ["haystack.components.converters.openapi_functions.OpenAPIServiceToFunctions._parse_openapi_spec", "haystack.components.converters.openapi_functions.OpenAPIServiceToFunctions.run", "haystack.components.converters.openapi_functions.OpenAPIServiceToFunctions._parse_property_attributes", "haystack.components.converters.openapi_functions.OpenAPIServiceToFunctions._parse_endpoint_spec", "haystack.components.converters.openapi_functions.OpenAPIServiceToFunctions._openapi_to_functions"], "language": "Python", "toolfunc_count": 3, "func_count": 5, "pytest_info": {"total_num": 8, "base_passed_num": 0}} {"id": ["haystack.haystack.utils.callable_serialization.serialize_callable", "haystack.haystack.components.converters.output_adapter.OutputAdapter::to_dict", "haystack.haystack.utils.type_serialization.thread_safe_import", "haystack.haystack.utils.callable_serialization.deserialize_callable"], "project": "haystack", "origin_file": ["haystack/utils/callable_serialization.py", "haystack/components/converters/output_adapter.py", "haystack/utils/type_serialization.py", "haystack/utils/callable_serialization.py"], "test_list": ["test/components/converters/test_output_adapter.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 80, "func_start_lineno": 12, "func_end_lineno": 42, "func_code": "def serialize_callable(callable_handle: Callable) -> str:\n \"\"\"\n Serializes a callable to its full path.\n\n :param callable_handle: The callable to serialize\n :return: The full path of the callable\n \"\"\"\n try:\n full_arg_spec = inspect.getfullargspec(callable_handle)\n is_instance_method = bool(full_arg_spec.args and full_arg_spec.args[0] == \"self\")\n except TypeError:\n is_instance_method = False\n if is_instance_method:\n raise SerializationError(\"Serialization of instance methods is not supported.\")\n\n # __qualname__ contains the fully qualified path we need for classmethods and staticmethods\n qualname = getattr(callable_handle, \"__qualname__\", \"\")\n if \"\" in qualname:\n raise SerializationError(\"Serialization of lambdas is not supported.\")\n if \"\" in qualname:\n raise SerializationError(\"Serialization of nested functions is not supported.\")\n\n name = qualname or callable_handle.__name__\n\n # Get the full package path of the function\n module = inspect.getmodule(callable_handle)\n if module is not None:\n full_path = f\"{module.__name__}.{name}\"\n else:\n full_path = name\n return full_path"}, {"class_start_lineno": 25, "class_end_lineno": 184, "func_start_lineno": 139, "func_end_lineno": 153, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serializes the component to a dictionary.\n\n :returns:\n Dictionary with serialized data.\n \"\"\"\n se_filters = {name: serialize_callable(filter_func) for name, filter_func in self.custom_filters.items()}\n return default_to_dict(\n self,\n template=self.template,\n output_type=serialize_type(self.output_type),\n custom_filters=se_filters,\n unsafe=self._unsafe,\n )"}, {"class_start_lineno": 1, "class_end_lineno": 170, "func_start_lineno": 159, "func_end_lineno": 170, "func_code": "def thread_safe_import(module_name: str) -> ModuleType:\n \"\"\"\n Import a module in a thread-safe manner.\n\n Importing modules in a multi-threaded environment can lead to race conditions.\n This function ensures that the module is imported in a thread-safe manner without having impact\n on the performance of the import for single-threaded environments.\n\n :param module_name: the module to import\n \"\"\"\n with _import_lock:\n return importlib.import_module(module_name)"}, {"class_start_lineno": 1, "class_end_lineno": 80, "func_start_lineno": 45, "func_end_lineno": 80, "func_code": "def deserialize_callable(callable_handle: str) -> Callable:\n \"\"\"\n Deserializes a callable given its full import path as a string.\n\n :param callable_handle: The full path of the callable_handle\n :return: The callable\n :raises DeserializationError: If the callable cannot be found\n \"\"\"\n parts = callable_handle.split(\".\")\n\n for i in range(len(parts), 0, -1):\n module_name = \".\".join(parts[:i])\n try:\n mod: Any = thread_safe_import(module_name)\n except Exception:\n # keep reducing i until we find a valid module import\n continue\n\n attr_value = mod\n for part in parts[i:]:\n try:\n attr_value = getattr(attr_value, part)\n except AttributeError as e:\n raise DeserializationError(f\"Could not find attribute '{part}' in {attr_value.__name__}\") from e\n\n # when the attribute is a classmethod, we need the underlying function\n if isinstance(attr_value, (classmethod, staticmethod)):\n attr_value = attr_value.__func__\n\n if not callable(attr_value):\n raise DeserializationError(f\"The final attribute is not callable: {attr_value}\")\n\n return attr_value\n\n # Fallback if we never find anything\n raise DeserializationError(f\"Could not import '{callable_handle}' as a module or callable.\")"}], "type": ["function_empty", "Development"], "node": ["haystack.utils.callable_serialization.serialize_callable", "haystack.components.converters.output_adapter.OutputAdapter.to_dict", "haystack.utils.type_serialization.thread_safe_import", "haystack.utils.callable_serialization.deserialize_callable"], "language": "Python", "toolfunc_count": 3, "func_count": 4, "pytest_info": {"total_num": 14, "base_passed_num": 9}} {"id": ["haystack.haystack.utils.callable_serialization.serialize_callable", "haystack.haystack.components.embedders.azure_document_embedder.AzureOpenAIDocumentEmbedder::to_dict", "haystack.haystack.utils.type_serialization.thread_safe_import", "haystack.haystack.utils.callable_serialization.deserialize_callable"], "project": "haystack", "origin_file": ["haystack/utils/callable_serialization.py", "haystack/components/embedders/azure_document_embedder.py", "haystack/utils/type_serialization.py", "haystack/utils/callable_serialization.py"], "test_list": ["test/components/embedders/test_azure_document_embedder.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 80, "func_start_lineno": 12, "func_end_lineno": 42, "func_code": "def serialize_callable(callable_handle: Callable) -> str:\n \"\"\"\n Serializes a callable to its full path.\n\n :param callable_handle: The callable to serialize\n :return: The full path of the callable\n \"\"\"\n try:\n full_arg_spec = inspect.getfullargspec(callable_handle)\n is_instance_method = bool(full_arg_spec.args and full_arg_spec.args[0] == \"self\")\n except TypeError:\n is_instance_method = False\n if is_instance_method:\n raise SerializationError(\"Serialization of instance methods is not supported.\")\n\n # __qualname__ contains the fully qualified path we need for classmethods and staticmethods\n qualname = getattr(callable_handle, \"__qualname__\", \"\")\n if \"\" in qualname:\n raise SerializationError(\"Serialization of lambdas is not supported.\")\n if \"\" in qualname:\n raise SerializationError(\"Serialization of nested functions is not supported.\")\n\n name = qualname or callable_handle.__name__\n\n # Get the full package path of the function\n module = inspect.getmodule(callable_handle)\n if module is not None:\n full_path = f\"{module.__name__}.{name}\"\n else:\n full_path = name\n return full_path"}, {"class_start_lineno": 20, "class_end_lineno": 281, "func_start_lineno": 154, "func_end_lineno": 183, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serializes the component to a dictionary.\n\n :returns:\n Dictionary with serialized data.\n \"\"\"\n azure_ad_token_provider_name = None\n if self.azure_ad_token_provider:\n azure_ad_token_provider_name = serialize_callable(self.azure_ad_token_provider)\n return default_to_dict(\n self,\n azure_endpoint=self.azure_endpoint,\n azure_deployment=self.azure_deployment,\n dimensions=self.dimensions,\n organization=self.organization,\n api_version=self.api_version,\n prefix=self.prefix,\n suffix=self.suffix,\n batch_size=self.batch_size,\n progress_bar=self.progress_bar,\n meta_fields_to_embed=self.meta_fields_to_embed,\n embedding_separator=self.embedding_separator,\n api_key=self.api_key.to_dict() if self.api_key is not None else None,\n azure_ad_token=self.azure_ad_token.to_dict() if self.azure_ad_token is not None else None,\n timeout=self.timeout,\n max_retries=self.max_retries,\n default_headers=self.default_headers,\n azure_ad_token_provider=azure_ad_token_provider_name,\n )"}, {"class_start_lineno": 1, "class_end_lineno": 170, "func_start_lineno": 159, "func_end_lineno": 170, "func_code": "def thread_safe_import(module_name: str) -> ModuleType:\n \"\"\"\n Import a module in a thread-safe manner.\n\n Importing modules in a multi-threaded environment can lead to race conditions.\n This function ensures that the module is imported in a thread-safe manner without having impact\n on the performance of the import for single-threaded environments.\n\n :param module_name: the module to import\n \"\"\"\n with _import_lock:\n return importlib.import_module(module_name)"}, {"class_start_lineno": 1, "class_end_lineno": 80, "func_start_lineno": 45, "func_end_lineno": 80, "func_code": "def deserialize_callable(callable_handle: str) -> Callable:\n \"\"\"\n Deserializes a callable given its full import path as a string.\n\n :param callable_handle: The full path of the callable_handle\n :return: The callable\n :raises DeserializationError: If the callable cannot be found\n \"\"\"\n parts = callable_handle.split(\".\")\n\n for i in range(len(parts), 0, -1):\n module_name = \".\".join(parts[:i])\n try:\n mod: Any = thread_safe_import(module_name)\n except Exception:\n # keep reducing i until we find a valid module import\n continue\n\n attr_value = mod\n for part in parts[i:]:\n try:\n attr_value = getattr(attr_value, part)\n except AttributeError as e:\n raise DeserializationError(f\"Could not find attribute '{part}' in {attr_value.__name__}\") from e\n\n # when the attribute is a classmethod, we need the underlying function\n if isinstance(attr_value, (classmethod, staticmethod)):\n attr_value = attr_value.__func__\n\n if not callable(attr_value):\n raise DeserializationError(f\"The final attribute is not callable: {attr_value}\")\n\n return attr_value\n\n # Fallback if we never find anything\n raise DeserializationError(f\"Could not import '{callable_handle}' as a module or callable.\")"}], "type": ["function_empty", "Development"], "node": ["haystack.utils.callable_serialization.serialize_callable", "haystack.components.embedders.azure_document_embedder.AzureOpenAIDocumentEmbedder.to_dict", "haystack.utils.type_serialization.thread_safe_import", "haystack.utils.callable_serialization.deserialize_callable"], "language": "Python", "toolfunc_count": 3, "func_count": 4, "pytest_info": {"total_num": 6, "base_passed_num": 3}} {"id": ["haystack.haystack.utils.callable_serialization.serialize_callable", "haystack.haystack.components.embedders.azure_text_embedder.AzureOpenAITextEmbedder::to_dict", "haystack.haystack.utils.type_serialization.thread_safe_import", "haystack.haystack.utils.callable_serialization.deserialize_callable"], "project": "haystack", "origin_file": ["haystack/utils/callable_serialization.py", "haystack/components/embedders/azure_text_embedder.py", "haystack/utils/type_serialization.py", "haystack/utils/callable_serialization.py"], "test_list": ["test/components/embedders/test_azure_text_embedder.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 80, "func_start_lineno": 12, "func_end_lineno": 42, "func_code": "def serialize_callable(callable_handle: Callable) -> str:\n \"\"\"\n Serializes a callable to its full path.\n\n :param callable_handle: The callable to serialize\n :return: The full path of the callable\n \"\"\"\n try:\n full_arg_spec = inspect.getfullargspec(callable_handle)\n is_instance_method = bool(full_arg_spec.args and full_arg_spec.args[0] == \"self\")\n except TypeError:\n is_instance_method = False\n if is_instance_method:\n raise SerializationError(\"Serialization of instance methods is not supported.\")\n\n # __qualname__ contains the fully qualified path we need for classmethods and staticmethods\n qualname = getattr(callable_handle, \"__qualname__\", \"\")\n if \"\" in qualname:\n raise SerializationError(\"Serialization of lambdas is not supported.\")\n if \"\" in qualname:\n raise SerializationError(\"Serialization of nested functions is not supported.\")\n\n name = qualname or callable_handle.__name__\n\n # Get the full package path of the function\n module = inspect.getmodule(callable_handle)\n if module is not None:\n full_path = f\"{module.__name__}.{name}\"\n else:\n full_path = name\n return full_path"}, {"class_start_lineno": 15, "class_end_lineno": 216, "func_start_lineno": 136, "func_end_lineno": 161, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serializes the component to a dictionary.\n\n :returns:\n Dictionary with serialized data.\n \"\"\"\n azure_ad_token_provider_name = None\n if self.azure_ad_token_provider:\n azure_ad_token_provider_name = serialize_callable(self.azure_ad_token_provider)\n return default_to_dict(\n self,\n azure_endpoint=self.azure_endpoint,\n azure_deployment=self.azure_deployment,\n dimensions=self.dimensions,\n organization=self.organization,\n api_version=self.api_version,\n prefix=self.prefix,\n suffix=self.suffix,\n api_key=self.api_key.to_dict() if self.api_key is not None else None,\n azure_ad_token=self.azure_ad_token.to_dict() if self.azure_ad_token is not None else None,\n timeout=self.timeout,\n max_retries=self.max_retries,\n default_headers=self.default_headers,\n azure_ad_token_provider=azure_ad_token_provider_name,\n )"}, {"class_start_lineno": 1, "class_end_lineno": 170, "func_start_lineno": 159, "func_end_lineno": 170, "func_code": "def thread_safe_import(module_name: str) -> ModuleType:\n \"\"\"\n Import a module in a thread-safe manner.\n\n Importing modules in a multi-threaded environment can lead to race conditions.\n This function ensures that the module is imported in a thread-safe manner without having impact\n on the performance of the import for single-threaded environments.\n\n :param module_name: the module to import\n \"\"\"\n with _import_lock:\n return importlib.import_module(module_name)"}, {"class_start_lineno": 1, "class_end_lineno": 80, "func_start_lineno": 45, "func_end_lineno": 80, "func_code": "def deserialize_callable(callable_handle: str) -> Callable:\n \"\"\"\n Deserializes a callable given its full import path as a string.\n\n :param callable_handle: The full path of the callable_handle\n :return: The callable\n :raises DeserializationError: If the callable cannot be found\n \"\"\"\n parts = callable_handle.split(\".\")\n\n for i in range(len(parts), 0, -1):\n module_name = \".\".join(parts[:i])\n try:\n mod: Any = thread_safe_import(module_name)\n except Exception:\n # keep reducing i until we find a valid module import\n continue\n\n attr_value = mod\n for part in parts[i:]:\n try:\n attr_value = getattr(attr_value, part)\n except AttributeError as e:\n raise DeserializationError(f\"Could not find attribute '{part}' in {attr_value.__name__}\") from e\n\n # when the attribute is a classmethod, we need the underlying function\n if isinstance(attr_value, (classmethod, staticmethod)):\n attr_value = attr_value.__func__\n\n if not callable(attr_value):\n raise DeserializationError(f\"The final attribute is not callable: {attr_value}\")\n\n return attr_value\n\n # Fallback if we never find anything\n raise DeserializationError(f\"Could not import '{callable_handle}' as a module or callable.\")"}], "type": ["function_empty", "Development"], "node": ["haystack.utils.callable_serialization.serialize_callable", "haystack.components.embedders.azure_text_embedder.AzureOpenAITextEmbedder.to_dict", "haystack.utils.type_serialization.thread_safe_import", "haystack.utils.callable_serialization.deserialize_callable"], "language": "Python", "toolfunc_count": 3, "func_count": 4, "pytest_info": {"total_num": 5, "base_passed_num": 2}} {"id": ["haystack.haystack.components.embedders.hugging_face_api_document_embedder.HuggingFaceAPIDocumentEmbedder::_embed_batch", "haystack.haystack.components.embedders.hugging_face_api_document_embedder.HuggingFaceAPIDocumentEmbedder::run"], "project": "haystack", "origin_file": ["haystack/components/embedders/hugging_face_api_document_embedder.py", "haystack/components/embedders/hugging_face_api_document_embedder.py"], "test_list": ["test/components/embedders/test_hugging_face_api_document_embedder.py"], "prob_info": [{"class_start_lineno": 24, "class_end_lineno": 298, "func_start_lineno": 236, "func_end_lineno": 271, "func_code": " def _embed_batch(self, texts_to_embed: List[str], batch_size: int) -> List[List[float]]:\n \"\"\"\n Embed a list of texts in batches.\n \"\"\"\n truncate = self.truncate\n normalize = self.normalize\n\n if self.api_type == HFEmbeddingAPIType.SERVERLESS_INFERENCE_API:\n if truncate is not None:\n msg = \"`truncate` parameter is not supported for Serverless Inference API. It will be ignored.\"\n warnings.warn(msg)\n truncate = None\n if normalize is not None:\n msg = \"`normalize` parameter is not supported for Serverless Inference API. It will be ignored.\"\n warnings.warn(msg)\n normalize = None\n\n all_embeddings = []\n for i in tqdm(\n range(0, len(texts_to_embed), batch_size), disable=not self.progress_bar, desc=\"Calculating embeddings\"\n ):\n batch = texts_to_embed[i : i + batch_size]\n\n np_embeddings = self._client.feature_extraction(\n # this method does not officially support list of strings, but works as expected\n text=batch, # type: ignore[arg-type]\n truncate=truncate,\n normalize=normalize,\n )\n\n if np_embeddings.ndim != 2 or np_embeddings.shape[0] != len(batch):\n raise ValueError(f\"Expected embedding shape ({batch_size}, embedding_dim), got {np_embeddings.shape}\")\n\n all_embeddings.extend(np_embeddings.tolist())\n\n return all_embeddings"}, {"class_start_lineno": 24, "class_end_lineno": 298, "func_start_lineno": 274, "func_end_lineno": 298, "func_code": " def run(self, documents: List[Document]):\n \"\"\"\n Embeds a list of documents.\n\n :param documents:\n Documents to embed.\n\n :returns:\n A dictionary with the following keys:\n - `documents`: A list of documents with embeddings.\n \"\"\"\n if not isinstance(documents, list) or documents and not isinstance(documents[0], Document):\n raise TypeError(\n \"HuggingFaceAPIDocumentEmbedder expects a list of Documents as input.\"\n \" In case you want to embed a string, please use the HuggingFaceAPITextEmbedder.\"\n )\n\n texts_to_embed = self._prepare_texts_to_embed(documents=documents)\n\n embeddings = self._embed_batch(texts_to_embed=texts_to_embed, batch_size=self.batch_size)\n\n for doc, emb in zip(documents, embeddings):\n doc.embedding = emb\n\n return {\"documents\": documents}"}], "type": ["function_empty", "Development"], "node": ["haystack.components.embedders.hugging_face_api_document_embedder.HuggingFaceAPIDocumentEmbedder._embed_batch", "haystack.components.embedders.hugging_face_api_document_embedder.HuggingFaceAPIDocumentEmbedder.run"], "language": "Python", "toolfunc_count": 1, "func_count": 2, "pytest_info": {"total_num": 17, "base_passed_num": 12}} {"id": ["haystack.haystack.components.embedders.openai_document_embedder.OpenAIDocumentEmbedder::_prepare_texts_to_embed", "haystack.haystack.components.embedders.openai_document_embedder.OpenAIDocumentEmbedder::_embed_batch", "haystack.haystack.components.embedders.openai_document_embedder.OpenAIDocumentEmbedder::run"], "project": "haystack", "origin_file": ["haystack/components/embedders/openai_document_embedder.py", "haystack/components/embedders/openai_document_embedder.py", "haystack/components/embedders/openai_document_embedder.py"], "test_list": ["test/components/embedders/test_openai_document_embedder.py"], "prob_info": [{"class_start_lineno": 19, "class_end_lineno": 245, "func_start_lineno": 164, "func_end_lineno": 181, "func_code": " def _prepare_texts_to_embed(self, documents: List[Document]) -> Dict[str, str]:\n \"\"\"\n Prepare the texts to embed by concatenating the Document text with the metadata fields to embed.\n \"\"\"\n texts_to_embed = {}\n for doc in documents:\n meta_values_to_embed = [\n str(doc.meta[key]) for key in self.meta_fields_to_embed if key in doc.meta and doc.meta[key] is not None\n ]\n\n text_to_embed = (\n self.prefix + self.embedding_separator.join(meta_values_to_embed + [doc.content or \"\"]) + self.suffix\n )\n\n # copied from OpenAI embedding_utils (https://github.com/openai/openai-python/blob/main/openai/embeddings_utils.py)\n # replace newlines, which can negatively affect performance.\n texts_to_embed[doc.id] = text_to_embed.replace(\"\\n\", \" \")\n return texts_to_embed"}, {"class_start_lineno": 19, "class_end_lineno": 245, "func_start_lineno": 183, "func_end_lineno": 217, "func_code": " def _embed_batch(self, texts_to_embed: Dict[str, str], batch_size: int) -> Tuple[List[List[float]], Dict[str, Any]]:\n \"\"\"\n Embed a list of texts in batches.\n \"\"\"\n\n all_embeddings = []\n meta: Dict[str, Any] = {}\n for batch in tqdm(\n batched(texts_to_embed.items(), batch_size), disable=not self.progress_bar, desc=\"Calculating embeddings\"\n ):\n args: Dict[str, Any] = {\"model\": self.model, \"input\": [b[1] for b in batch]}\n\n if self.dimensions is not None:\n args[\"dimensions\"] = self.dimensions\n\n try:\n response = self.client.embeddings.create(**args)\n except APIError as exc:\n ids = \", \".join(b[0] for b in batch)\n msg = \"Failed embedding of documents {ids} caused by {exc}\"\n logger.exception(msg, ids=ids, exc=exc)\n continue\n\n embeddings = [el.embedding for el in response.data]\n all_embeddings.extend(embeddings)\n\n if \"model\" not in meta:\n meta[\"model\"] = response.model\n if \"usage\" not in meta:\n meta[\"usage\"] = dict(response.usage)\n else:\n meta[\"usage\"][\"prompt_tokens\"] += response.usage.prompt_tokens\n meta[\"usage\"][\"total_tokens\"] += response.usage.total_tokens\n\n return all_embeddings, meta"}, {"class_start_lineno": 19, "class_end_lineno": 245, "func_start_lineno": 220, "func_end_lineno": 245, "func_code": " def run(self, documents: List[Document]):\n \"\"\"\n Embeds a list of documents.\n\n :param documents:\n A list of documents to embed.\n\n :returns:\n A dictionary with the following keys:\n - `documents`: A list of documents with embeddings.\n - `meta`: Information about the usage of the model.\n \"\"\"\n if not isinstance(documents, list) or documents and not isinstance(documents[0], Document):\n raise TypeError(\n \"OpenAIDocumentEmbedder expects a list of Documents as input.\"\n \"In case you want to embed a string, please use the OpenAITextEmbedder.\"\n )\n\n texts_to_embed = self._prepare_texts_to_embed(documents=documents)\n\n embeddings, meta = self._embed_batch(texts_to_embed=texts_to_embed, batch_size=self.batch_size)\n\n for doc, emb in zip(documents, embeddings):\n doc.embedding = emb\n\n return {\"documents\": documents, \"meta\": meta}"}], "type": ["function_empty", "Development"], "node": ["haystack.components.embedders.openai_document_embedder.OpenAIDocumentEmbedder._prepare_texts_to_embed", "haystack.components.embedders.openai_document_embedder.OpenAIDocumentEmbedder._embed_batch", "haystack.components.embedders.openai_document_embedder.OpenAIDocumentEmbedder.run"], "language": "Python", "toolfunc_count": 2, "func_count": 3, "pytest_info": {"total_num": 11, "base_passed_num": 4}} {"id": ["haystack.haystack.utils.device.ComponentDevice::to_dict", "haystack.haystack.components.embedders.sentence_transformers_document_embedder.SentenceTransformersDocumentEmbedder::to_dict"], "project": "haystack", "origin_file": ["haystack/utils/device.py", "haystack/components/embedders/sentence_transformers_document_embedder.py"], "test_list": ["test/components/embedders/test_sentence_transformers_document_embedder.py"], "prob_info": [{"class_start_lineno": 240, "class_end_lineno": 480, "func_start_lineno": 450, "func_end_lineno": 463, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Convert the component device representation to a JSON-serializable dictionary.\n\n :returns:\n The dictionary representation.\n \"\"\"\n if self._single_device is not None:\n return {\"type\": \"single\", \"device\": str(self._single_device)}\n elif self._multiple_devices is not None:\n return {\"type\": \"multiple\", \"device_map\": self._multiple_devices.to_dict()}\n else:\n # Unreachable\n assert False"}, {"class_start_lineno": 16, "class_end_lineno": 256, "func_start_lineno": 145, "func_end_lineno": 175, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serializes the component to a dictionary.\n\n :returns:\n Dictionary with serialized data.\n \"\"\"\n serialization_dict = default_to_dict(\n self,\n model=self.model,\n device=self.device.to_dict(),\n token=self.token.to_dict() if self.token else None,\n prefix=self.prefix,\n suffix=self.suffix,\n batch_size=self.batch_size,\n progress_bar=self.progress_bar,\n normalize_embeddings=self.normalize_embeddings,\n meta_fields_to_embed=self.meta_fields_to_embed,\n embedding_separator=self.embedding_separator,\n trust_remote_code=self.trust_remote_code,\n truncate_dim=self.truncate_dim,\n model_kwargs=self.model_kwargs,\n tokenizer_kwargs=self.tokenizer_kwargs,\n config_kwargs=self.config_kwargs,\n precision=self.precision,\n encode_kwargs=self.encode_kwargs,\n backend=self.backend,\n )\n if serialization_dict[\"init_parameters\"].get(\"model_kwargs\") is not None:\n serialize_hf_model_kwargs(serialization_dict[\"init_parameters\"][\"model_kwargs\"])\n return serialization_dict"}], "type": ["function_empty"], "node": ["haystack.utils.device.ComponentDevice.to_dict", "haystack.components.embedders.sentence_transformers_document_embedder.SentenceTransformersDocumentEmbedder.to_dict"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 18, "base_passed_num": 15}} {"id": ["haystack.haystack.utils.device.ComponentDevice::to_dict", "haystack.haystack.components.embedders.sentence_transformers_text_embedder.SentenceTransformersTextEmbedder::to_dict", "haystack.haystack.utils.device.ComponentDevice::to_torch_str", "haystack.haystack.components.embedders.sentence_transformers_text_embedder.SentenceTransformersTextEmbedder::warm_up"], "project": "haystack", "origin_file": ["haystack/utils/device.py", "haystack/components/embedders/sentence_transformers_text_embedder.py", "haystack/utils/device.py", "haystack/components/embedders/sentence_transformers_text_embedder.py"], "test_list": ["test/components/embedders/test_sentence_transformers_text_embedder.py"], "prob_info": [{"class_start_lineno": 240, "class_end_lineno": 480, "func_start_lineno": 450, "func_end_lineno": 463, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Convert the component device representation to a JSON-serializable dictionary.\n\n :returns:\n The dictionary representation.\n \"\"\"\n if self._single_device is not None:\n return {\"type\": \"single\", \"device\": str(self._single_device)}\n elif self._multiple_devices is not None:\n return {\"type\": \"multiple\", \"device_map\": self._multiple_devices.to_dict()}\n else:\n # Unreachable\n assert False"}, {"class_start_lineno": 16, "class_end_lineno": 229, "func_start_lineno": 133, "func_end_lineno": 161, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serializes the component to a dictionary.\n\n :returns:\n Dictionary with serialized data.\n \"\"\"\n serialization_dict = default_to_dict(\n self,\n model=self.model,\n device=self.device.to_dict(),\n token=self.token.to_dict() if self.token else None,\n prefix=self.prefix,\n suffix=self.suffix,\n batch_size=self.batch_size,\n progress_bar=self.progress_bar,\n normalize_embeddings=self.normalize_embeddings,\n trust_remote_code=self.trust_remote_code,\n truncate_dim=self.truncate_dim,\n model_kwargs=self.model_kwargs,\n tokenizer_kwargs=self.tokenizer_kwargs,\n config_kwargs=self.config_kwargs,\n precision=self.precision,\n encode_kwargs=self.encode_kwargs,\n backend=self.backend,\n )\n if serialization_dict[\"init_parameters\"].get(\"model_kwargs\") is not None:\n serialize_hf_model_kwargs(serialization_dict[\"init_parameters\"][\"model_kwargs\"])\n return serialization_dict"}, {"class_start_lineno": 240, "class_end_lineno": 480, "func_start_lineno": 321, "func_end_lineno": 336, "func_code": " def to_torch_str(self) -> str:\n \"\"\"\n Convert the component device representation to PyTorch string format.\n\n Device maps are not supported.\n\n :returns:\n The PyTorch device string representation.\n \"\"\"\n self._validate()\n\n if self._single_device is None:\n raise ValueError(\"Only single devices can be converted to PyTorch format\")\n\n assert self._single_device is not None\n return str(self._single_device)"}, {"class_start_lineno": 16, "class_end_lineno": 229, "func_start_lineno": 181, "func_end_lineno": 198, "func_code": " def warm_up(self):\n \"\"\"\n Initializes the component.\n \"\"\"\n if self.embedding_backend is None:\n self.embedding_backend = _SentenceTransformersEmbeddingBackendFactory.get_embedding_backend(\n model=self.model,\n device=self.device.to_torch_str(),\n auth_token=self.token,\n trust_remote_code=self.trust_remote_code,\n truncate_dim=self.truncate_dim,\n model_kwargs=self.model_kwargs,\n tokenizer_kwargs=self.tokenizer_kwargs,\n config_kwargs=self.config_kwargs,\n backend=self.backend,\n )\n if self.tokenizer_kwargs and self.tokenizer_kwargs.get(\"model_max_length\"):\n self.embedding_backend.model.max_seq_length = self.tokenizer_kwargs[\"model_max_length\"]"}], "type": ["function_empty", "Development"], "node": ["haystack.utils.device.ComponentDevice.to_dict", "haystack.components.embedders.sentence_transformers_text_embedder.SentenceTransformersTextEmbedder.to_dict", "haystack.utils.device.ComponentDevice.to_torch_str", "haystack.components.embedders.sentence_transformers_text_embedder.SentenceTransformersTextEmbedder.warm_up"], "language": "Python", "toolfunc_count": 3, "func_count": 4, "pytest_info": {"total_num": 19, "base_passed_num": 8}} {"id": ["haystack.haystack.utils.type_serialization.serialize_type", "haystack.haystack.components.evaluators.llm_evaluator.LLMEvaluator::to_dict", "haystack.haystack.core.serialization.component_to_dict", "haystack.haystack.utils.type_serialization.deserialize_type", "haystack.haystack.core.serialization.component_from_dict"], "project": "haystack", "origin_file": ["haystack/utils/type_serialization.py", "haystack/components/evaluators/llm_evaluator.py", "haystack/core/serialization.py", "haystack/utils/type_serialization.py", "haystack/core/serialization.py"], "test_list": ["test/components/evaluators/test_llm_evaluator.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 170, "func_start_lineno": 19, "func_end_lineno": 52, "func_code": "def serialize_type(target: Any) -> str:\n \"\"\"\n Serializes a type or an instance to its string representation, including the module name.\n\n This function handles types, instances of types, and special typing objects.\n It assumes that non-typing objects will have a '__name__' attribute.\n\n :param target:\n The object to serialize, can be an instance or a type.\n :return:\n The string representation of the type.\n \"\"\"\n name = getattr(target, \"__name__\", str(target))\n\n # Remove the 'typing.' prefix when using python <3.9\n if name.startswith(\"typing.\"):\n name = name[7:]\n # Remove the arguments from the name when using python <3.9\n if \"[\" in name:\n name = name.split(\"[\")[0]\n\n # Get module name\n module = inspect.getmodule(target)\n module_name = \"\"\n # We omit the module name for builtins to not clutter the output\n if module and hasattr(module, \"__name__\") and module.__name__ != \"builtins\":\n module_name = f\"{module.__name__}\"\n\n args = get_args(target)\n if args:\n args_str = \", \".join([serialize_type(a) for a in args if a is not type(None)])\n return f\"{module_name}.{name}[{args_str}]\" if module_name else f\"{name}[{args_str}]\"\n\n return f\"{module_name}.{name}\" if module_name else f\"{name}\""}, {"class_start_lineno": 18, "class_end_lineno": 387, "func_start_lineno": 278, "func_end_lineno": 297, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serialize this component to a dictionary.\n\n :returns:\n The serialized component as a dictionary.\n \"\"\"\n # Since we cannot currently serialize tuples, convert the inputs to a list.\n inputs = [[name, serialize_type(type_)] for name, type_ in self.inputs]\n return default_to_dict(\n self,\n instructions=self.instructions,\n inputs=inputs,\n outputs=self.outputs,\n examples=self.examples,\n api=self.api,\n api_key=self.api_key and self.api_key.to_dict(),\n api_params=self.api_params,\n progress_bar=self.progress_bar,\n )"}, {"class_start_lineno": 1, "class_end_lineno": 264, "func_start_lineno": 36, "func_end_lineno": 82, "func_code": "def component_to_dict(obj: Any, name: str) -> Dict[str, Any]:\n \"\"\"\n Converts a component instance into a dictionary.\n\n If a `to_dict` method is present in the component instance, that will be used instead of the default method.\n\n :param obj:\n The component to be serialized.\n :param name:\n The name of the component.\n :returns:\n A dictionary representation of the component.\n\n :raises SerializationError:\n If the component doesn't have a `to_dict` method.\n If the values of the init parameters can't be determined.\n If a non-basic Python type is used in the serialized data.\n \"\"\"\n if hasattr(obj, \"to_dict\"):\n data = obj.to_dict()\n else:\n init_parameters = {}\n for param_name, param in inspect.signature(obj.__init__).parameters.items():\n # Ignore `args` and `kwargs`, used by the default constructor\n if param_name in (\"args\", \"kwargs\"):\n continue\n try:\n # This only works if the Component constructor assigns the init\n # parameter to an instance variable or property with the same name\n param_value = getattr(obj, param_name)\n except AttributeError as e:\n # If the parameter doesn't have a default value, raise an error\n if param.default is param.empty:\n raise SerializationError(\n f\"Cannot determine the value of the init parameter '{param_name}' \"\n f\"for the class {obj.__class__.__name__}.\"\n f\"You can fix this error by assigning 'self.{param_name} = {param_name}' or adding a \"\n f\"custom serialization method 'to_dict' to the class.\"\n ) from e\n # In case the init parameter was not assigned, we use the default value\n param_value = param.default\n init_parameters[param_name] = param_value\n\n data = default_to_dict(obj, **init_parameters)\n\n _validate_component_to_dict_output(obj, name, data)\n return data"}, {"class_start_lineno": 1, "class_end_lineno": 170, "func_start_lineno": 78, "func_end_lineno": 156, "func_code": "def deserialize_type(type_str: str) -> Any: # pylint: disable=too-many-return-statements\n \"\"\"\n Deserializes a type given its full import path as a string, including nested generic types.\n\n This function will dynamically import the module if it's not already imported\n and then retrieve the type object from it. It also handles nested generic types like\n `typing.List[typing.Dict[int, str]]`.\n\n :param type_str:\n The string representation of the type's full import path.\n :returns:\n The deserialized type object.\n :raises DeserializationError:\n If the type cannot be deserialized due to missing module or type.\n \"\"\"\n\n type_mapping = {\n list: typing.List,\n dict: typing.Dict,\n set: typing.Set,\n tuple: typing.Tuple,\n frozenset: typing.FrozenSet,\n }\n\n # Handle generics\n if \"[\" in type_str and type_str.endswith(\"]\"):\n main_type_str, generics_str = type_str.split(\"[\", 1)\n generics_str = generics_str[:-1]\n\n main_type = deserialize_type(main_type_str)\n generic_args = [deserialize_type(arg) for arg in _parse_generic_args(generics_str)]\n\n # Reconstruct\n try:\n if sys.version_info >= (3, 9) or repr(main_type).startswith(\"typing.\"):\n return main_type[tuple(generic_args) if len(generic_args) > 1 else generic_args[0]]\n else:\n return type_mapping[main_type][tuple(generic_args) if len(generic_args) > 1 else generic_args[0]]\n except (TypeError, AttributeError) as e:\n raise DeserializationError(f\"Could not apply arguments {generic_args} to type {main_type}\") from e\n\n # Handle non-generic types\n # First, check if there's a module prefix\n if \".\" in type_str:\n parts = type_str.split(\".\")\n module_name = \".\".join(parts[:-1])\n type_name = parts[-1]\n\n module = sys.modules.get(module_name)\n if module is None:\n try:\n module = thread_safe_import(module_name)\n except ImportError as e:\n raise DeserializationError(f\"Could not import the module: {module_name}\") from e\n\n # Get the class from the module\n if hasattr(module, type_name):\n return getattr(module, type_name)\n\n raise DeserializationError(f\"Could not locate the type: {type_name} in the module: {module_name}\")\n\n # No module prefix, check builtins and typing\n # First check builtins\n if hasattr(builtins, type_str):\n return getattr(builtins, type_str)\n\n # Then check typing\n if hasattr(typing, type_str):\n return getattr(typing, type_str)\n\n # Special case for NoneType\n if type_str == \"NoneType\":\n return type(None)\n\n # Special case for None\n if type_str == \"None\":\n return None\n\n raise DeserializationError(f\"Could not deserialize type: {type_str}\")"}, {"class_start_lineno": 1, "class_end_lineno": 264, "func_start_lineno": 134, "func_end_lineno": 169, "func_code": "def component_from_dict(\n cls: Type[object], data: Dict[str, Any], name: str, callbacks: Optional[DeserializationCallbacks] = None\n) -> Any:\n \"\"\"\n Creates a component instance from a dictionary.\n\n If a `from_dict` method is present in the component class, that will be used instead of the default method.\n\n :param cls:\n The class to be used for deserialization.\n :param data:\n The serialized data.\n :param name:\n The name of the component.\n :param callbacks:\n Callbacks to invoke during deserialization.\n :returns:\n The deserialized component.\n \"\"\"\n\n def component_pre_init_callback(component_cls, init_params):\n assert callbacks is not None\n assert callbacks.component_pre_init is not None\n callbacks.component_pre_init(name, component_cls, init_params)\n\n def do_from_dict():\n if hasattr(cls, \"from_dict\"):\n return cls.from_dict(data)\n\n return default_from_dict(cls, data)\n\n if callbacks is None or callbacks.component_pre_init is None:\n return do_from_dict()\n\n with _hook_component_init(component_pre_init_callback):\n return do_from_dict()"}], "type": ["function_empty", "Development"], "node": ["haystack.utils.type_serialization.serialize_type", "haystack.components.evaluators.llm_evaluator.LLMEvaluator.to_dict", "haystack.core.serialization.component_to_dict", "haystack.utils.type_serialization.deserialize_type", "haystack.core.serialization.component_from_dict"], "language": "Python", "toolfunc_count": 2, "func_count": 5, "pytest_info": {"total_num": 17, "base_passed_num": 12}} {"id": ["haystack.haystack.utils.device.ComponentDevice::to_dict", "haystack.haystack.components.evaluators.sas_evaluator.SASEvaluator::to_dict"], "project": "haystack", "origin_file": ["haystack/utils/device.py", "haystack/components/evaluators/sas_evaluator.py"], "test_list": ["test/components/evaluators/test_sas_evaluator.py"], "prob_info": [{"class_start_lineno": 240, "class_end_lineno": 480, "func_start_lineno": 450, "func_end_lineno": 463, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Convert the component device representation to a JSON-serializable dictionary.\n\n :returns:\n The dictionary representation.\n \"\"\"\n if self._single_device is not None:\n return {\"type\": \"single\", \"device\": str(self._single_device)}\n elif self._multiple_devices is not None:\n return {\"type\": \"multiple\", \"device_map\": self._multiple_devices.to_dict()}\n else:\n # Unreachable\n assert False"}, {"class_start_lineno": 20, "class_end_lineno": 201, "func_start_lineno": 85, "func_end_lineno": 98, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serialize this component to a dictionary.\n\n :returns:\n The serialized component as a dictionary.\n \"\"\"\n return default_to_dict(\n self,\n model=self._model,\n batch_size=self._batch_size,\n device=self._device.to_dict() if self._device else None,\n token=self._token.to_dict() if self._token else None,\n )"}], "type": ["function_empty"], "node": ["haystack.utils.device.ComponentDevice.to_dict", "haystack.components.evaluators.sas_evaluator.SASEvaluator.to_dict"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 12, "base_passed_num": 11}} {"id": ["haystack.haystack.components.generators.chat.openai.OpenAIChatGenerator::to_dict", "haystack.haystack.components.extractors.llm_metadata_extractor.LLMMetadataExtractor::to_dict", "haystack.haystack.components.builders.prompt_builder.PromptBuilder::_validate_variables", "haystack.haystack.components.builders.prompt_builder.PromptBuilder::run", "haystack.haystack.components.extractors.llm_metadata_extractor.LLMMetadataExtractor::_prepare_prompts"], "project": "haystack", "origin_file": ["haystack/components/generators/chat/openai.py", "haystack/components/extractors/llm_metadata_extractor.py", "haystack/components/builders/prompt_builder.py", "haystack/components/builders/prompt_builder.py", "haystack/components/extractors/llm_metadata_extractor.py"], "test_list": ["test/components/extractors/test_llm_metadata_extractor.py"], "prob_info": [{"class_start_lineno": 32, "class_end_lineno": 571, "func_start_lineno": 170, "func_end_lineno": 190, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serialize this component to a dictionary.\n\n :returns:\n The serialized component as a dictionary.\n \"\"\"\n callback_name = serialize_callable(self.streaming_callback) if self.streaming_callback else None\n return default_to_dict(\n self,\n model=self.model,\n streaming_callback=callback_name,\n api_base_url=self.api_base_url,\n organization=self.organization,\n generation_kwargs=self.generation_kwargs,\n api_key=self.api_key.to_dict(),\n timeout=self.timeout,\n max_retries=self.max_retries,\n tools=[tool.to_dict() for tool in self.tools] if self.tools else None,\n tools_strict=self.tools_strict,\n )"}, {"class_start_lineno": 61, "class_end_lineno": 442, "func_start_lineno": 239, "func_end_lineno": 258, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serializes the component to a dictionary.\n\n :returns:\n Dictionary with serialized data.\n \"\"\"\n\n llm_provider = self.llm_provider.to_dict()\n\n return default_to_dict(\n self,\n prompt=self.prompt,\n generator_api=self.generator_api.value,\n generator_api_params=llm_provider[\"init_parameters\"],\n expected_keys=self.expected_keys,\n page_range=self.expanded_range,\n raise_on_failure=self.raise_on_failure,\n max_workers=self.max_workers,\n )"}, {"class_start_lineno": 17, "class_end_lineno": 266, "func_start_lineno": 247, "func_end_lineno": 266, "func_code": " def _validate_variables(self, provided_variables: Set[str]):\n \"\"\"\n Checks if all the required template variables are provided.\n\n :param provided_variables:\n A set of provided template variables.\n :raises ValueError:\n If any of the required template variables is not provided.\n \"\"\"\n if self.required_variables == \"*\":\n required_variables = sorted(self.variables)\n else:\n required_variables = self.required_variables\n missing_variables = [var for var in required_variables if var not in provided_variables]\n if missing_variables:\n missing_vars_str = \", \".join(missing_variables)\n raise ValueError(\n f\"Missing required input variables in PromptBuilder: {missing_vars_str}. \"\n f\"Required variables: {required_variables}. Provided variables: {provided_variables}.\"\n )"}, {"class_start_lineno": 17, "class_end_lineno": 266, "func_start_lineno": 213, "func_end_lineno": 245, "func_code": " def run(self, template: Optional[str] = None, template_variables: Optional[Dict[str, Any]] = None, **kwargs):\n \"\"\"\n Renders the prompt template with the provided variables.\n\n It applies the template variables to render the final prompt. You can provide variables via pipeline kwargs.\n In order to overwrite the default template, you can set the `template` parameter.\n In order to overwrite pipeline kwargs, you can set the `template_variables` parameter.\n\n :param template:\n An optional string template to overwrite PromptBuilder's default template. If None, the default template\n provided at initialization is used.\n :param template_variables:\n An optional dictionary of template variables to overwrite the pipeline variables.\n :param kwargs:\n Pipeline variables used for rendering the prompt.\n\n :returns: A dictionary with the following keys:\n - `prompt`: The updated prompt text after rendering the prompt template.\n\n :raises ValueError:\n If any of the required template variables is not provided.\n \"\"\"\n kwargs = kwargs or {}\n template_variables = template_variables or {}\n template_variables_combined = {**kwargs, **template_variables}\n self._validate_variables(set(template_variables_combined.keys()))\n\n compiled_template = self.template\n if template is not None:\n compiled_template = self._env.from_string(template)\n\n result = compiled_template.render(template_variables_combined)\n return {\"prompt\": result}"}, {"class_start_lineno": 61, "class_end_lineno": 442, "func_start_lineno": 332, "func_end_lineno": 359, "func_code": " def _prepare_prompts(\n self, documents: List[Document], expanded_range: Optional[List[int]] = None\n ) -> List[Union[ChatMessage, None]]:\n all_prompts: List[Union[ChatMessage, None]] = []\n for document in documents:\n if not document.content:\n logger.warning(\"Document {doc_id} has no content. Skipping metadata extraction.\", doc_id=document.id)\n all_prompts.append(None)\n continue\n\n if expanded_range:\n doc_copy = copy.deepcopy(document)\n pages = self.splitter.run(documents=[doc_copy])\n content = \"\"\n for idx, page in enumerate(pages[\"documents\"]):\n if idx + 1 in expanded_range:\n content += page.content\n doc_copy.content = content\n else:\n doc_copy = document\n\n prompt_with_doc = self.builder.run(template=self.prompt, template_variables={\"document\": doc_copy})\n\n # build a ChatMessage with the prompt\n message = ChatMessage.from_user(prompt_with_doc[\"prompt\"])\n all_prompts.append(message)\n\n return all_prompts"}], "type": ["function_empty", "Development"], "node": ["haystack.components.generators.chat.openai.OpenAIChatGenerator.to_dict", "haystack.components.extractors.llm_metadata_extractor.LLMMetadataExtractor.to_dict", "haystack.components.builders.prompt_builder.PromptBuilder._validate_variables", "haystack.components.builders.prompt_builder.PromptBuilder.run", "haystack.components.extractors.llm_metadata_extractor.LLMMetadataExtractor._prepare_prompts"], "language": "Python", "toolfunc_count": 4, "func_count": 5, "pytest_info": {"total_num": 13, "base_passed_num": 9}} {"id": ["haystack.haystack.components.extractors.named_entity_extractor.NamedEntityExtractor::to_dict", "haystack.haystack.core.serialization.component_to_dict"], "project": "haystack", "origin_file": ["haystack/components/extractors/named_entity_extractor.py", "haystack/core/serialization.py"], "test_list": ["test/components/extractors/test_named_entity_extractor.py"], "prob_info": [{"class_start_lineno": 78, "class_end_lineno": 275, "func_start_lineno": 212, "func_end_lineno": 232, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serializes the component to a dictionary.\n\n :returns:\n Dictionary with serialized data.\n \"\"\"\n serialization_dict = default_to_dict(\n self,\n backend=self._backend.type.name,\n model=self._backend.model_name,\n device=self._backend.device.to_dict(),\n pipeline_kwargs=self._backend._pipeline_kwargs,\n token=self.token.to_dict() if self.token else None,\n )\n\n hf_pipeline_kwargs = serialization_dict[\"init_parameters\"][\"pipeline_kwargs\"]\n hf_pipeline_kwargs.pop(\"token\", None)\n\n serialize_hf_model_kwargs(hf_pipeline_kwargs)\n return serialization_dict"}, {"class_start_lineno": 1, "class_end_lineno": 264, "func_start_lineno": 36, "func_end_lineno": 82, "func_code": "def component_to_dict(obj: Any, name: str) -> Dict[str, Any]:\n \"\"\"\n Converts a component instance into a dictionary.\n\n If a `to_dict` method is present in the component instance, that will be used instead of the default method.\n\n :param obj:\n The component to be serialized.\n :param name:\n The name of the component.\n :returns:\n A dictionary representation of the component.\n\n :raises SerializationError:\n If the component doesn't have a `to_dict` method.\n If the values of the init parameters can't be determined.\n If a non-basic Python type is used in the serialized data.\n \"\"\"\n if hasattr(obj, \"to_dict\"):\n data = obj.to_dict()\n else:\n init_parameters = {}\n for param_name, param in inspect.signature(obj.__init__).parameters.items():\n # Ignore `args` and `kwargs`, used by the default constructor\n if param_name in (\"args\", \"kwargs\"):\n continue\n try:\n # This only works if the Component constructor assigns the init\n # parameter to an instance variable or property with the same name\n param_value = getattr(obj, param_name)\n except AttributeError as e:\n # If the parameter doesn't have a default value, raise an error\n if param.default is param.empty:\n raise SerializationError(\n f\"Cannot determine the value of the init parameter '{param_name}' \"\n f\"for the class {obj.__class__.__name__}.\"\n f\"You can fix this error by assigning 'self.{param_name} = {param_name}' or adding a \"\n f\"custom serialization method 'to_dict' to the class.\"\n ) from e\n # In case the init parameter was not assigned, we use the default value\n param_value = param.default\n init_parameters[param_name] = param_value\n\n data = default_to_dict(obj, **init_parameters)\n\n _validate_component_to_dict_output(obj, name, data)\n return data"}], "type": ["function_empty", "Development"], "node": ["haystack.components.extractors.named_entity_extractor.NamedEntityExtractor.to_dict", "haystack.core.serialization.component_to_dict"], "language": "Python", "toolfunc_count": 1, "func_count": 2, "pytest_info": {"total_num": 7, "base_passed_num": 2}} {"id": ["haystack.haystack.utils.callable_serialization.serialize_callable", "haystack.haystack.components.generators.azure.AzureOpenAIGenerator::to_dict", "haystack.haystack.core.serialization.component_to_dict"], "project": "haystack", "origin_file": ["haystack/utils/callable_serialization.py", "haystack/components/generators/azure.py", "haystack/core/serialization.py"], "test_list": ["test/components/generators/test_azure.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 80, "func_start_lineno": 12, "func_end_lineno": 42, "func_code": "def serialize_callable(callable_handle: Callable) -> str:\n \"\"\"\n Serializes a callable to its full path.\n\n :param callable_handle: The callable to serialize\n :return: The full path of the callable\n \"\"\"\n try:\n full_arg_spec = inspect.getfullargspec(callable_handle)\n is_instance_method = bool(full_arg_spec.args and full_arg_spec.args[0] == \"self\")\n except TypeError:\n is_instance_method = False\n if is_instance_method:\n raise SerializationError(\"Serialization of instance methods is not supported.\")\n\n # __qualname__ contains the fully qualified path we need for classmethods and staticmethods\n qualname = getattr(callable_handle, \"__qualname__\", \"\")\n if \"\" in qualname:\n raise SerializationError(\"Serialization of lambdas is not supported.\")\n if \"\" in qualname:\n raise SerializationError(\"Serialization of nested functions is not supported.\")\n\n name = qualname or callable_handle.__name__\n\n # Get the full package path of the function\n module = inspect.getmodule(callable_handle)\n if module is not None:\n full_path = f\"{module.__name__}.{name}\"\n else:\n full_path = name\n return full_path"}, {"class_start_lineno": 19, "class_end_lineno": 210, "func_start_lineno": 162, "func_end_lineno": 188, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serialize this component to a dictionary.\n\n :returns:\n The serialized component as a dictionary.\n \"\"\"\n callback_name = serialize_callable(self.streaming_callback) if self.streaming_callback else None\n azure_ad_token_provider_name = None\n if self.azure_ad_token_provider:\n azure_ad_token_provider_name = serialize_callable(self.azure_ad_token_provider)\n return default_to_dict(\n self,\n azure_endpoint=self.azure_endpoint,\n azure_deployment=self.azure_deployment,\n organization=self.organization,\n api_version=self.api_version,\n streaming_callback=callback_name,\n generation_kwargs=self.generation_kwargs,\n system_prompt=self.system_prompt,\n api_key=self.api_key.to_dict() if self.api_key is not None else None,\n azure_ad_token=self.azure_ad_token.to_dict() if self.azure_ad_token is not None else None,\n timeout=self.timeout,\n max_retries=self.max_retries,\n default_headers=self.default_headers,\n azure_ad_token_provider=azure_ad_token_provider_name,\n )"}, {"class_start_lineno": 1, "class_end_lineno": 264, "func_start_lineno": 36, "func_end_lineno": 82, "func_code": "def component_to_dict(obj: Any, name: str) -> Dict[str, Any]:\n \"\"\"\n Converts a component instance into a dictionary.\n\n If a `to_dict` method is present in the component instance, that will be used instead of the default method.\n\n :param obj:\n The component to be serialized.\n :param name:\n The name of the component.\n :returns:\n A dictionary representation of the component.\n\n :raises SerializationError:\n If the component doesn't have a `to_dict` method.\n If the values of the init parameters can't be determined.\n If a non-basic Python type is used in the serialized data.\n \"\"\"\n if hasattr(obj, \"to_dict\"):\n data = obj.to_dict()\n else:\n init_parameters = {}\n for param_name, param in inspect.signature(obj.__init__).parameters.items():\n # Ignore `args` and `kwargs`, used by the default constructor\n if param_name in (\"args\", \"kwargs\"):\n continue\n try:\n # This only works if the Component constructor assigns the init\n # parameter to an instance variable or property with the same name\n param_value = getattr(obj, param_name)\n except AttributeError as e:\n # If the parameter doesn't have a default value, raise an error\n if param.default is param.empty:\n raise SerializationError(\n f\"Cannot determine the value of the init parameter '{param_name}' \"\n f\"for the class {obj.__class__.__name__}.\"\n f\"You can fix this error by assigning 'self.{param_name} = {param_name}' or adding a \"\n f\"custom serialization method 'to_dict' to the class.\"\n ) from e\n # In case the init parameter was not assigned, we use the default value\n param_value = param.default\n init_parameters[param_name] = param_value\n\n data = default_to_dict(obj, **init_parameters)\n\n _validate_component_to_dict_output(obj, name, data)\n return data"}], "type": ["function_empty", "Development"], "node": ["haystack.utils.callable_serialization.serialize_callable", "haystack.components.generators.azure.AzureOpenAIGenerator.to_dict", "haystack.core.serialization.component_to_dict"], "language": "Python", "toolfunc_count": 2, "func_count": 3, "pytest_info": {"total_num": 7, "base_passed_num": 4}} {"id": ["haystack.haystack.utils.callable_serialization.serialize_callable", "haystack.haystack.components.generators.openai.OpenAIGenerator::to_dict", "haystack.haystack.utils.type_serialization.thread_safe_import", "haystack.haystack.utils.callable_serialization.deserialize_callable"], "project": "haystack", "origin_file": ["haystack/utils/callable_serialization.py", "haystack/components/generators/openai.py", "haystack/utils/type_serialization.py", "haystack/utils/callable_serialization.py"], "test_list": ["test/components/generators/test_openai.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 80, "func_start_lineno": 12, "func_end_lineno": 42, "func_code": "def serialize_callable(callable_handle: Callable) -> str:\n \"\"\"\n Serializes a callable to its full path.\n\n :param callable_handle: The callable to serialize\n :return: The full path of the callable\n \"\"\"\n try:\n full_arg_spec = inspect.getfullargspec(callable_handle)\n is_instance_method = bool(full_arg_spec.args and full_arg_spec.args[0] == \"self\")\n except TypeError:\n is_instance_method = False\n if is_instance_method:\n raise SerializationError(\"Serialization of instance methods is not supported.\")\n\n # __qualname__ contains the fully qualified path we need for classmethods and staticmethods\n qualname = getattr(callable_handle, \"__qualname__\", \"\")\n if \"\" in qualname:\n raise SerializationError(\"Serialization of lambdas is not supported.\")\n if \"\" in qualname:\n raise SerializationError(\"Serialization of nested functions is not supported.\")\n\n name = qualname or callable_handle.__name__\n\n # Get the full package path of the function\n module = inspect.getmodule(callable_handle)\n if module is not None:\n full_path = f\"{module.__name__}.{name}\"\n else:\n full_path = name\n return full_path"}, {"class_start_lineno": 20, "class_end_lineno": 335, "func_start_lineno": 133, "func_end_lineno": 150, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serialize this component to a dictionary.\n\n :returns:\n The serialized component as a dictionary.\n \"\"\"\n callback_name = serialize_callable(self.streaming_callback) if self.streaming_callback else None\n return default_to_dict(\n self,\n model=self.model,\n streaming_callback=callback_name,\n api_base_url=self.api_base_url,\n organization=self.organization,\n generation_kwargs=self.generation_kwargs,\n system_prompt=self.system_prompt,\n api_key=self.api_key.to_dict(),\n )"}, {"class_start_lineno": 1, "class_end_lineno": 170, "func_start_lineno": 159, "func_end_lineno": 170, "func_code": "def thread_safe_import(module_name: str) -> ModuleType:\n \"\"\"\n Import a module in a thread-safe manner.\n\n Importing modules in a multi-threaded environment can lead to race conditions.\n This function ensures that the module is imported in a thread-safe manner without having impact\n on the performance of the import for single-threaded environments.\n\n :param module_name: the module to import\n \"\"\"\n with _import_lock:\n return importlib.import_module(module_name)"}, {"class_start_lineno": 1, "class_end_lineno": 80, "func_start_lineno": 45, "func_end_lineno": 80, "func_code": "def deserialize_callable(callable_handle: str) -> Callable:\n \"\"\"\n Deserializes a callable given its full import path as a string.\n\n :param callable_handle: The full path of the callable_handle\n :return: The callable\n :raises DeserializationError: If the callable cannot be found\n \"\"\"\n parts = callable_handle.split(\".\")\n\n for i in range(len(parts), 0, -1):\n module_name = \".\".join(parts[:i])\n try:\n mod: Any = thread_safe_import(module_name)\n except Exception:\n # keep reducing i until we find a valid module import\n continue\n\n attr_value = mod\n for part in parts[i:]:\n try:\n attr_value = getattr(attr_value, part)\n except AttributeError as e:\n raise DeserializationError(f\"Could not find attribute '{part}' in {attr_value.__name__}\") from e\n\n # when the attribute is a classmethod, we need the underlying function\n if isinstance(attr_value, (classmethod, staticmethod)):\n attr_value = attr_value.__func__\n\n if not callable(attr_value):\n raise DeserializationError(f\"The final attribute is not callable: {attr_value}\")\n\n return attr_value\n\n # Fallback if we never find anything\n raise DeserializationError(f\"Could not import '{callable_handle}' as a module or callable.\")"}], "type": ["function_empty", "Development"], "node": ["haystack.utils.callable_serialization.serialize_callable", "haystack.components.generators.openai.OpenAIGenerator.to_dict", "haystack.utils.type_serialization.thread_safe_import", "haystack.utils.callable_serialization.deserialize_callable"], "language": "Python", "toolfunc_count": 3, "func_count": 4, "pytest_info": {"total_num": 12, "base_passed_num": 9}} {"id": ["haystack.haystack.utils.callable_serialization.serialize_callable", "haystack.haystack.components.generators.chat.azure.AzureOpenAIChatGenerator::to_dict", "haystack.haystack.core.serialization.import_class_by_name", "haystack.haystack.tools.tool.deserialize_tools_inplace"], "project": "haystack", "origin_file": ["haystack/utils/callable_serialization.py", "haystack/components/generators/chat/azure.py", "haystack/core/serialization.py", "haystack/tools/tool.py"], "test_list": ["test/components/generators/chat/test_azure.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 80, "func_start_lineno": 12, "func_end_lineno": 42, "func_code": "def serialize_callable(callable_handle: Callable) -> str:\n \"\"\"\n Serializes a callable to its full path.\n\n :param callable_handle: The callable to serialize\n :return: The full path of the callable\n \"\"\"\n try:\n full_arg_spec = inspect.getfullargspec(callable_handle)\n is_instance_method = bool(full_arg_spec.args and full_arg_spec.args[0] == \"self\")\n except TypeError:\n is_instance_method = False\n if is_instance_method:\n raise SerializationError(\"Serialization of instance methods is not supported.\")\n\n # __qualname__ contains the fully qualified path we need for classmethods and staticmethods\n qualname = getattr(callable_handle, \"__qualname__\", \"\")\n if \"\" in qualname:\n raise SerializationError(\"Serialization of lambdas is not supported.\")\n if \"\" in qualname:\n raise SerializationError(\"Serialization of nested functions is not supported.\")\n\n name = qualname or callable_handle.__name__\n\n # Get the full package path of the function\n module = inspect.getmodule(callable_handle)\n if module is not None:\n full_path = f\"{module.__name__}.{name}\"\n else:\n full_path = name\n return full_path"}, {"class_start_lineno": 20, "class_end_lineno": 226, "func_start_lineno": 177, "func_end_lineno": 204, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serialize this component to a dictionary.\n\n :returns:\n The serialized component as a dictionary.\n \"\"\"\n callback_name = serialize_callable(self.streaming_callback) if self.streaming_callback else None\n azure_ad_token_provider_name = None\n if self.azure_ad_token_provider:\n azure_ad_token_provider_name = serialize_callable(self.azure_ad_token_provider)\n return default_to_dict(\n self,\n azure_endpoint=self.azure_endpoint,\n azure_deployment=self.azure_deployment,\n organization=self.organization,\n api_version=self.api_version,\n streaming_callback=callback_name,\n generation_kwargs=self.generation_kwargs,\n timeout=self.timeout,\n max_retries=self.max_retries,\n api_key=self.api_key.to_dict() if self.api_key is not None else None,\n azure_ad_token=self.azure_ad_token.to_dict() if self.azure_ad_token is not None else None,\n default_headers=self.default_headers,\n tools=[tool.to_dict() for tool in self.tools] if self.tools else None,\n tools_strict=self.tools_strict,\n azure_ad_token_provider=azure_ad_token_provider_name,\n )"}, {"class_start_lineno": 1, "class_end_lineno": 264, "func_start_lineno": 243, "func_end_lineno": 264, "func_code": "def import_class_by_name(fully_qualified_name: str) -> Type[object]:\n \"\"\"\n Utility function to import (load) a class object based on its fully qualified class name.\n\n This function dynamically imports a class based on its string name.\n It splits the name into module path and class name, imports the module,\n and returns the class object.\n\n :param fully_qualified_name: the fully qualified class name as a string\n :returns: the class object.\n :raises ImportError: If the class cannot be imported or found.\n \"\"\"\n try:\n module_path, class_name = fully_qualified_name.rsplit(\".\", 1)\n logger.debug(\n \"Attempting to import class '{cls_name}' from module '{md_path}'\", cls_name=class_name, md_path=module_path\n )\n module = thread_safe_import(module_path)\n return getattr(module, class_name)\n except (ImportError, AttributeError) as error:\n logger.error(\"Failed to import class '{full_name}'\", full_name=fully_qualified_name)\n raise ImportError(f\"Could not import class '{fully_qualified_name}'\") from error"}, {"class_start_lineno": 1, "class_end_lineno": 136, "func_start_lineno": 106, "func_end_lineno": 136, "func_code": "def deserialize_tools_inplace(data: Dict[str, Any], key: str = \"tools\"):\n \"\"\"\n Deserialize Tools in a dictionary inplace.\n\n :param data:\n The dictionary with the serialized data.\n :param key:\n The key in the dictionary where the Tools are stored.\n \"\"\"\n if key in data:\n serialized_tools = data[key]\n\n if serialized_tools is None:\n return\n\n if not isinstance(serialized_tools, list):\n raise TypeError(f\"The value of '{key}' is not a list\")\n\n deserialized_tools = []\n for tool in serialized_tools:\n if not isinstance(tool, dict):\n raise TypeError(f\"Serialized tool '{tool}' is not a dictionary\")\n\n # different classes are allowed: Tool, ComponentTool, etc.\n tool_class = import_class_by_name(tool[\"type\"])\n if not issubclass(tool_class, Tool):\n raise TypeError(f\"Class '{tool_class}' is not a subclass of Tool\")\n\n deserialized_tools.append(tool_class.from_dict(tool))\n\n data[key] = deserialized_tools"}], "type": ["function_empty", "Development"], "node": ["haystack.utils.callable_serialization.serialize_callable", "haystack.components.generators.chat.azure.AzureOpenAIChatGenerator.to_dict", "haystack.core.serialization.import_class_by_name", "haystack.tools.tool.deserialize_tools_inplace"], "language": "Python", "toolfunc_count": 2, "func_count": 4, "pytest_info": {"total_num": 8, "base_passed_num": 4}} {"id": ["haystack.haystack.utils.callable_serialization.serialize_callable", "haystack.haystack.components.generators.chat.openai.OpenAIChatGenerator::to_dict", "haystack.haystack.core.serialization.import_class_by_name", "haystack.haystack.tools.tool.deserialize_tools_inplace"], "project": "haystack", "origin_file": ["haystack/utils/callable_serialization.py", "haystack/components/generators/chat/openai.py", "haystack/core/serialization.py", "haystack/tools/tool.py"], "test_list": ["test/components/generators/chat/test_openai.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 80, "func_start_lineno": 12, "func_end_lineno": 42, "func_code": "def serialize_callable(callable_handle: Callable) -> str:\n \"\"\"\n Serializes a callable to its full path.\n\n :param callable_handle: The callable to serialize\n :return: The full path of the callable\n \"\"\"\n try:\n full_arg_spec = inspect.getfullargspec(callable_handle)\n is_instance_method = bool(full_arg_spec.args and full_arg_spec.args[0] == \"self\")\n except TypeError:\n is_instance_method = False\n if is_instance_method:\n raise SerializationError(\"Serialization of instance methods is not supported.\")\n\n # __qualname__ contains the fully qualified path we need for classmethods and staticmethods\n qualname = getattr(callable_handle, \"__qualname__\", \"\")\n if \"\" in qualname:\n raise SerializationError(\"Serialization of lambdas is not supported.\")\n if \"\" in qualname:\n raise SerializationError(\"Serialization of nested functions is not supported.\")\n\n name = qualname or callable_handle.__name__\n\n # Get the full package path of the function\n module = inspect.getmodule(callable_handle)\n if module is not None:\n full_path = f\"{module.__name__}.{name}\"\n else:\n full_path = name\n return full_path"}, {"class_start_lineno": 32, "class_end_lineno": 571, "func_start_lineno": 170, "func_end_lineno": 190, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serialize this component to a dictionary.\n\n :returns:\n The serialized component as a dictionary.\n \"\"\"\n callback_name = serialize_callable(self.streaming_callback) if self.streaming_callback else None\n return default_to_dict(\n self,\n model=self.model,\n streaming_callback=callback_name,\n api_base_url=self.api_base_url,\n organization=self.organization,\n generation_kwargs=self.generation_kwargs,\n api_key=self.api_key.to_dict(),\n timeout=self.timeout,\n max_retries=self.max_retries,\n tools=[tool.to_dict() for tool in self.tools] if self.tools else None,\n tools_strict=self.tools_strict,\n )"}, {"class_start_lineno": 1, "class_end_lineno": 264, "func_start_lineno": 243, "func_end_lineno": 264, "func_code": "def import_class_by_name(fully_qualified_name: str) -> Type[object]:\n \"\"\"\n Utility function to import (load) a class object based on its fully qualified class name.\n\n This function dynamically imports a class based on its string name.\n It splits the name into module path and class name, imports the module,\n and returns the class object.\n\n :param fully_qualified_name: the fully qualified class name as a string\n :returns: the class object.\n :raises ImportError: If the class cannot be imported or found.\n \"\"\"\n try:\n module_path, class_name = fully_qualified_name.rsplit(\".\", 1)\n logger.debug(\n \"Attempting to import class '{cls_name}' from module '{md_path}'\", cls_name=class_name, md_path=module_path\n )\n module = thread_safe_import(module_path)\n return getattr(module, class_name)\n except (ImportError, AttributeError) as error:\n logger.error(\"Failed to import class '{full_name}'\", full_name=fully_qualified_name)\n raise ImportError(f\"Could not import class '{fully_qualified_name}'\") from error"}, {"class_start_lineno": 1, "class_end_lineno": 136, "func_start_lineno": 106, "func_end_lineno": 136, "func_code": "def deserialize_tools_inplace(data: Dict[str, Any], key: str = \"tools\"):\n \"\"\"\n Deserialize Tools in a dictionary inplace.\n\n :param data:\n The dictionary with the serialized data.\n :param key:\n The key in the dictionary where the Tools are stored.\n \"\"\"\n if key in data:\n serialized_tools = data[key]\n\n if serialized_tools is None:\n return\n\n if not isinstance(serialized_tools, list):\n raise TypeError(f\"The value of '{key}' is not a list\")\n\n deserialized_tools = []\n for tool in serialized_tools:\n if not isinstance(tool, dict):\n raise TypeError(f\"Serialized tool '{tool}' is not a dictionary\")\n\n # different classes are allowed: Tool, ComponentTool, etc.\n tool_class = import_class_by_name(tool[\"type\"])\n if not issubclass(tool_class, Tool):\n raise TypeError(f\"Class '{tool_class}' is not a subclass of Tool\")\n\n deserialized_tools.append(tool_class.from_dict(tool))\n\n data[key] = deserialized_tools"}], "type": ["function_empty", "Development"], "node": ["haystack.utils.callable_serialization.serialize_callable", "haystack.components.generators.chat.openai.OpenAIChatGenerator.to_dict", "haystack.core.serialization.import_class_by_name", "haystack.tools.tool.deserialize_tools_inplace"], "language": "Python", "toolfunc_count": 2, "func_count": 4, "pytest_info": {"total_num": 19, "base_passed_num": 8}} {"id": ["haystack.haystack.core.type_utils._strict_types_are_compatible", "haystack.haystack.core.type_utils._types_are_compatible"], "project": "haystack", "origin_file": ["haystack/core/type_utils.py", "haystack/core/type_utils.py"], "test_list": ["test/components/joiners/test_list_joiner.py", "test/components/validators/test_json_schema.py", "test/core/pipeline/test_pipeline.py", "test/tracing/test_logging_tracer.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 105, "func_start_lineno": 29, "func_end_lineno": 76, "func_code": "def _strict_types_are_compatible(sender, receiver): # pylint: disable=too-many-return-statements\n \"\"\"\n Checks whether the sender type is equal to or a subtype of the receiver type under strict validation.\n\n Note: this method has no pretense to perform proper type matching. It especially does not deal with aliasing of\n typing classes such as `List` or `Dict` to their runtime counterparts `list` and `dict`. It also does not deal well\n with \"bare\" types, so `List` is treated differently from `List[Any]`, even though they should be the same.\n Consider simplifying the typing of your components if you observe unexpected errors during component connection.\n\n :param sender: The sender type.\n :param receiver: The receiver type.\n :return: True if the sender type is strictly compatible with the receiver type, False otherwise.\n \"\"\"\n if sender == receiver or receiver is Any:\n return True\n\n if sender is Any:\n return False\n\n try:\n if issubclass(sender, receiver):\n return True\n except TypeError: # typing classes can't be used with issubclass, so we deal with them below\n pass\n\n sender_origin = get_origin(sender)\n receiver_origin = get_origin(receiver)\n\n if sender_origin is not Union and receiver_origin is Union:\n return any(_strict_types_are_compatible(sender, union_arg) for union_arg in get_args(receiver))\n\n # Both must have origins and they must be equal\n if not (sender_origin and receiver_origin and sender_origin == receiver_origin):\n return False\n\n # Compare generic type arguments\n sender_args = get_args(sender)\n receiver_args = get_args(receiver)\n\n # Handle bare types\n if not sender_args and sender_origin:\n sender_args = (Any,)\n if not receiver_args and receiver_origin:\n receiver_args = (Any,) * (len(sender_args) if sender_args else 1)\n if len(sender_args) > len(receiver_args):\n return False\n\n return all(_strict_types_are_compatible(*args) for args in zip(sender_args, receiver_args))"}, {"class_start_lineno": 1, "class_end_lineno": 105, "func_start_lineno": 14, "func_end_lineno": 26, "func_code": "def _types_are_compatible(sender, receiver, type_validation: bool = True) -> bool:\n \"\"\"\n Determines if two types are compatible based on the specified validation mode.\n\n :param sender: The sender type.\n :param receiver: The receiver type.\n :param type_validation: Whether to perform strict type validation.\n :return: True if the types are compatible, False otherwise.\n \"\"\"\n if type_validation:\n return _strict_types_are_compatible(sender, receiver)\n else:\n return True"}], "type": ["function_empty"], "node": ["haystack.core.type_utils._strict_types_are_compatible", "haystack.core.type_utils._types_are_compatible"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 36, "base_passed_num": 29}} {"id": ["haystack.haystack.components.preprocessors.csv_document_splitter.CSVDocumentSplitter::_split_dataframe", "haystack.haystack.components.preprocessors.csv_document_splitter.CSVDocumentSplitter::_recursive_split"], "project": "haystack", "origin_file": ["haystack/components/preprocessors/csv_document_splitter.py", "haystack/components/preprocessors/csv_document_splitter.py"], "test_list": ["test/components/preprocessors/test_csv_document_splitter.py"], "prob_info": [{"class_start_lineno": 18, "class_end_lineno": 244, "func_start_lineno": 174, "func_end_lineno": 207, "func_code": " def _split_dataframe(\n self, df: \"pd.DataFrame\", split_threshold: int, axis: Literal[\"row\", \"column\"]\n ) -> List[\"pd.DataFrame\"]:\n \"\"\"\n Splits a DataFrame into sub-tables based on consecutive empty rows or columns exceeding `split_threshold`.\n\n :param df: DataFrame to split.\n :param split_threshold: Minimum number of consecutive empty rows or columns to trigger a split.\n :param axis: Axis along which to split. Either \"row\" or \"column\".\n :return: List of split DataFrames.\n \"\"\"\n # Find indices of consecutive empty rows or columns\n split_indices = self._find_split_indices(df=df, split_threshold=split_threshold, axis=axis)\n\n # If no split_indices are found, return the original DataFrame\n if len(split_indices) == 0:\n return [df]\n\n # Split the DataFrame at identified indices\n sub_tables = []\n table_start_idx = 0\n df_length = df.shape[0] if axis == \"row\" else df.shape[1]\n for empty_start_idx, empty_end_idx in split_indices + [(df_length, df_length)]:\n # Avoid empty splits\n if empty_start_idx - table_start_idx >= 1:\n if axis == \"row\":\n sub_table = df.iloc[table_start_idx:empty_start_idx]\n else:\n sub_table = df.iloc[:, table_start_idx:empty_start_idx]\n if not sub_table.empty:\n sub_tables.append(sub_table)\n table_start_idx = empty_end_idx + 1\n\n return sub_tables"}, {"class_start_lineno": 18, "class_end_lineno": 244, "func_start_lineno": 209, "func_end_lineno": 244, "func_code": " def _recursive_split(\n self, df: \"pd.DataFrame\", row_split_threshold: int, column_split_threshold: int\n ) -> List[\"pd.DataFrame\"]:\n \"\"\"\n Recursively splits a DataFrame.\n\n Recursively splits a DataFrame first by empty rows, then by empty columns, and repeats the process\n until no more splits are possible. Returns a list of DataFrames, each representing a fully separated sub-table.\n\n :param df: A Pandas DataFrame representing a table (or multiple tables) extracted from a CSV.\n :param row_split_threshold: The minimum number of consecutive empty rows required to trigger a split.\n :param column_split_threshold: The minimum number of consecutive empty columns to trigger a split.\n \"\"\"\n\n # Step 1: Split by rows\n new_sub_tables = self._split_dataframe(df=df, split_threshold=row_split_threshold, axis=\"row\")\n\n # Step 2: Split by columns\n final_tables = []\n for table in new_sub_tables:\n final_tables.extend(self._split_dataframe(df=table, split_threshold=column_split_threshold, axis=\"column\"))\n\n # Step 3: Recursively reapply splitting checked by whether any new empty rows appear after column split\n result = []\n for table in final_tables:\n # Check if there are consecutive rows >= row_split_threshold now present\n if len(self._find_split_indices(df=table, split_threshold=row_split_threshold, axis=\"row\")) > 0:\n result.extend(\n self._recursive_split(\n df=table, row_split_threshold=row_split_threshold, column_split_threshold=column_split_threshold\n )\n )\n else:\n result.append(table)\n\n return result"}], "type": ["function_empty", "Development"], "node": ["haystack.components.preprocessors.csv_document_splitter.CSVDocumentSplitter._split_dataframe", "haystack.components.preprocessors.csv_document_splitter.CSVDocumentSplitter._recursive_split"], "language": "Python", "toolfunc_count": 1, "func_count": 2, "pytest_info": {"total_num": 23, "base_passed_num": 15}} {"id": ["haystack.haystack.components.preprocessors.document_cleaner.DocumentCleaner::_find_and_remove_header_footer", "haystack.haystack.components.preprocessors.document_cleaner.DocumentCleaner::_find_longest_common_ngram", "haystack.haystack.components.preprocessors.document_cleaner.DocumentCleaner::_allngram", "haystack.haystack.components.preprocessors.document_cleaner.DocumentCleaner::run"], "project": "haystack", "origin_file": ["haystack/components/preprocessors/document_cleaner.py", "haystack/components/preprocessors/document_cleaner.py", "haystack/components/preprocessors/document_cleaner.py", "haystack/components/preprocessors/document_cleaner.py", "haystack/components/preprocessors/document_cleaner.py"], "test_list": ["test/components/preprocessors/test_document_cleaner.py"], "prob_info": [{"class_start_lineno": 18, "class_end_lineno": 325, "func_start_lineno": 231, "func_end_lineno": 267, "func_code": " def _find_and_remove_header_footer(\n self, text: str, n_chars: int, n_first_pages_to_ignore: int, n_last_pages_to_ignore: int\n ) -> str:\n \"\"\"\n Heuristic to find footers and headers across different pages by searching for the longest common string.\n\n Pages in the text need to be separated by form feed character \"\\f\".\n For headers, we only search in the first n_chars characters (for footer: last n_chars).\n Note: This heuristic uses exact matches and therefore works well for footers like \"Copyright 2019 by XXX\",\n but won't detect \"Page 3 of 4\" or similar.\n\n :param n_chars: The number of first/last characters where the header/footer shall be searched in.\n :param n_first_pages_to_ignore: The number of first pages to ignore\n (e.g. TOCs often don't contain footer/header).\n :param n_last_pages_to_ignore: The number of last pages to ignore.\n :returns: The text without the found headers and footers.\n \"\"\"\n\n pages = text.split(\"\\f\")\n\n # header\n start_of_pages = [p[:n_chars] for p in pages[n_first_pages_to_ignore:-n_last_pages_to_ignore]]\n found_header = self._find_longest_common_ngram(start_of_pages)\n if found_header:\n pages = [page.replace(found_header, \"\") for page in pages]\n\n # footer\n end_of_pages = [p[-n_chars:] for p in pages[n_first_pages_to_ignore:-n_last_pages_to_ignore]]\n found_footer = self._find_longest_common_ngram(end_of_pages)\n if found_footer:\n pages = [page.replace(found_footer, \"\") for page in pages]\n\n logger.debug(\n \"Removed header '{header}' and footer '{footer}' in document\", header=found_header, footer=found_footer\n )\n text = \"\\f\".join(pages)\n return text"}, {"class_start_lineno": 18, "class_end_lineno": 325, "func_start_lineno": 306, "func_end_lineno": 325, "func_code": " def _find_longest_common_ngram(self, sequences: List[str], min_ngram: int = 3, max_ngram: int = 30) -> str:\n \"\"\"\n Find the longest common ngram across a list of text sequences (e.g. start of pages).\n\n Considering all ngram lengths between the minimum and maximum length. Helpful for finding footers, headers etc.\n Empty sequences are ignored.\n\n :param sequences: The list of strings that shall be searched for common n_grams.\n :param max_ngram: The maximum length of ngram to consider.\n :param min_ngram: The minimum length of ngram to consider.\n :returns: The longest ngram that all sequences have in common.\n \"\"\"\n sequences = [s for s in sequences if s] # filter empty sequences\n if not sequences:\n return \"\"\n seqs_ngrams = map(partial(self._allngram, min_ngram=min_ngram, max_ngram=max_ngram), sequences)\n intersection = reduce(set.intersection, seqs_ngrams)\n\n longest = max(intersection, key=len, default=\"\")\n return longest if longest.strip() else \"\""}, {"class_start_lineno": 18, "class_end_lineno": 325, "func_start_lineno": 290, "func_end_lineno": 304, "func_code": " def _allngram(self, seq: str, min_ngram: int, max_ngram: int) -> Set[str]:\n \"\"\"\n Generates all possible ngrams from a given sequence of text.\n\n Considering all ngram lengths between the minimum and maximum length.\n\n :param seq: The sequence to generate ngrams from.\n :param min_ngram: The minimum length of ngram to consider.\n :param max_ngram: The maximum length of ngram to consider.\n :returns: A set of all ngrams from the given sequence.\n \"\"\"\n lengths = range(min_ngram, max_ngram) if max_ngram else range(min_ngram, len(seq))\n ngrams = map(partial(self._ngram, seq), lengths)\n res = set(chain.from_iterable(ngrams))\n return res"}, {"class_start_lineno": 18, "class_end_lineno": 325, "func_start_lineno": 219, "func_end_lineno": 229, "func_code": " def _remove_repeated_substrings(self, text: str) -> str:\n \"\"\"\n Remove any substrings from the text that occur repeatedly on every page. For example headers or footers.\n\n Pages in the text need to be separated by form feed character \"\\f\".\n :param text: Text to clean.\n :returns: The text without the repeated substrings.\n \"\"\"\n return self._find_and_remove_header_footer(\n text, n_chars=300, n_first_pages_to_ignore=1, n_last_pages_to_ignore=1\n )"}, {"class_start_lineno": 18, "class_end_lineno": 325, "func_start_lineno": 93, "func_end_lineno": 145, "func_code": " def run(self, documents: List[Document]):\n \"\"\"\n Cleans up the documents.\n\n :param documents: List of Documents to clean.\n\n :returns: A dictionary with the following key:\n - `documents`: List of cleaned Documents.\n\n :raises TypeError: if documents is not a list of Documents.\n \"\"\"\n if not isinstance(documents, list) or documents and not isinstance(documents[0], Document):\n raise TypeError(\"DocumentCleaner expects a List of Documents as input.\")\n\n cleaned_docs = []\n for doc in documents:\n if doc.content is None:\n logger.warning(\n \"DocumentCleaner only cleans text documents but document.content for document ID\"\n \" %{document_id} is None.\",\n document_id=doc.id,\n )\n cleaned_docs.append(doc)\n continue\n text = doc.content\n\n if self.unicode_normalization:\n text = self._normalize_unicode(text, self.unicode_normalization)\n if self.ascii_only:\n text = self._ascii_only(text)\n if self.remove_extra_whitespaces:\n text = self._remove_extra_whitespaces(text)\n if self.remove_empty_lines:\n text = self._remove_empty_lines(text)\n if self.remove_substrings:\n text = self._remove_substrings(text, self.remove_substrings)\n if self.remove_regex:\n text = self._remove_regex(text, self.remove_regex)\n if self.remove_repeated_substrings:\n text = self._remove_repeated_substrings(text)\n\n clean_doc = Document(\n id=doc.id if self.keep_id else \"\",\n content=text,\n blob=doc.blob,\n meta=deepcopy(doc.meta),\n score=doc.score,\n embedding=doc.embedding,\n sparse_embedding=doc.sparse_embedding,\n )\n cleaned_docs.append(clean_doc)\n\n return {\"documents\": cleaned_docs}"}], "type": ["function_empty", "Development"], "node": ["haystack.components.preprocessors.document_cleaner.DocumentCleaner._find_and_remove_header_footer", "haystack.components.preprocessors.document_cleaner.DocumentCleaner._find_longest_common_ngram", "haystack.components.preprocessors.document_cleaner.DocumentCleaner._allngram", "haystack.components.preprocessors.document_cleaner.DocumentCleaner._remove_repeated_substrings", "haystack.components.preprocessors.document_cleaner.DocumentCleaner.run"], "language": "Python", "toolfunc_count": 3, "func_count": 4, "pytest_info": {"total_num": 14, "base_passed_num": 3}} {"id": ["haystack.haystack.components.preprocessors.document_splitter.DocumentSplitter::_split_by_character", "haystack.haystack.components.preprocessors.document_splitter.DocumentSplitter::_split_by_function", "haystack.haystack.components.preprocessors.document_splitter.DocumentSplitter::_split_by_nltk_sentence", "haystack.haystack.components.preprocessors.document_splitter.DocumentSplitter::run"], "project": "haystack", "origin_file": ["haystack/components/preprocessors/document_splitter.py", "haystack/components/preprocessors/document_splitter.py", "haystack/components/preprocessors/document_splitter.py", "haystack/components/preprocessors/document_splitter.py", "haystack/components/preprocessors/document_splitter.py"], "test_list": ["test/components/preprocessors/test_document_splitter.py"], "prob_info": [{"class_start_lineno": 22, "class_end_lineno": 490, "func_start_lineno": 238, "func_end_lineno": 251, "func_code": " def _split_by_character(self, doc) -> List[Document]:\n split_at = _CHARACTER_SPLIT_BY_MAPPING[self.split_by]\n units = doc.content.split(split_at)\n # Add the delimiter back to all units except the last one\n for i in range(len(units) - 1):\n units[i] += split_at\n text_splits, splits_pages, splits_start_idxs = self._concatenate_units(\n units, self.split_length, self.split_overlap, self.split_threshold\n )\n metadata = deepcopy(doc.meta)\n metadata[\"source_id\"] = doc.id\n return self._create_docs_from_splits(\n text_splits=text_splits, splits_pages=splits_pages, splits_start_idxs=splits_start_idxs, meta=metadata\n )"}, {"class_start_lineno": 22, "class_end_lineno": 490, "func_start_lineno": 253, "func_end_lineno": 261, "func_code": " def _split_by_function(self, doc) -> List[Document]:\n # the check for None is done already in the run method\n splits = self.splitting_function(doc.content) # type: ignore\n docs: List[Document] = []\n for s in splits:\n meta = deepcopy(doc.meta)\n meta[\"source_id\"] = doc.id\n docs.append(Document(content=s, meta=meta))\n return docs"}, {"class_start_lineno": 22, "class_end_lineno": 490, "func_start_lineno": 213, "func_end_lineno": 236, "func_code": " def _split_by_nltk_sentence(self, doc: Document) -> List[Document]:\n split_docs = []\n\n result = self.sentence_splitter.split_sentences(doc.content) # type: ignore # None check is done in run()\n units = [sentence[\"sentence\"] for sentence in result]\n\n if self.respect_sentence_boundary:\n text_splits, splits_pages, splits_start_idxs = self._concatenate_sentences_based_on_word_amount(\n sentences=units, split_length=self.split_length, split_overlap=self.split_overlap\n )\n else:\n text_splits, splits_pages, splits_start_idxs = self._concatenate_units(\n elements=units,\n split_length=self.split_length,\n split_overlap=self.split_overlap,\n split_threshold=self.split_threshold,\n )\n metadata = deepcopy(doc.meta)\n metadata[\"source_id\"] = doc.id\n split_docs += self._create_docs_from_splits(\n text_splits=text_splits, splits_pages=splits_pages, splits_start_idxs=splits_start_idxs, meta=metadata\n )\n\n return split_docs"}, {"class_start_lineno": 22, "class_end_lineno": 490, "func_start_lineno": 204, "func_end_lineno": 211, "func_code": " def _split_document(self, doc: Document) -> List[Document]:\n if self.split_by == \"sentence\" or self.respect_sentence_boundary:\n return self._split_by_nltk_sentence(doc)\n\n if self.split_by == \"function\" and self.splitting_function is not None:\n return self._split_by_function(doc)\n\n return self._split_by_character(doc)"}, {"class_start_lineno": 22, "class_end_lineno": 490, "func_start_lineno": 166, "func_end_lineno": 202, "func_code": " def run(self, documents: List[Document]):\n \"\"\"\n Split documents into smaller parts.\n\n Splits documents by the unit expressed in `split_by`, with a length of `split_length`\n and an overlap of `split_overlap`.\n\n :param documents: The documents to split.\n :returns: A dictionary with the following key:\n - `documents`: List of documents with the split texts. Each document includes:\n - A metadata field `source_id` to track the original document.\n - A metadata field `page_number` to track the original page number.\n - All other metadata copied from the original document.\n\n :raises TypeError: if the input is not a list of Documents.\n :raises ValueError: if the content of a document is None.\n \"\"\"\n if self._use_sentence_splitter and self.sentence_splitter is None:\n raise RuntimeError(\n \"The component DocumentSplitter wasn't warmed up. Run 'warm_up()' before calling 'run()'.\"\n )\n\n if not isinstance(documents, list) or (documents and not isinstance(documents[0], Document)):\n raise TypeError(\"DocumentSplitter expects a List of Documents as input.\")\n\n split_docs: List[Document] = []\n for doc in documents:\n if doc.content is None:\n raise ValueError(\n f\"DocumentSplitter only works with text documents but content for document ID {doc.id} is None.\"\n )\n if doc.content == \"\":\n logger.warning(\"Document ID {doc_id} has an empty content. Skipping this document.\", doc_id=doc.id)\n continue\n\n split_docs += self._split_document(doc)\n return {\"documents\": split_docs}"}], "type": ["function_empty", "Development"], "node": ["haystack.components.preprocessors.document_splitter.DocumentSplitter._split_by_character", "haystack.components.preprocessors.document_splitter.DocumentSplitter._split_by_function", "haystack.components.preprocessors.document_splitter.DocumentSplitter._split_by_nltk_sentence", "haystack.components.preprocessors.document_splitter.DocumentSplitter._split_document", "haystack.components.preprocessors.document_splitter.DocumentSplitter.run"], "language": "Python", "toolfunc_count": 1, "func_count": 4, "pytest_info": {"total_num": 53, "base_passed_num": 17}} {"id": ["haystack.haystack.components.preprocessors.recursive_splitter.RecursiveDocumentSplitter::_chunk_length", "haystack.haystack.components.preprocessors.recursive_splitter.RecursiveDocumentSplitter::_split_chunk", "haystack.haystack.components.preprocessors.recursive_splitter.RecursiveDocumentSplitter::_apply_overlap", "haystack.haystack.components.preprocessors.sentence_tokenizer.SentenceSplitter::split_sentences", "haystack.haystack.components.preprocessors.recursive_splitter.RecursiveDocumentSplitter::_chunk_text"], "project": "haystack", "origin_file": ["haystack/components/preprocessors/recursive_splitter.py", "haystack/components/preprocessors/recursive_splitter.py", "haystack/components/preprocessors/recursive_splitter.py", "haystack/components/preprocessors/recursive_splitter.py", "haystack/components/preprocessors/sentence_tokenizer.py", "haystack/components/preprocessors/recursive_splitter.py"], "test_list": ["test/components/preprocessors/test_recursive_splitter.py"], "prob_info": [{"class_start_lineno": 15, "class_end_lineno": 421, "func_start_lineno": 215, "func_end_lineno": 227, "func_code": " def _chunk_length(self, text: str) -> int:\n \"\"\"\n Split the text by whitespace and count non-empty elements.\n\n :param: The text to be split.\n :return: The number of words in the text.\n \"\"\"\n\n if self.split_units == \"word\":\n words = [word for word in text.split(\" \") if word]\n return len(words)\n\n return len(text)"}, {"class_start_lineno": 15, "class_end_lineno": 421, "func_start_lineno": 204, "func_end_lineno": 213, "func_code": " def _get_overlap(self, overlapped_chunks: List[str]) -> Tuple[str, str]:\n \"\"\"Get the previous overlapped chunk instead of the original chunk.\"\"\"\n prev_chunk = overlapped_chunks[-1]\n overlap_start = max(0, self._chunk_length(prev_chunk) - self.split_overlap)\n if self.split_units == \"word\":\n word_chunks = prev_chunk.split()\n overlap = \" \".join(word_chunks[overlap_start:])\n else:\n overlap = prev_chunk[overlap_start:]\n return overlap, prev_chunk"}, {"class_start_lineno": 15, "class_end_lineno": 421, "func_start_lineno": 114, "func_end_lineno": 133, "func_code": " def _split_chunk(self, current_chunk: str) -> Tuple[str, str]:\n \"\"\"\n Splits a chunk based on the split_length and split_units attribute.\n\n :param current_chunk: The current chunk to be split.\n :returns:\n A tuple containing the current chunk and the remaining words or characters.\n \"\"\"\n\n if self.split_units == \"word\":\n words = current_chunk.split()\n current_chunk = \" \".join(words[: self.split_length])\n remaining_words = words[self.split_length :]\n return current_chunk, \" \".join(remaining_words)\n\n # split by characters\n text = current_chunk\n current_chunk = text[: self.split_length]\n remaining_chars = text[self.split_length :]\n return current_chunk, remaining_chars"}, {"class_start_lineno": 15, "class_end_lineno": 421, "func_start_lineno": 135, "func_end_lineno": 202, "func_code": " def _apply_overlap(self, chunks: List[str]) -> List[str]:\n \"\"\"\n Applies an overlap between consecutive chunks if the chunk_overlap attribute is greater than zero.\n\n Works for both word- and character-level splitting. It trims the last chunk if it exceeds the split_length and\n adds the trimmed content to the next chunk. If the last chunk is still too long after trimming, it splits it\n and adds the first chunk to the list. This process continues until the last chunk is within the split_length.\n\n :param chunks: A list of text chunks.\n :returns:\n A list of text chunks with the overlap applied.\n \"\"\"\n overlapped_chunks: List[str] = []\n\n for idx, chunk in enumerate(chunks):\n if idx == 0:\n overlapped_chunks.append(chunk)\n continue\n\n # get the overlap between the current and previous chunk\n overlap, prev_chunk = self._get_overlap(overlapped_chunks)\n if overlap == prev_chunk:\n logger.warning(\n \"Overlap is the same as the previous chunk. \"\n \"Consider increasing the `split_length` parameter or decreasing the `split_overlap` parameter.\"\n )\n\n # create a new chunk starting with the overlap\n current_chunk = overlap + \" \" + chunk if self.split_units == \"word\" else overlap + chunk\n\n # if this new chunk exceeds 'split_length', trim it and move the remaining text to the next chunk\n # if this is the last chunk, another new chunk will contain the trimmed text preceded by the overlap\n # of the last chunk\n if self._chunk_length(current_chunk) > self.split_length:\n current_chunk, remaining_text = self._split_chunk(current_chunk)\n if idx < len(chunks) - 1:\n chunks[idx + 1] = remaining_text + (\" \" if self.split_units == \"word\" else \"\") + chunks[idx + 1]\n elif remaining_text:\n # create a new chunk with the trimmed text preceded by the overlap of the last chunk\n overlapped_chunks.append(current_chunk)\n chunk = remaining_text\n overlap, _ = self._get_overlap(overlapped_chunks)\n current_chunk = overlap + \" \" + chunk if self.split_units == \"word\" else overlap + chunk\n\n overlapped_chunks.append(current_chunk)\n\n # it can still be that the new last chunk exceeds the 'split_length'\n # continue splitting until the last chunk is within 'split_length'\n if idx == len(chunks) - 1 and self._chunk_length(current_chunk) > self.split_length:\n last_chunk = overlapped_chunks.pop()\n first_chunk, remaining_chunk = self._split_chunk(last_chunk)\n overlapped_chunks.append(first_chunk)\n\n while remaining_chunk:\n # combine overlap with remaining chunk\n overlap, _ = self._get_overlap(overlapped_chunks)\n current = overlap + (\" \" if self.split_units == \"word\" else \"\") + remaining_chunk\n\n # if it fits within split_length we are done\n if self._chunk_length(current) <= self.split_length:\n overlapped_chunks.append(current)\n break\n\n # otherwise split it again\n first_chunk, remaining_chunk = self._split_chunk(current)\n overlapped_chunks.append(first_chunk)\n\n return overlapped_chunks"}, {"class_start_lineno": 116, "class_end_lineno": 238, "func_start_lineno": 147, "func_end_lineno": 159, "func_code": " def split_sentences(self, text: str) -> List[Dict[str, Any]]:\n \"\"\"\n Splits a text into sentences including references to original char positions for each split.\n\n :param text: The text to split.\n :returns: list of sentences with positions.\n \"\"\"\n sentence_spans = list(self.sentence_tokenizer.span_tokenize(text))\n if self.use_split_rules:\n sentence_spans = SentenceSplitter._apply_split_rules(text, sentence_spans)\n\n sentences = [{\"sentence\": text[start:end], \"start\": start, \"end\": end} for start, end in sentence_spans]\n return sentences"}, {"class_start_lineno": 15, "class_end_lineno": 421, "func_start_lineno": 229, "func_end_lineno": 311, "func_code": " def _chunk_text(self, text: str) -> List[str]:\n \"\"\"\n Recursive chunking algorithm that divides text into smaller chunks based on a list of separator characters.\n\n It starts with a list of separator characters (e.g., [\"\\n\\n\", \"sentence\", \"\\n\", \" \"]) and attempts to divide\n the text using the first separator. If the resulting chunks are still larger than the specified chunk size,\n it moves to the next separator in the list. This process continues recursively, progressively applying each\n specific separator until the chunks meet the desired size criteria.\n\n :param text: The text to be split into chunks.\n :returns:\n A list of text chunks.\n \"\"\"\n if self._chunk_length(text) <= self.split_length:\n return [text]\n\n for curr_separator in self.separators: # type: ignore # the caller already checked that separators is not None\n if curr_separator == \"sentence\":\n # re. ignore: correct SentenceSplitter initialization is checked at the initialization of the component\n sentence_with_spans = self.nltk_tokenizer.split_sentences(text) # type: ignore\n splits = [sentence[\"sentence\"] for sentence in sentence_with_spans]\n else:\n # add escape \"\\\" to the separator and wrapped it in a group so that it's included in the splits as well\n escaped_separator = re.escape(curr_separator)\n escaped_separator = f\"({escaped_separator})\"\n\n # split the text and merge every two consecutive splits, i.e.: the text and the separator after it\n splits = re.split(escaped_separator, text)\n splits = [\n \"\".join([splits[i], splits[i + 1]]) if i < len(splits) - 1 else splits[i]\n for i in range(0, len(splits), 2)\n ]\n\n # remove last split if it's empty\n splits = splits[:-1] if splits[-1] == \"\" else splits\n\n if len(splits) == 1: # go to next separator, if current separator not found in the text\n continue\n\n chunks = []\n current_chunk: List[str] = []\n current_length = 0\n\n # check splits, if any is too long, recursively chunk it, otherwise add to current chunk\n for split in splits:\n split_text = split\n\n # if adding this split exceeds chunk_size, process current_chunk\n if current_length + self._chunk_length(split_text) > self.split_length:\n # process current_chunk\n if current_chunk: # keep the good splits\n chunks.append(\"\".join(current_chunk))\n current_chunk = []\n current_length = 0\n\n # recursively handle splits that are too large\n if self._chunk_length(split_text) > self.split_length:\n if curr_separator == self.separators[-1]:\n # tried last separator, can't split further, do a fixed-split based on word/character\n fall_back_chunks = self._fall_back_to_fixed_chunking(split_text, self.split_units)\n chunks.extend(fall_back_chunks)\n else:\n chunks.extend(self._chunk_text(split_text))\n current_length += self._chunk_length(split_text)\n\n else:\n current_chunk.append(split_text)\n current_length += self._chunk_length(split_text)\n else:\n current_chunk.append(split_text)\n current_length += self._chunk_length(split_text)\n\n if current_chunk:\n chunks.append(\"\".join(current_chunk))\n\n if self.split_overlap > 0:\n chunks = self._apply_overlap(chunks)\n\n if chunks:\n return chunks\n\n # if no separator worked, fall back to word- or character-level chunking\n return self._fall_back_to_fixed_chunking(text, self.split_units)"}], "type": ["function_empty", "Development"], "node": ["haystack.components.preprocessors.recursive_splitter.RecursiveDocumentSplitter._chunk_length", "haystack.components.preprocessors.recursive_splitter.RecursiveDocumentSplitter._get_overlap", "haystack.components.preprocessors.recursive_splitter.RecursiveDocumentSplitter._split_chunk", "haystack.components.preprocessors.recursive_splitter.RecursiveDocumentSplitter._apply_overlap", "haystack.components.preprocessors.sentence_tokenizer.SentenceSplitter.split_sentences", "haystack.components.preprocessors.recursive_splitter.RecursiveDocumentSplitter._chunk_text"], "language": "Python", "toolfunc_count": 4, "func_count": 5, "pytest_info": {"total_num": 35, "base_passed_num": 9}} {"id": ["haystack.haystack.utils.device.ComponentDevice::to_dict", "haystack.haystack.components.rankers.sentence_transformers_diversity.SentenceTransformersDiversityRanker::to_dict", "haystack.haystack.components.rankers.sentence_transformers_diversity.SentenceTransformersDiversityRanker::_greedy_diversity_order", "haystack.haystack.components.rankers.sentence_transformers_diversity.SentenceTransformersDiversityRanker::run"], "project": "haystack", "origin_file": ["haystack/utils/device.py", "haystack/components/rankers/sentence_transformers_diversity.py", "haystack/components/rankers/sentence_transformers_diversity.py", "haystack/components/rankers/sentence_transformers_diversity.py"], "test_list": ["test/components/rankers/test_sentence_transformers_diversity.py"], "prob_info": [{"class_start_lineno": 240, "class_end_lineno": 480, "func_start_lineno": 450, "func_end_lineno": 463, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Convert the component device representation to a JSON-serializable dictionary.\n\n :returns:\n The dictionary representation.\n \"\"\"\n if self._single_device is not None:\n return {\"type\": \"single\", \"device\": str(self._single_device)}\n elif self._multiple_devices is not None:\n return {\"type\": \"multiple\", \"device_map\": self._multiple_devices.to_dict()}\n else:\n # Unreachable\n assert False"}, {"class_start_lineno": 76, "class_end_lineno": 435, "func_start_lineno": 212, "func_end_lineno": 241, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serializes the component to a dictionary.\n\n :returns:\n Dictionary with serialized data.\n \"\"\"\n serialization_dict = default_to_dict(\n self,\n model=self.model_name_or_path,\n top_k=self.top_k,\n device=self.device.to_dict(),\n token=self.token.to_dict() if self.token else None,\n similarity=str(self.similarity),\n query_prefix=self.query_prefix,\n query_suffix=self.query_suffix,\n document_prefix=self.document_prefix,\n document_suffix=self.document_suffix,\n meta_fields_to_embed=self.meta_fields_to_embed,\n embedding_separator=self.embedding_separator,\n strategy=str(self.strategy),\n lambda_threshold=self.lambda_threshold,\n model_kwargs=self.model_kwargs,\n tokenizer_kwargs=self.tokenizer_kwargs,\n config_kwargs=self.config_kwargs,\n backend=self.backend,\n )\n if serialization_dict[\"init_parameters\"].get(\"model_kwargs\") is not None:\n serialize_hf_model_kwargs(serialization_dict[\"init_parameters\"][\"model_kwargs\"])\n return serialization_dict"}, {"class_start_lineno": 76, "class_end_lineno": 435, "func_start_lineno": 279, "func_end_lineno": 323, "func_code": " def _greedy_diversity_order(self, query: str, documents: List[Document]) -> List[Document]:\n \"\"\"\n Orders the given list of documents to maximize diversity.\n\n The algorithm first calculates embeddings for each document and the query. It starts by selecting the document\n that is semantically closest to the query. Then, for each remaining document, it selects the one that, on\n average, is least similar to the already selected documents. This process continues until all documents are\n selected, resulting in a list where each subsequent document contributes the most to the overall diversity of\n the selected set.\n\n :param query: The search query.\n :param documents: The list of Document objects to be ranked.\n\n :return: A list of documents ordered to maximize diversity.\n \"\"\"\n texts_to_embed = self._prepare_texts_to_embed(documents)\n\n doc_embeddings, query_embedding = self._embed_and_normalize(query, texts_to_embed)\n\n n = len(documents)\n selected: List[int] = []\n\n # Compute the similarity vector between the query and documents\n query_doc_sim = query_embedding @ doc_embeddings.T\n\n # Start with the document with the highest similarity to the query\n selected.append(int(torch.argmax(query_doc_sim).item()))\n\n selected_sum = doc_embeddings[selected[0]] / n\n\n while len(selected) < n:\n # Compute mean of dot products of all selected documents and all other documents\n similarities = selected_sum @ doc_embeddings.T\n # Mask documents that are already selected\n similarities[selected] = torch.inf\n # Select the document with the lowest total similarity score\n index_unselected = int(torch.argmin(similarities).item())\n selected.append(index_unselected)\n # It's enough just to add to the selected vectors because dot product is distributive\n # It's divided by n for numerical stability\n selected_sum += doc_embeddings[index_unselected] / n\n\n ranked_docs: List[Document] = [documents[i] for i in selected]\n\n return ranked_docs"}, {"class_start_lineno": 76, "class_end_lineno": 435, "func_start_lineno": 388, "func_end_lineno": 435, "func_code": " def run(\n self,\n query: str,\n documents: List[Document],\n top_k: Optional[int] = None,\n lambda_threshold: Optional[float] = None,\n ) -> Dict[str, List[Document]]:\n \"\"\"\n Rank the documents based on their diversity.\n\n :param query: The search query.\n :param documents: List of Document objects to be ranker.\n :param top_k: Optional. An integer to override the top_k set during initialization.\n :param lambda_threshold: Override the trade-off parameter between relevance and diversity. Only used when\n strategy is \"maximum_margin_relevance\".\n\n :returns: A dictionary with the following key:\n - `documents`: List of Document objects that have been selected based on the diversity ranking.\n\n :raises ValueError: If the top_k value is less than or equal to 0.\n :raises RuntimeError: If the component has not been warmed up.\n \"\"\"\n if self.model is None:\n error_msg = (\n \"The component SentenceTransformersDiversityRanker wasn't warmed up. \"\n \"Run 'warm_up()' before calling 'run()'.\"\n )\n raise RuntimeError(error_msg)\n\n if not documents:\n return {\"documents\": []}\n\n if top_k is None:\n top_k = self.top_k\n elif not 0 < top_k <= len(documents):\n raise ValueError(f\"top_k must be between 1 and {len(documents)}, but got {top_k}\")\n\n if self.strategy == DiversityRankingStrategy.MAXIMUM_MARGIN_RELEVANCE:\n if lambda_threshold is None:\n lambda_threshold = self.lambda_threshold\n self._check_lambda_threshold(lambda_threshold, self.strategy)\n re_ranked_docs = self._maximum_margin_relevance(\n query=query, documents=documents, lambda_threshold=lambda_threshold, top_k=top_k\n )\n else:\n re_ranked_docs = self._greedy_diversity_order(query=query, documents=documents)\n\n return {\"documents\": re_ranked_docs[:top_k]}"}], "type": ["function_empty", "Development"], "node": ["haystack.utils.device.ComponentDevice.to_dict", "haystack.components.rankers.sentence_transformers_diversity.SentenceTransformersDiversityRanker.to_dict", "haystack.components.rankers.sentence_transformers_diversity.SentenceTransformersDiversityRanker._greedy_diversity_order", "haystack.components.rankers.sentence_transformers_diversity.SentenceTransformersDiversityRanker.run"], "language": "Python", "toolfunc_count": 3, "func_count": 4, "pytest_info": {"total_num": 53, "base_passed_num": 17}} {"id": ["haystack.haystack.utils.auth.EnvVarSecret::resolve_value", "haystack.haystack.components.rankers.transformers_similarity.TransformersSimilarityRanker::warm_up"], "project": "haystack", "origin_file": ["haystack/utils/auth.py", "haystack/components/rankers/transformers_similarity.py"], "test_list": ["test/components/rankers/test_transformers_similarity.py"], "prob_info": [{"class_start_lineno": 171, "class_end_lineno": 211, "func_start_lineno": 196, "func_end_lineno": 206, "func_code": " def resolve_value(self) -> Optional[Any]:\n \"\"\"Resolve the secret to an atomic value. The semantics of the value is secret-dependent.\"\"\"\n out = None\n for env_var in self._env_vars:\n value = os.getenv(env_var)\n if value is not None:\n out = value\n break\n if out is None and self._strict:\n raise ValueError(f\"None of the following authentication environment variables are set: {self._env_vars}\")\n return out"}, {"class_start_lineno": 24, "class_end_lineno": 309, "func_start_lineno": 142, "func_end_lineno": 155, "func_code": " def warm_up(self):\n \"\"\"\n Initializes the component.\n \"\"\"\n if self.model is None:\n self.model = AutoModelForSequenceClassification.from_pretrained(\n self.model_name_or_path, token=self.token.resolve_value() if self.token else None, **self.model_kwargs\n )\n self.tokenizer = AutoTokenizer.from_pretrained(\n self.model_name_or_path,\n token=self.token.resolve_value() if self.token else None,\n **self.tokenizer_kwargs,\n )\n self.device = ComponentDevice.from_multiple(device_map=DeviceMap.from_hf(self.model.hf_device_map))"}], "type": ["Development"], "node": ["haystack.utils.auth.EnvVarSecret.resolve_value", "haystack.components.rankers.transformers_similarity.TransformersSimilarityRanker.warm_up"], "language": "Python", "toolfunc_count": 0, "func_count": 2, "pytest_info": {"total_num": 26, "base_passed_num": 8}} {"id": ["haystack.haystack.core.serialization.default_to_dict", "haystack.haystack.utils.hf.serialize_hf_model_kwargs", "haystack.haystack.components.readers.extractive.ExtractiveReader::to_dict"], "project": "haystack", "origin_file": ["haystack/core/serialization.py", "haystack/utils/hf.py", "haystack/components/readers/extractive.py"], "test_list": ["test/components/readers/test_extractive.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 264, "func_start_lineno": 172, "func_end_lineno": 210, "func_code": "def default_to_dict(obj: Any, **init_parameters) -> Dict[str, Any]:\n \"\"\"\n Utility function to serialize an object to a dictionary.\n\n This is mostly necessary for components but can be used by any object.\n `init_parameters` are parameters passed to the object class `__init__`.\n They must be defined explicitly as they'll be used when creating a new\n instance of `obj` with `from_dict`. Omitting them might cause deserialisation\n errors or unexpected behaviours later, when calling `from_dict`.\n\n An example usage:\n\n ```python\n class MyClass:\n def __init__(self, my_param: int = 10):\n self.my_param = my_param\n\n def to_dict(self):\n return default_to_dict(self, my_param=self.my_param)\n\n\n obj = MyClass(my_param=1000)\n data = obj.to_dict()\n assert data == {\n \"type\": \"MyClass\",\n \"init_parameters\": {\n \"my_param\": 1000,\n },\n }\n ```\n\n :param obj:\n The object to be serialized.\n :param init_parameters:\n The parameters used to create a new instance of the class.\n :returns:\n A dictionary representation of the instance.\n \"\"\"\n return {\"type\": generate_qualified_class_name(type(obj)), \"init_parameters\": init_parameters}"}, {"class_start_lineno": 1, "class_end_lineno": 395, "func_start_lineno": 98, "func_end_lineno": 112, "func_code": "def serialize_hf_model_kwargs(kwargs: Dict[str, Any]):\n \"\"\"\n Recursively serialize HuggingFace specific model keyword arguments in-place to make them JSON serializable.\n\n :param kwargs: The keyword arguments to serialize\n \"\"\"\n torch_import.check()\n\n for k, v in kwargs.items():\n # torch.dtype\n if isinstance(v, torch.dtype):\n kwargs[k] = str(v)\n\n if isinstance(v, dict):\n serialize_hf_model_kwargs(v)"}, {"class_start_lineno": 26, "class_end_lineno": 660, "func_start_lineno": 136, "func_end_lineno": 160, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serializes the component to a dictionary.\n\n :returns:\n Dictionary with serialized data.\n \"\"\"\n serialization_dict = default_to_dict(\n self,\n model=self.model_name_or_path,\n device=None,\n token=self.token.to_dict() if self.token else None,\n max_seq_length=self.max_seq_length,\n top_k=self.top_k,\n score_threshold=self.score_threshold,\n stride=self.stride,\n max_batch_size=self.max_batch_size,\n answers_per_seq=self.answers_per_seq,\n no_answer=self.no_answer,\n calibration_factor=self.calibration_factor,\n model_kwargs=self.model_kwargs,\n )\n\n serialize_hf_model_kwargs(serialization_dict[\"init_parameters\"][\"model_kwargs\"])\n return serialization_dict"}], "type": ["function_empty"], "node": ["haystack.core.serialization.default_to_dict", "haystack.utils.hf.serialize_hf_model_kwargs", "haystack.components.readers.extractive.ExtractiveReader.to_dict"], "language": "Python", "toolfunc_count": 3, "func_count": 3, "pytest_info": {"total_num": 34, "base_passed_num": 21}} {"id": ["haystack.haystack.core.serialization.default_to_dict", "haystack.haystack.document_stores.in_memory.document_store.InMemoryDocumentStore::to_dict"], "project": "haystack", "origin_file": ["haystack/core/serialization.py", "haystack/document_stores/in_memory/document_store.py", "haystack/components/retrievers/filter_retriever.py"], "test_list": ["test/components/retrievers/test_filter_retriever.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 264, "func_start_lineno": 172, "func_end_lineno": 210, "func_code": "def default_to_dict(obj: Any, **init_parameters) -> Dict[str, Any]:\n \"\"\"\n Utility function to serialize an object to a dictionary.\n\n This is mostly necessary for components but can be used by any object.\n `init_parameters` are parameters passed to the object class `__init__`.\n They must be defined explicitly as they'll be used when creating a new\n instance of `obj` with `from_dict`. Omitting them might cause deserialisation\n errors or unexpected behaviours later, when calling `from_dict`.\n\n An example usage:\n\n ```python\n class MyClass:\n def __init__(self, my_param: int = 10):\n self.my_param = my_param\n\n def to_dict(self):\n return default_to_dict(self, my_param=self.my_param)\n\n\n obj = MyClass(my_param=1000)\n data = obj.to_dict()\n assert data == {\n \"type\": \"MyClass\",\n \"init_parameters\": {\n \"my_param\": 1000,\n },\n }\n ```\n\n :param obj:\n The object to be serialized.\n :param init_parameters:\n The parameters used to create a new instance of the class.\n :returns:\n A dictionary representation of the instance.\n \"\"\"\n return {\"type\": generate_qualified_class_name(type(obj)), \"init_parameters\": init_parameters}"}, {"class_start_lineno": 58, "class_end_lineno": 738, "func_start_lineno": 344, "func_end_lineno": 358, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serializes the component to a dictionary.\n\n :returns:\n Dictionary with serialized data.\n \"\"\"\n return default_to_dict(\n self,\n bm25_tokenization_regex=self.bm25_tokenization_regex,\n bm25_algorithm=self.bm25_algorithm,\n bm25_parameters=self.bm25_parameters,\n embedding_similarity_function=self.embedding_similarity_function,\n index=self.index,\n )"}, {"class_start_lineno": 15, "class_end_lineno": 96, "func_start_lineno": 60, "func_end_lineno": 68, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serializes the component to a dictionary.\n\n :returns:\n Dictionary with serialized data.\n \"\"\"\n docstore = self.document_store.to_dict()\n return default_to_dict(self, document_store=docstore, filters=self.filters)"}], "type": ["function_empty"], "node": ["haystack.core.serialization.default_to_dict", "haystack.document_stores.in_memory.document_store.InMemoryDocumentStore.to_dict", "haystack.components.retrievers.filter_retriever.FilterRetriever.to_dict"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 10, "base_passed_num": 7}} {"id": ["haystack.haystack.core.serialization.default_to_dict", "haystack.haystack.document_stores.in_memory.document_store.InMemoryDocumentStore::to_dict", "haystack.haystack.components.preprocessors.document_splitter.DocumentSplitter::_split_by_character", "haystack.haystack.components.preprocessors.document_splitter.DocumentSplitter::run"], "project": "haystack", "origin_file": ["haystack/core/serialization.py", "haystack/document_stores/in_memory/document_store.py", "haystack/components/retrievers/sentence_window_retriever.py", "haystack/components/preprocessors/document_splitter.py", "haystack/components/preprocessors/document_splitter.py", "haystack/components/preprocessors/document_splitter.py"], "test_list": ["test/components/retrievers/test_sentence_window_retriever.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 264, "func_start_lineno": 172, "func_end_lineno": 210, "func_code": "def default_to_dict(obj: Any, **init_parameters) -> Dict[str, Any]:\n \"\"\"\n Utility function to serialize an object to a dictionary.\n\n This is mostly necessary for components but can be used by any object.\n `init_parameters` are parameters passed to the object class `__init__`.\n They must be defined explicitly as they'll be used when creating a new\n instance of `obj` with `from_dict`. Omitting them might cause deserialisation\n errors or unexpected behaviours later, when calling `from_dict`.\n\n An example usage:\n\n ```python\n class MyClass:\n def __init__(self, my_param: int = 10):\n self.my_param = my_param\n\n def to_dict(self):\n return default_to_dict(self, my_param=self.my_param)\n\n\n obj = MyClass(my_param=1000)\n data = obj.to_dict()\n assert data == {\n \"type\": \"MyClass\",\n \"init_parameters\": {\n \"my_param\": 1000,\n },\n }\n ```\n\n :param obj:\n The object to be serialized.\n :param init_parameters:\n The parameters used to create a new instance of the class.\n :returns:\n A dictionary representation of the instance.\n \"\"\"\n return {\"type\": generate_qualified_class_name(type(obj)), \"init_parameters\": init_parameters}"}, {"class_start_lineno": 58, "class_end_lineno": 738, "func_start_lineno": 344, "func_end_lineno": 358, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serializes the component to a dictionary.\n\n :returns:\n Dictionary with serialized data.\n \"\"\"\n return default_to_dict(\n self,\n bm25_tokenization_regex=self.bm25_tokenization_regex,\n bm25_algorithm=self.bm25_algorithm,\n bm25_parameters=self.bm25_parameters,\n embedding_similarity_function=self.embedding_similarity_function,\n index=self.index,\n )"}, {"class_start_lineno": 13, "class_end_lineno": 198, "func_start_lineno": 122, "func_end_lineno": 130, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serializes the component to a dictionary.\n\n :returns:\n Dictionary with serialized data.\n \"\"\"\n docstore = self.document_store.to_dict()\n return default_to_dict(self, document_store=docstore, window_size=self.window_size)"}, {"class_start_lineno": 22, "class_end_lineno": 490, "func_start_lineno": 238, "func_end_lineno": 251, "func_code": " def _split_by_character(self, doc) -> List[Document]:\n split_at = _CHARACTER_SPLIT_BY_MAPPING[self.split_by]\n units = doc.content.split(split_at)\n # Add the delimiter back to all units except the last one\n for i in range(len(units) - 1):\n units[i] += split_at\n text_splits, splits_pages, splits_start_idxs = self._concatenate_units(\n units, self.split_length, self.split_overlap, self.split_threshold\n )\n metadata = deepcopy(doc.meta)\n metadata[\"source_id\"] = doc.id\n return self._create_docs_from_splits(\n text_splits=text_splits, splits_pages=splits_pages, splits_start_idxs=splits_start_idxs, meta=metadata\n )"}, {"class_start_lineno": 22, "class_end_lineno": 490, "func_start_lineno": 204, "func_end_lineno": 211, "func_code": " def _split_document(self, doc: Document) -> List[Document]:\n if self.split_by == \"sentence\" or self.respect_sentence_boundary:\n return self._split_by_nltk_sentence(doc)\n\n if self.split_by == \"function\" and self.splitting_function is not None:\n return self._split_by_function(doc)\n\n return self._split_by_character(doc)"}, {"class_start_lineno": 22, "class_end_lineno": 490, "func_start_lineno": 166, "func_end_lineno": 202, "func_code": " def run(self, documents: List[Document]):\n \"\"\"\n Split documents into smaller parts.\n\n Splits documents by the unit expressed in `split_by`, with a length of `split_length`\n and an overlap of `split_overlap`.\n\n :param documents: The documents to split.\n :returns: A dictionary with the following key:\n - `documents`: List of documents with the split texts. Each document includes:\n - A metadata field `source_id` to track the original document.\n - A metadata field `page_number` to track the original page number.\n - All other metadata copied from the original document.\n\n :raises TypeError: if the input is not a list of Documents.\n :raises ValueError: if the content of a document is None.\n \"\"\"\n if self._use_sentence_splitter and self.sentence_splitter is None:\n raise RuntimeError(\n \"The component DocumentSplitter wasn't warmed up. Run 'warm_up()' before calling 'run()'.\"\n )\n\n if not isinstance(documents, list) or (documents and not isinstance(documents[0], Document)):\n raise TypeError(\"DocumentSplitter expects a List of Documents as input.\")\n\n split_docs: List[Document] = []\n for doc in documents:\n if doc.content is None:\n raise ValueError(\n f\"DocumentSplitter only works with text documents but content for document ID {doc.id} is None.\"\n )\n if doc.content == \"\":\n logger.warning(\"Document ID {doc_id} has an empty content. Skipping this document.\", doc_id=doc.id)\n continue\n\n split_docs += self._split_document(doc)\n return {\"documents\": split_docs}"}], "type": ["function_empty", "Development"], "node": ["haystack.core.serialization.default_to_dict", "haystack.document_stores.in_memory.document_store.InMemoryDocumentStore.to_dict", "haystack.components.retrievers.sentence_window_retriever.SentenceWindowRetriever.to_dict", "haystack.components.preprocessors.document_splitter.DocumentSplitter._split_by_character", "haystack.components.preprocessors.document_splitter.DocumentSplitter._split_document", "haystack.components.preprocessors.document_splitter.DocumentSplitter.run"], "language": "Python", "toolfunc_count": 3, "func_count": 4, "pytest_info": {"total_num": 16, "base_passed_num": 12}} {"id": ["haystack.haystack.utils.type_serialization.serialize_type", "haystack.haystack.components.routers.conditional_router.ConditionalRouter::to_dict"], "project": "haystack", "origin_file": ["haystack/utils/type_serialization.py", "haystack/components/routers/conditional_router.py"], "test_list": ["test/components/routers/test_conditional_router.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 170, "func_start_lineno": 19, "func_end_lineno": 52, "func_code": "def serialize_type(target: Any) -> str:\n \"\"\"\n Serializes a type or an instance to its string representation, including the module name.\n\n This function handles types, instances of types, and special typing objects.\n It assumes that non-typing objects will have a '__name__' attribute.\n\n :param target:\n The object to serialize, can be an instance or a type.\n :return:\n The string representation of the type.\n \"\"\"\n name = getattr(target, \"__name__\", str(target))\n\n # Remove the 'typing.' prefix when using python <3.9\n if name.startswith(\"typing.\"):\n name = name[7:]\n # Remove the arguments from the name when using python <3.9\n if \"[\" in name:\n name = name.split(\"[\")[0]\n\n # Get module name\n module = inspect.getmodule(target)\n module_name = \"\"\n # We omit the module name for builtins to not clutter the output\n if module and hasattr(module, \"__name__\") and module.__name__ != \"builtins\":\n module_name = f\"{module.__name__}\"\n\n args = get_args(target)\n if args:\n args_str = \", \".join([serialize_type(a) for a in args if a is not type(None)])\n return f\"{module_name}.{name}[{args_str}]\" if module_name else f\"{name}[{args_str}]\"\n\n return f\"{module_name}.{name}\" if module_name else f\"{name}\""}, {"class_start_lineno": 29, "class_end_lineno": 433, "func_start_lineno": 237, "func_end_lineno": 256, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serializes the component to a dictionary.\n\n :returns:\n Dictionary with serialized data.\n \"\"\"\n serialized_routes = []\n for route in self.routes:\n # output_type needs to be serialized to a string\n serialized_routes.append({**route, \"output_type\": serialize_type(route[\"output_type\"])})\n se_filters = {name: serialize_callable(filter_func) for name, filter_func in self.custom_filters.items()}\n return default_to_dict(\n self,\n routes=serialized_routes,\n custom_filters=se_filters,\n unsafe=self._unsafe,\n validate_output_type=self._validate_output_type,\n optional_variables=self.optional_variables,\n )"}], "type": ["function_empty", "Development"], "node": ["haystack.utils.type_serialization.serialize_type", "haystack.components.routers.conditional_router.ConditionalRouter.to_dict"], "language": "Python", "toolfunc_count": 1, "func_count": 2, "pytest_info": {"total_num": 23, "base_passed_num": 15}} {"id": ["haystack.haystack.components.samplers.top_p.TopPSampler::_get_documents_and_scores", "haystack.haystack.components.samplers.top_p.TopPSampler::run"], "project": "haystack", "origin_file": ["haystack/components/samplers/top_p.py", "haystack/components/samplers/top_p.py"], "test_list": ["test/components/samplers/test_top_p.py"], "prob_info": [{"class_start_lineno": 18, "class_end_lineno": 177, "func_start_lineno": 144, "func_end_lineno": 177, "func_code": " def _get_documents_and_scores(self, documents: List[Document]) -> Tuple[List[Document], List[float]]:\n \"\"\"\n Checks if documents have scores in their metadata or score field and returns the documents with scores.\n\n :param documents: List of Documents.\n :return: List of scores.\n \"\"\"\n docs_with_scores = []\n scores = []\n docs_missing_scores = []\n for doc in documents:\n score = self._get_doc_score(doc=doc, score_field=self.score_field)\n if score is None:\n docs_missing_scores.append(doc)\n else:\n scores.append(score)\n docs_with_scores.append(doc)\n\n if len(docs_missing_scores) > 0:\n missing_scores_docs_ids = [d.id for d in docs_missing_scores if d.id]\n if self.score_field:\n logger.warning(\n \"Score field '{score_field}' not found in metadata of documents with IDs: {doc_ids}.\"\n \"Make sure that all documents have a score field '{score_field_2}' in their metadata.\",\n score_field=self.score_field,\n doc_ids=\",\".join(missing_scores_docs_ids),\n score_field_2=self.score_field,\n )\n else:\n logger.warning(\n \"Ensure all documents have a valid score value. These documents {doc_ids} are missing scores.\",\n doc_ids=\",\".join(missing_scores_docs_ids),\n )\n return docs_with_scores, scores"}, {"class_start_lineno": 18, "class_end_lineno": 177, "func_start_lineno": 65, "func_end_lineno": 122, "func_code": " def run(self, documents: List[Document], top_p: Optional[float] = None):\n \"\"\"\n Filters documents using top-p sampling based on their scores.\n\n If the specified top_p results in no documents being selected (especially in cases of a low top_p value), the\n method returns the document with the highest score.\n\n :param documents: List of Document objects to be filtered.\n :param top_p: If specified, a float to override the cumulative probability threshold set during initialization.\n\n :returns: A dictionary with the following key:\n - `documents`: List of Document objects that have been selected based on the top-p sampling.\n :raises ValueError: If the top_p value is not within the range [0, 1].\n \"\"\"\n if not documents:\n return {\"documents\": []}\n\n top_p = top_p or self.top_p\n if not 0 <= top_p <= 1:\n raise ValueError(f\"top_p must be between 0 and 1. Got {top_p}.\")\n\n documents_with_scores, scores = self._get_documents_and_scores(documents)\n if len(documents_with_scores) == 0:\n logger.warning(\"No documents with scores found. Returning the original documents.\")\n return {\"documents\": documents}\n\n sorted_docs_with_scores = sorted(zip(documents_with_scores, scores), key=lambda x: x[1], reverse=True)\n sorted_documents, sorted_scores = [list(t) for t in zip(*sorted_docs_with_scores)]\n\n tensor_scores = torch.tensor(sorted_scores, dtype=torch.float32)\n probs = torch.nn.functional.softmax(tensor_scores, dim=-1)\n cumulative_probs = torch.cumsum(probs, dim=-1)\n\n # Check if the cumulative probabilities are close to top_p with a 1e-6 tolerance\n close_to_top_p = torch.isclose(cumulative_probs, torch.tensor(top_p, device=cumulative_probs.device), atol=1e-6)\n\n # Combine the close_to_top_p with original condition using logical OR\n condition = (cumulative_probs <= top_p) | close_to_top_p\n\n # Find the indices with cumulative probabilities that exceed top_p\n top_p_indices = torch.where(torch.BoolTensor(condition))[0]\n\n # Map the selected indices back to their original indices\n selected_docs = [sorted_documents[i.item()] for i in top_p_indices]\n\n if self.min_top_k and len(selected_docs) < self.min_top_k:\n selected_docs = sorted_documents[: self.min_top_k]\n\n # If low p resulted in no documents being selected, then return at least one document\n if len(selected_docs) == 0:\n logger.warning(\n \"Top-p sampling with p={top_p} resulted in no documents being selected. \"\n \"Returning the document with the highest score.\",\n top_p=top_p,\n )\n selected_docs = [sorted_documents[0]]\n\n return {\"documents\": selected_docs}"}], "type": ["function_empty", "Development"], "node": ["haystack.components.samplers.top_p.TopPSampler._get_documents_and_scores", "haystack.components.samplers.top_p.TopPSampler.run"], "language": "Python", "toolfunc_count": 1, "func_count": 2, "pytest_info": {"total_num": 11, "base_passed_num": 3}} {"id": ["haystack.haystack.core.type_utils._strict_types_are_compatible", "haystack.haystack.core.type_utils._types_are_compatible", "haystack.haystack.components.tools.tool_invoker.ToolInvoker::to_dict", "haystack.haystack.components.generators.chat.openai.OpenAIChatGenerator::to_dict", "haystack.haystack.core.serialization.component_to_dict"], "project": "haystack", "origin_file": ["haystack/core/type_utils.py", "haystack/core/type_utils.py", "haystack/components/tools/tool_invoker.py", "haystack/components/generators/chat/openai.py", "haystack/core/serialization.py"], "test_list": ["test/components/tools/test_tool_invoker.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 105, "func_start_lineno": 29, "func_end_lineno": 76, "func_code": "def _strict_types_are_compatible(sender, receiver): # pylint: disable=too-many-return-statements\n \"\"\"\n Checks whether the sender type is equal to or a subtype of the receiver type under strict validation.\n\n Note: this method has no pretense to perform proper type matching. It especially does not deal with aliasing of\n typing classes such as `List` or `Dict` to their runtime counterparts `list` and `dict`. It also does not deal well\n with \"bare\" types, so `List` is treated differently from `List[Any]`, even though they should be the same.\n Consider simplifying the typing of your components if you observe unexpected errors during component connection.\n\n :param sender: The sender type.\n :param receiver: The receiver type.\n :return: True if the sender type is strictly compatible with the receiver type, False otherwise.\n \"\"\"\n if sender == receiver or receiver is Any:\n return True\n\n if sender is Any:\n return False\n\n try:\n if issubclass(sender, receiver):\n return True\n except TypeError: # typing classes can't be used with issubclass, so we deal with them below\n pass\n\n sender_origin = get_origin(sender)\n receiver_origin = get_origin(receiver)\n\n if sender_origin is not Union and receiver_origin is Union:\n return any(_strict_types_are_compatible(sender, union_arg) for union_arg in get_args(receiver))\n\n # Both must have origins and they must be equal\n if not (sender_origin and receiver_origin and sender_origin == receiver_origin):\n return False\n\n # Compare generic type arguments\n sender_args = get_args(sender)\n receiver_args = get_args(receiver)\n\n # Handle bare types\n if not sender_args and sender_origin:\n sender_args = (Any,)\n if not receiver_args and receiver_origin:\n receiver_args = (Any,) * (len(sender_args) if sender_args else 1)\n if len(sender_args) > len(receiver_args):\n return False\n\n return all(_strict_types_are_compatible(*args) for args in zip(sender_args, receiver_args))"}, {"class_start_lineno": 1, "class_end_lineno": 105, "func_start_lineno": 14, "func_end_lineno": 26, "func_code": "def _types_are_compatible(sender, receiver, type_validation: bool = True) -> bool:\n \"\"\"\n Determines if two types are compatible based on the specified validation mode.\n\n :param sender: The sender type.\n :param receiver: The receiver type.\n :param type_validation: Whether to perform strict type validation.\n :return: True if the types are compatible, False otherwise.\n \"\"\"\n if type_validation:\n return _strict_types_are_compatible(sender, receiver)\n else:\n return True"}, {"class_start_lineno": 38, "class_end_lineno": 242, "func_start_lineno": 216, "func_end_lineno": 229, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serializes the component to a dictionary.\n\n :returns:\n Dictionary with serialized data.\n \"\"\"\n serialized_tools = [tool.to_dict() for tool in self.tools]\n return default_to_dict(\n self,\n tools=serialized_tools,\n raise_on_failure=self.raise_on_failure,\n convert_result_to_json_string=self.convert_result_to_json_string,\n )"}, {"class_start_lineno": 32, "class_end_lineno": 571, "func_start_lineno": 170, "func_end_lineno": 190, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serialize this component to a dictionary.\n\n :returns:\n The serialized component as a dictionary.\n \"\"\"\n callback_name = serialize_callable(self.streaming_callback) if self.streaming_callback else None\n return default_to_dict(\n self,\n model=self.model,\n streaming_callback=callback_name,\n api_base_url=self.api_base_url,\n organization=self.organization,\n generation_kwargs=self.generation_kwargs,\n api_key=self.api_key.to_dict(),\n timeout=self.timeout,\n max_retries=self.max_retries,\n tools=[tool.to_dict() for tool in self.tools] if self.tools else None,\n tools_strict=self.tools_strict,\n )"}, {"class_start_lineno": 1, "class_end_lineno": 264, "func_start_lineno": 36, "func_end_lineno": 82, "func_code": "def component_to_dict(obj: Any, name: str) -> Dict[str, Any]:\n \"\"\"\n Converts a component instance into a dictionary.\n\n If a `to_dict` method is present in the component instance, that will be used instead of the default method.\n\n :param obj:\n The component to be serialized.\n :param name:\n The name of the component.\n :returns:\n A dictionary representation of the component.\n\n :raises SerializationError:\n If the component doesn't have a `to_dict` method.\n If the values of the init parameters can't be determined.\n If a non-basic Python type is used in the serialized data.\n \"\"\"\n if hasattr(obj, \"to_dict\"):\n data = obj.to_dict()\n else:\n init_parameters = {}\n for param_name, param in inspect.signature(obj.__init__).parameters.items():\n # Ignore `args` and `kwargs`, used by the default constructor\n if param_name in (\"args\", \"kwargs\"):\n continue\n try:\n # This only works if the Component constructor assigns the init\n # parameter to an instance variable or property with the same name\n param_value = getattr(obj, param_name)\n except AttributeError as e:\n # If the parameter doesn't have a default value, raise an error\n if param.default is param.empty:\n raise SerializationError(\n f\"Cannot determine the value of the init parameter '{param_name}' \"\n f\"for the class {obj.__class__.__name__}.\"\n f\"You can fix this error by assigning 'self.{param_name} = {param_name}' or adding a \"\n f\"custom serialization method 'to_dict' to the class.\"\n ) from e\n # In case the init parameter was not assigned, we use the default value\n param_value = param.default\n init_parameters[param_name] = param_value\n\n data = default_to_dict(obj, **init_parameters)\n\n _validate_component_to_dict_output(obj, name, data)\n return data"}], "type": ["function_empty", "Development"], "node": ["haystack.core.type_utils._strict_types_are_compatible", "haystack.core.type_utils._types_are_compatible", "haystack.components.tools.tool_invoker.ToolInvoker.to_dict", "haystack.components.generators.chat.openai.OpenAIChatGenerator.to_dict", "haystack.core.serialization.component_to_dict"], "language": "Python", "toolfunc_count": 4, "func_count": 5, "pytest_info": {"total_num": 16, "base_passed_num": 13}} {"id": ["haystack.haystack.document_stores.in_memory.document_store.InMemoryDocumentStore::write_documents", "haystack.haystack.components.writers.document_writer.DocumentWriter::run"], "project": "haystack", "origin_file": ["haystack/document_stores/in_memory/document_store.py", "haystack/components/writers/document_writer.py"], "test_list": ["test/components/writers/test_document_writer.py"], "prob_info": [{"class_start_lineno": 58, "class_end_lineno": 738, "func_start_lineno": 432, "func_end_lineno": 473, "func_code": " def write_documents(self, documents: List[Document], policy: DuplicatePolicy = DuplicatePolicy.NONE) -> int:\n \"\"\"\n Refer to the DocumentStore.write_documents() protocol documentation.\n\n If `policy` is set to `DuplicatePolicy.NONE` defaults to `DuplicatePolicy.FAIL`.\n \"\"\"\n if (\n not isinstance(documents, Iterable)\n or isinstance(documents, str)\n or any(not isinstance(doc, Document) for doc in documents)\n ):\n raise ValueError(\"Please provide a list of Documents.\")\n\n if policy == DuplicatePolicy.NONE:\n policy = DuplicatePolicy.FAIL\n\n written_documents = len(documents)\n for document in documents:\n if policy != DuplicatePolicy.OVERWRITE and document.id in self.storage.keys():\n if policy == DuplicatePolicy.FAIL:\n raise DuplicateDocumentError(f\"ID '{document.id}' already exists.\")\n if policy == DuplicatePolicy.SKIP:\n logger.warning(\"ID '{document_id}' already exists\", document_id=document.id)\n written_documents -= 1\n continue\n\n # Since the statistics are updated in an incremental manner,\n # we need to explicitly remove the existing document to revert\n # the statistics before updating them with the new document.\n if document.id in self.storage.keys():\n self.delete_documents([document.id])\n\n tokens = []\n if document.content is not None:\n tokens = self._tokenize_bm25(document.content)\n\n self.storage[document.id] = document\n\n self._bm25_attr[document.id] = BM25DocumentStats(Counter(tokens), len(tokens))\n self._freq_vocab_for_idf.update(set(tokens))\n self._avg_doc_len = (len(tokens) + self._avg_doc_len * len(self._bm25_attr)) / (len(self._bm25_attr) + 1)\n return written_documents"}, {"class_start_lineno": 15, "class_end_lineno": 134, "func_start_lineno": 85, "func_end_lineno": 103, "func_code": " def run(self, documents: List[Document], policy: Optional[DuplicatePolicy] = None):\n \"\"\"\n Run the DocumentWriter on the given input data.\n\n :param documents:\n A list of documents to write to the document store.\n :param policy:\n The policy to use when encountering duplicate documents.\n :returns:\n Number of documents written to the document store.\n\n :raises ValueError:\n If the specified document store is not found.\n \"\"\"\n if policy is None:\n policy = self.policy\n\n documents_written = self.document_store.write_documents(documents=documents, policy=policy)\n return {\"documents_written\": documents_written}"}], "type": ["function_empty"], "node": ["haystack.document_stores.in_memory.document_store.InMemoryDocumentStore.write_documents", "haystack.components.writers.document_writer.DocumentWriter.run"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 11, "base_passed_num": 7}} {"id": ["haystack.haystack.evaluation.eval_run_result.EvaluationRunResult::detailed_report", "haystack.haystack.evaluation.eval_run_result.EvaluationRunResult::comparative_detailed_report"], "project": "haystack", "origin_file": ["haystack/evaluation/eval_run_result.py", "haystack/evaluation/eval_run_result.py"], "test_list": ["test/evaluation/test_eval_run_result.py"], "prob_info": [{"class_start_lineno": 16, "class_end_lineno": 222, "func_start_lineno": 138, "func_end_lineno": 162, "func_code": " def detailed_report(\n self, output_format: Literal[\"json\", \"csv\", \"df\"] = \"json\", csv_file: Optional[str] = None\n ) -> Union[Dict[str, List[Any]], \"DataFrame\", str]:\n \"\"\"\n Generates a report with detailed scores for each metric.\n\n :param output_format: The output format for the report, \"json\", \"csv\", or \"df\", default to \"json\".\n :param csv_file: Filepath to save CSV output if `output_format` is \"csv\", must be provided.\n\n :returns:\n JSON or DataFrame with the detailed scores, in case the output is set to a CSV file, a message confirming\n the successful write or an error message.\n \"\"\"\n\n combined_data = {col: self.inputs[col] for col in self.inputs}\n\n # enforce columns type consistency\n scores_columns = list(self.results.keys())\n for col in scores_columns:\n col_values = self.results[col][\"individual_scores\"]\n if any(isinstance(v, float) for v in col_values):\n col_values = [float(v) for v in col_values]\n combined_data[col] = col_values\n\n return self._handle_output(combined_data, output_format, csv_file)"}, {"class_start_lineno": 16, "class_end_lineno": 222, "func_start_lineno": 164, "func_end_lineno": 222, "func_code": " def comparative_detailed_report(\n self,\n other: \"EvaluationRunResult\",\n keep_columns: Optional[List[str]] = None,\n output_format: Literal[\"json\", \"csv\", \"df\"] = \"json\",\n csv_file: Optional[str] = None,\n ) -> Union[str, \"DataFrame\", None]:\n \"\"\"\n Generates a report with detailed scores for each metric from two evaluation runs for comparison.\n\n :param other: Results of another evaluation run to compare with.\n :param keep_columns: List of common column names to keep from the inputs of the evaluation runs to compare.\n :param output_format: The output format for the report, \"json\", \"csv\", or \"df\", default to \"json\".\n :param csv_file: Filepath to save CSV output if `output_format` is \"csv\", must be provided.\n\n :returns:\n JSON or DataFrame with a comparison of the detailed scores, in case the output is set to a CSV file,\n a message confirming the successful write or an error message.\n \"\"\"\n\n if not isinstance(other, EvaluationRunResult):\n raise ValueError(\"Comparative scores can only be computed between EvaluationRunResults.\")\n\n if not hasattr(other, \"run_name\") or not hasattr(other, \"inputs\") or not hasattr(other, \"results\"):\n raise ValueError(\"The 'other' parameter must have 'run_name', 'inputs', and 'results' attributes.\")\n\n if self.run_name == other.run_name:\n warn(f\"The run names of the two evaluation results are the same ('{self.run_name}')\")\n\n if self.inputs.keys() != other.inputs.keys():\n warn(f\"The input columns differ between the results; using the input columns of '{self.run_name}'.\")\n\n # got both detailed reports\n detailed_a = self.detailed_report(output_format=\"json\")\n detailed_b = other.detailed_report(output_format=\"json\")\n\n # ensure both detailed reports are in dictionaries format\n if not isinstance(detailed_a, dict) or not isinstance(detailed_b, dict):\n raise ValueError(\"Detailed reports must be dictionaries.\")\n\n # determine which columns to ignore\n if keep_columns is None:\n ignore = list(self.inputs.keys())\n else:\n ignore = [col for col in list(self.inputs.keys()) if col not in keep_columns]\n\n # filter out ignored columns from pipe_b_dict\n filtered_detailed_b = {\n f\"{other.run_name}_{key}\": value for key, value in detailed_b.items() if key not in ignore\n }\n\n # rename columns in pipe_a_dict based on ignore list\n renamed_detailed_a = {\n (key if key in ignore else f\"{self.run_name}_{key}\"): value for key, value in detailed_a.items()\n }\n\n # combine both detailed reports\n combined_results = {**renamed_detailed_a, **filtered_detailed_b}\n return self._handle_output(combined_results, output_format, csv_file)"}], "type": ["function_empty", "Development"], "node": ["haystack.evaluation.eval_run_result.EvaluationRunResult.detailed_report", "haystack.evaluation.eval_run_result.EvaluationRunResult.comparative_detailed_report"], "language": "Python", "toolfunc_count": 1, "func_count": 2, "pytest_info": {"total_num": 4, "base_passed_num": 2}} {"id": ["haystack.haystack.core.type_utils._strict_types_are_compatible", "haystack.haystack.core.type_utils._types_are_compatible", "haystack.haystack.components.websearch.serper_dev.SerperDevWebSearch::to_dict", "haystack.haystack.components.tools.tool_invoker.ToolInvoker::to_dict", "haystack.haystack.core.serialization.component_to_dict"], "project": "haystack", "origin_file": ["haystack/core/type_utils.py", "haystack/core/type_utils.py", "haystack/components/websearch/serper_dev.py", "haystack/components/tools/tool_invoker.py", "haystack/core/serialization.py"], "test_list": ["test/tools/test_component_tool.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 105, "func_start_lineno": 29, "func_end_lineno": 76, "func_code": "def _strict_types_are_compatible(sender, receiver): # pylint: disable=too-many-return-statements\n \"\"\"\n Checks whether the sender type is equal to or a subtype of the receiver type under strict validation.\n\n Note: this method has no pretense to perform proper type matching. It especially does not deal with aliasing of\n typing classes such as `List` or `Dict` to their runtime counterparts `list` and `dict`. It also does not deal well\n with \"bare\" types, so `List` is treated differently from `List[Any]`, even though they should be the same.\n Consider simplifying the typing of your components if you observe unexpected errors during component connection.\n\n :param sender: The sender type.\n :param receiver: The receiver type.\n :return: True if the sender type is strictly compatible with the receiver type, False otherwise.\n \"\"\"\n if sender == receiver or receiver is Any:\n return True\n\n if sender is Any:\n return False\n\n try:\n if issubclass(sender, receiver):\n return True\n except TypeError: # typing classes can't be used with issubclass, so we deal with them below\n pass\n\n sender_origin = get_origin(sender)\n receiver_origin = get_origin(receiver)\n\n if sender_origin is not Union and receiver_origin is Union:\n return any(_strict_types_are_compatible(sender, union_arg) for union_arg in get_args(receiver))\n\n # Both must have origins and they must be equal\n if not (sender_origin and receiver_origin and sender_origin == receiver_origin):\n return False\n\n # Compare generic type arguments\n sender_args = get_args(sender)\n receiver_args = get_args(receiver)\n\n # Handle bare types\n if not sender_args and sender_origin:\n sender_args = (Any,)\n if not receiver_args and receiver_origin:\n receiver_args = (Any,) * (len(sender_args) if sender_args else 1)\n if len(sender_args) > len(receiver_args):\n return False\n\n return all(_strict_types_are_compatible(*args) for args in zip(sender_args, receiver_args))"}, {"class_start_lineno": 1, "class_end_lineno": 105, "func_start_lineno": 14, "func_end_lineno": 26, "func_code": "def _types_are_compatible(sender, receiver, type_validation: bool = True) -> bool:\n \"\"\"\n Determines if two types are compatible based on the specified validation mode.\n\n :param sender: The sender type.\n :param receiver: The receiver type.\n :param type_validation: Whether to perform strict type validation.\n :return: True if the types are compatible, False otherwise.\n \"\"\"\n if type_validation:\n return _strict_types_are_compatible(sender, receiver)\n else:\n return True"}, {"class_start_lineno": 23, "class_end_lineno": 175, "func_start_lineno": 67, "func_end_lineno": 80, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serializes the component to a dictionary.\n\n :returns:\n Dictionary with serialized data.\n \"\"\"\n return default_to_dict(\n self,\n top_k=self.top_k,\n allowed_domains=self.allowed_domains,\n search_params=self.search_params,\n api_key=self.api_key.to_dict(),\n )"}, {"class_start_lineno": 38, "class_end_lineno": 242, "func_start_lineno": 216, "func_end_lineno": 229, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serializes the component to a dictionary.\n\n :returns:\n Dictionary with serialized data.\n \"\"\"\n serialized_tools = [tool.to_dict() for tool in self.tools]\n return default_to_dict(\n self,\n tools=serialized_tools,\n raise_on_failure=self.raise_on_failure,\n convert_result_to_json_string=self.convert_result_to_json_string,\n )"}, {"class_start_lineno": 1, "class_end_lineno": 264, "func_start_lineno": 36, "func_end_lineno": 82, "func_code": "def component_to_dict(obj: Any, name: str) -> Dict[str, Any]:\n \"\"\"\n Converts a component instance into a dictionary.\n\n If a `to_dict` method is present in the component instance, that will be used instead of the default method.\n\n :param obj:\n The component to be serialized.\n :param name:\n The name of the component.\n :returns:\n A dictionary representation of the component.\n\n :raises SerializationError:\n If the component doesn't have a `to_dict` method.\n If the values of the init parameters can't be determined.\n If a non-basic Python type is used in the serialized data.\n \"\"\"\n if hasattr(obj, \"to_dict\"):\n data = obj.to_dict()\n else:\n init_parameters = {}\n for param_name, param in inspect.signature(obj.__init__).parameters.items():\n # Ignore `args` and `kwargs`, used by the default constructor\n if param_name in (\"args\", \"kwargs\"):\n continue\n try:\n # This only works if the Component constructor assigns the init\n # parameter to an instance variable or property with the same name\n param_value = getattr(obj, param_name)\n except AttributeError as e:\n # If the parameter doesn't have a default value, raise an error\n if param.default is param.empty:\n raise SerializationError(\n f\"Cannot determine the value of the init parameter '{param_name}' \"\n f\"for the class {obj.__class__.__name__}.\"\n f\"You can fix this error by assigning 'self.{param_name} = {param_name}' or adding a \"\n f\"custom serialization method 'to_dict' to the class.\"\n ) from e\n # In case the init parameter was not assigned, we use the default value\n param_value = param.default\n init_parameters[param_name] = param_value\n\n data = default_to_dict(obj, **init_parameters)\n\n _validate_component_to_dict_output(obj, name, data)\n return data"}], "type": ["function_empty", "Development"], "node": ["haystack.core.type_utils._strict_types_are_compatible", "haystack.core.type_utils._types_are_compatible", "haystack.components.websearch.serper_dev.SerperDevWebSearch.to_dict", "haystack.components.tools.tool_invoker.ToolInvoker.to_dict", "haystack.core.serialization.component_to_dict"], "language": "Python", "toolfunc_count": 4, "func_count": 5, "pytest_info": {"total_num": 10, "base_passed_num": 8}} {"id": ["haystack.haystack.tools.from_function.create_tool_from_function", "haystack.haystack.tools.from_function.tool"], "project": "haystack", "origin_file": ["haystack/tools/from_function.py", "haystack/tools/from_function.py"], "test_list": ["test/tools/test_from_function.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 166, "func_start_lineno": 14, "func_end_lineno": 112, "func_code": "def create_tool_from_function(\n function: Callable, name: Optional[str] = None, description: Optional[str] = None\n) -> \"Tool\":\n \"\"\"\n Create a Tool instance from a function.\n\n Allows customizing the Tool name and description.\n For simpler use cases, consider using the `@tool` decorator.\n\n ### Usage example\n\n ```python\n from typing import Annotated, Literal\n from haystack.tools import create_tool_from_function\n\n def get_weather(\n city: Annotated[str, \"the city for which to get the weather\"] = \"Munich\",\n unit: Annotated[Literal[\"Celsius\", \"Fahrenheit\"], \"the unit for the temperature\"] = \"Celsius\"):\n '''A simple function to get the current weather for a location.'''\n return f\"Weather report for {city}: 20 {unit}, sunny\"\n\n tool = create_tool_from_function(get_weather)\n\n print(tool)\n >>> Tool(name='get_weather', description='A simple function to get the current weather for a location.',\n >>> parameters={\n >>> 'type': 'object',\n >>> 'properties': {\n >>> 'city': {'type': 'string', 'description': 'the city for which to get the weather', 'default': 'Munich'},\n >>> 'unit': {\n >>> 'type': 'string',\n >>> 'enum': ['Celsius', 'Fahrenheit'],\n >>> 'description': 'the unit for the temperature',\n >>> 'default': 'Celsius',\n >>> },\n >>> }\n >>> },\n >>> function=)\n ```\n\n :param function:\n The function to be converted into a Tool.\n The function must include type hints for all parameters.\n The function is expected to have basic python input types (str, int, float, bool, list, dict, tuple).\n Other input types may work but are not guaranteed.\n If a parameter is annotated using `typing.Annotated`, its metadata will be used as parameter description.\n :param name:\n The name of the Tool. If not provided, the name of the function will be used.\n :param description:\n The description of the Tool. If not provided, the docstring of the function will be used.\n To intentionally leave the description empty, pass an empty string.\n\n :returns:\n The Tool created from the function.\n\n :raises ValueError:\n If any parameter of the function lacks a type hint.\n :raises SchemaGenerationError:\n If there is an error generating the JSON schema for the Tool.\n \"\"\"\n\n tool_description = description if description is not None else (function.__doc__ or \"\")\n\n signature = inspect.signature(function)\n\n # collect fields (types and defaults) and descriptions from function parameters\n fields: Dict[str, Any] = {}\n descriptions = {}\n\n for param_name, param in signature.parameters.items():\n if param.annotation is param.empty:\n raise ValueError(f\"Function '{function.__name__}': parameter '{param_name}' does not have a type hint.\")\n\n # if the parameter has not a default value, Pydantic requires an Ellipsis (...)\n # to explicitly indicate that the parameter is required\n default = param.default if param.default is not param.empty else ...\n fields[param_name] = (param.annotation, default)\n\n if hasattr(param.annotation, \"__metadata__\"):\n descriptions[param_name] = param.annotation.__metadata__[0]\n\n # create Pydantic model and generate JSON schema\n try:\n model = create_model(function.__name__, **fields)\n schema = model.model_json_schema()\n except Exception as e:\n raise SchemaGenerationError(f\"Failed to create JSON schema for function '{function.__name__}'\") from e\n\n # we don't want to include title keywords in the schema, as they contain redundant information\n # there is no programmatic way to prevent Pydantic from adding them, so we remove them later\n # see https://github.com/pydantic/pydantic/discussions/8504\n _remove_title_from_schema(schema)\n\n # add parameters descriptions to the schema\n for param_name, param_description in descriptions.items():\n if param_name in schema[\"properties\"]:\n schema[\"properties\"][param_name][\"description\"] = param_description\n\n return Tool(name=name or function.__name__, description=tool_description, parameters=schema, function=function)"}, {"class_start_lineno": 1, "class_end_lineno": 166, "func_start_lineno": 115, "func_end_lineno": 151, "func_code": "def tool(function: Callable) -> Tool:\n \"\"\"\n Decorator to convert a function into a Tool.\n\n Tool name, description, and parameters are inferred from the function.\n If you need to customize more the Tool, use `create_tool_from_function` instead.\n\n ### Usage example\n ```python\n from typing import Annotated, Literal\n from haystack.tools import tool\n\n @tool\n def get_weather(\n city: Annotated[str, \"the city for which to get the weather\"] = \"Munich\",\n unit: Annotated[Literal[\"Celsius\", \"Fahrenheit\"], \"the unit for the temperature\"] = \"Celsius\"):\n '''A simple function to get the current weather for a location.'''\n return f\"Weather report for {city}: 20 {unit}, sunny\"\n\n print(get_weather)\n >>> Tool(name='get_weather', description='A simple function to get the current weather for a location.',\n >>> parameters={\n >>> 'type': 'object',\n >>> 'properties': {\n >>> 'city': {'type': 'string', 'description': 'the city for which to get the weather', 'default': 'Munich'},\n >>> 'unit': {\n >>> 'type': 'string',\n >>> 'enum': ['Celsius', 'Fahrenheit'],\n >>> 'description': 'the unit for the temperature',\n >>> 'default': 'Celsius',\n >>> },\n >>> }\n >>> },\n >>> function=)\n ```\n \"\"\"\n return create_tool_from_function(function)"}], "type": ["function_empty", "Development"], "node": ["haystack.tools.from_function.create_tool_from_function", "haystack.tools.from_function.tool"], "language": "Python", "toolfunc_count": 1, "func_count": 2, "pytest_info": {"total_num": 12, "base_passed_num": 3}} {"id": ["haystack.haystack.core.serialization.import_class_by_name", "haystack.haystack.tools.tool.deserialize_tools_inplace"], "project": "haystack", "origin_file": ["haystack/core/serialization.py", "haystack/tools/tool.py"], "test_list": ["test/tools/test_tool.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 264, "func_start_lineno": 243, "func_end_lineno": 264, "func_code": "def import_class_by_name(fully_qualified_name: str) -> Type[object]:\n \"\"\"\n Utility function to import (load) a class object based on its fully qualified class name.\n\n This function dynamically imports a class based on its string name.\n It splits the name into module path and class name, imports the module,\n and returns the class object.\n\n :param fully_qualified_name: the fully qualified class name as a string\n :returns: the class object.\n :raises ImportError: If the class cannot be imported or found.\n \"\"\"\n try:\n module_path, class_name = fully_qualified_name.rsplit(\".\", 1)\n logger.debug(\n \"Attempting to import class '{cls_name}' from module '{md_path}'\", cls_name=class_name, md_path=module_path\n )\n module = thread_safe_import(module_path)\n return getattr(module, class_name)\n except (ImportError, AttributeError) as error:\n logger.error(\"Failed to import class '{full_name}'\", full_name=fully_qualified_name)\n raise ImportError(f\"Could not import class '{fully_qualified_name}'\") from error"}, {"class_start_lineno": 1, "class_end_lineno": 136, "func_start_lineno": 106, "func_end_lineno": 136, "func_code": "def deserialize_tools_inplace(data: Dict[str, Any], key: str = \"tools\"):\n \"\"\"\n Deserialize Tools in a dictionary inplace.\n\n :param data:\n The dictionary with the serialized data.\n :param key:\n The key in the dictionary where the Tools are stored.\n \"\"\"\n if key in data:\n serialized_tools = data[key]\n\n if serialized_tools is None:\n return\n\n if not isinstance(serialized_tools, list):\n raise TypeError(f\"The value of '{key}' is not a list\")\n\n deserialized_tools = []\n for tool in serialized_tools:\n if not isinstance(tool, dict):\n raise TypeError(f\"Serialized tool '{tool}' is not a dictionary\")\n\n # different classes are allowed: Tool, ComponentTool, etc.\n tool_class = import_class_by_name(tool[\"type\"])\n if not issubclass(tool_class, Tool):\n raise TypeError(f\"Class '{tool_class}' is not a subclass of Tool\")\n\n deserialized_tools.append(tool_class.from_dict(tool))\n\n data[key] = deserialized_tools"}], "type": ["Development"], "node": ["haystack.core.serialization.import_class_by_name", "haystack.tools.tool.deserialize_tools_inplace"], "language": "Python", "toolfunc_count": 0, "func_count": 2, "pytest_info": {"total_num": 10, "base_passed_num": 7}} {"id": ["haystack.haystack.dataclasses.document.Document::to_dict", "haystack.haystack.tracing.utils.coerce_tag_value"], "project": "haystack", "origin_file": ["haystack/dataclasses/document.py", "haystack/tracing/utils.py", "haystack/tracing/utils.py"], "test_list": ["test/tracing/test_utils.py"], "prob_info": [{"class_start_lineno": 49, "class_end_lineno": 186, "func_start_lineno": 123, "func_end_lineno": 140, "func_code": " def to_dict(self, flatten=True) -> Dict[str, Any]:\n \"\"\"\n Converts Document into a dictionary.\n\n `blob` field is converted to a JSON-serializable type.\n\n :param flatten:\n Whether to flatten `meta` field or not. Defaults to `True` to be backward-compatible with Haystack 1.x.\n \"\"\"\n data = asdict(self)\n if (blob := data.get(\"blob\")) is not None:\n data[\"blob\"] = {\"data\": list(blob[\"data\"]), \"mime_type\": blob[\"mime_type\"]}\n\n if flatten:\n meta = data.pop(\"meta\")\n return {**data, **meta}\n\n return data"}, {"class_start_lineno": 1, "class_end_lineno": 52, "func_start_lineno": 42, "func_end_lineno": 52, "func_code": "def _serializable_value(value: Any) -> Any:\n if isinstance(value, list):\n return [_serializable_value(v) for v in value]\n\n if isinstance(value, dict):\n return {k: _serializable_value(v) for k, v in value.items()}\n\n if getattr(value, \"to_dict\", None):\n return _serializable_value(value.to_dict())\n\n return value"}, {"class_start_lineno": 1, "class_end_lineno": 52, "func_start_lineno": 15, "func_end_lineno": 39, "func_code": "def coerce_tag_value(value: Any) -> Union[bool, str, int, float]:\n \"\"\"\n Coerces span tag values to compatible types for the tracing backend.\n\n Most tracing libraries don't support sending complex types to the backend. Hence, we need to convert them to\n compatible types.\n\n :param value: an arbitrary value which should be coerced to a compatible type\n :return: the value coerced to a compatible type\n \"\"\"\n if isinstance(value, PRIMITIVE_TYPES):\n return value\n\n if value is None:\n return \"\"\n\n try:\n # do that with-in try-except because who knows what kind of objects are being passed\n serializable = _serializable_value(value)\n return json.dumps(serializable)\n except Exception as error:\n logger.debug(\"Failed to coerce tag value to string: {error}\", error=error)\n\n # Our last resort is to convert the value to a string\n return str(value)"}], "type": ["function_empty", "Development"], "node": ["haystack.dataclasses.document.Document.to_dict", "haystack.tracing.utils._serializable_value", "haystack.tracing.utils.coerce_tag_value"], "language": "Python", "toolfunc_count": 1, "func_count": 2, "pytest_info": {"total_num": 11, "base_passed_num": 5}} {"id": ["haystack.haystack.core.serialization.import_class_by_name", "haystack.haystack.utils.base_serialization.deserialize_class_instance"], "project": "haystack", "origin_file": ["haystack/core/serialization.py", "haystack/utils/base_serialization.py"], "test_list": ["test/utils/test_base_serialization.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 264, "func_start_lineno": 243, "func_end_lineno": 264, "func_code": "def import_class_by_name(fully_qualified_name: str) -> Type[object]:\n \"\"\"\n Utility function to import (load) a class object based on its fully qualified class name.\n\n This function dynamically imports a class based on its string name.\n It splits the name into module path and class name, imports the module,\n and returns the class object.\n\n :param fully_qualified_name: the fully qualified class name as a string\n :returns: the class object.\n :raises ImportError: If the class cannot be imported or found.\n \"\"\"\n try:\n module_path, class_name = fully_qualified_name.rsplit(\".\", 1)\n logger.debug(\n \"Attempting to import class '{cls_name}' from module '{md_path}'\", cls_name=class_name, md_path=module_path\n )\n module = thread_safe_import(module_path)\n return getattr(module, class_name)\n except (ImportError, AttributeError) as error:\n logger.error(\"Failed to import class '{full_name}'\", full_name=fully_qualified_name)\n raise ImportError(f\"Could not import class '{fully_qualified_name}'\") from error"}, {"class_start_lineno": 1, "class_end_lineno": 54, "func_start_lineno": 29, "func_end_lineno": 54, "func_code": "def deserialize_class_instance(data: Dict[str, Any]) -> Any:\n \"\"\"\n Deserializes an object from a dictionary representation generated by `auto_serialize_class_instance`.\n\n :param data:\n The dictionary to deserialize from.\n :returns:\n The deserialized object.\n :raises DeserializationError:\n If the serialization data is malformed, the class type cannot be imported, or the\n class does not have a `from_dict` method.\n \"\"\"\n if \"type\" not in data:\n raise DeserializationError(\"Missing 'type' in serialization data\")\n if \"data\" not in data:\n raise DeserializationError(\"Missing 'data' in serialization data\")\n\n try:\n obj_class = import_class_by_name(data[\"type\"])\n except ImportError as e:\n raise DeserializationError(f\"Class '{data['type']}' not correctly imported\") from e\n\n if not hasattr(obj_class, \"from_dict\"):\n raise DeserializationError(f\"Class '{data['type']}' does not have a 'from_dict' method\")\n\n return obj_class.from_dict(data[\"data\"])"}], "type": ["Development"], "node": ["haystack.core.serialization.import_class_by_name", "haystack.utils.base_serialization.deserialize_class_instance"], "language": "Python", "toolfunc_count": 0, "func_count": 2, "pytest_info": {"total_num": 4, "base_passed_num": 2}} {"id": ["haystack.haystack.utils.type_serialization.thread_safe_import", "haystack.haystack.utils.callable_serialization.deserialize_callable"], "project": "haystack", "origin_file": ["haystack/utils/type_serialization.py", "haystack/utils/callable_serialization.py"], "test_list": ["test/utils/test_callable_serialization.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 170, "func_start_lineno": 159, "func_end_lineno": 170, "func_code": "def thread_safe_import(module_name: str) -> ModuleType:\n \"\"\"\n Import a module in a thread-safe manner.\n\n Importing modules in a multi-threaded environment can lead to race conditions.\n This function ensures that the module is imported in a thread-safe manner without having impact\n on the performance of the import for single-threaded environments.\n\n :param module_name: the module to import\n \"\"\"\n with _import_lock:\n return importlib.import_module(module_name)"}, {"class_start_lineno": 1, "class_end_lineno": 80, "func_start_lineno": 45, "func_end_lineno": 80, "func_code": "def deserialize_callable(callable_handle: str) -> Callable:\n \"\"\"\n Deserializes a callable given its full import path as a string.\n\n :param callable_handle: The full path of the callable_handle\n :return: The callable\n :raises DeserializationError: If the callable cannot be found\n \"\"\"\n parts = callable_handle.split(\".\")\n\n for i in range(len(parts), 0, -1):\n module_name = \".\".join(parts[:i])\n try:\n mod: Any = thread_safe_import(module_name)\n except Exception:\n # keep reducing i until we find a valid module import\n continue\n\n attr_value = mod\n for part in parts[i:]:\n try:\n attr_value = getattr(attr_value, part)\n except AttributeError as e:\n raise DeserializationError(f\"Could not find attribute '{part}' in {attr_value.__name__}\") from e\n\n # when the attribute is a classmethod, we need the underlying function\n if isinstance(attr_value, (classmethod, staticmethod)):\n attr_value = attr_value.__func__\n\n if not callable(attr_value):\n raise DeserializationError(f\"The final attribute is not callable: {attr_value}\")\n\n return attr_value\n\n # Fallback if we never find anything\n raise DeserializationError(f\"Could not import '{callable_handle}' as a module or callable.\")"}], "type": ["function_empty", "Development"], "node": ["haystack.utils.type_serialization.thread_safe_import", "haystack.utils.callable_serialization.deserialize_callable"], "language": "Python", "toolfunc_count": 1, "func_count": 2, "pytest_info": {"total_num": 11, "base_passed_num": 5}} {"id": ["haystack.haystack.utils.device.ComponentDevice::to_hf", "haystack.haystack.utils.device.ComponentDevice::update_hf_kwargs"], "project": "haystack", "origin_file": ["haystack/utils/device.py", "haystack/utils/device.py"], "test_list": ["test/utils/test_device.py"], "prob_info": [{"class_start_lineno": 240, "class_end_lineno": 480, "func_start_lineno": 359, "func_end_lineno": 379, "func_code": " def to_hf(self) -> Union[Union[int, str], Dict[str, Union[int, str]]]:\n \"\"\"\n Convert the component device representation to HuggingFace format.\n\n :returns:\n The HuggingFace device representation.\n \"\"\"\n self._validate()\n\n def convert_device(device: Device, *, gpu_id_only: bool = False) -> Union[int, str]:\n if gpu_id_only and device.type == DeviceType.GPU:\n assert device.id is not None\n return device.id\n else:\n return str(device)\n\n if self._single_device is not None:\n return convert_device(self._single_device)\n\n assert self._multiple_devices is not None\n return {key: convert_device(device, gpu_id_only=True) for key, device in self._multiple_devices.mapping.items()}"}, {"class_start_lineno": 240, "class_end_lineno": 480, "func_start_lineno": 381, "func_end_lineno": 402, "func_code": " def update_hf_kwargs(self, hf_kwargs: Dict[str, Any], *, overwrite: bool) -> Dict[str, Any]:\n \"\"\"\n Convert the component device representation to HuggingFace format.\n\n Add them as canonical keyword arguments to the keyword arguments dictionary.\n\n :param hf_kwargs:\n The HuggingFace keyword arguments dictionary.\n :param overwrite:\n Whether to overwrite existing device arguments.\n :returns:\n The HuggingFace keyword arguments dictionary.\n \"\"\"\n self._validate()\n\n if not overwrite and any(x in hf_kwargs for x in (\"device\", \"device_map\")):\n return hf_kwargs\n\n converted = self.to_hf()\n key = \"device_map\" if self.has_multiple_devices else \"device\"\n hf_kwargs[key] = converted\n return hf_kwargs"}], "type": ["function_empty"], "node": ["haystack.utils.device.ComponentDevice.to_hf", "haystack.utils.device.ComponentDevice.update_hf_kwargs"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 7, "base_passed_num": 4}} {"id": ["haystack.haystack.core.serialization.import_class_by_name", "haystack.haystack.utils.docstore_deserialization.deserialize_document_store_in_init_params_inplace"], "project": "haystack", "origin_file": ["haystack/core/serialization.py", "haystack/utils/docstore_deserialization.py"], "test_list": ["test/utils/test_docstore_deserialization.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 264, "func_start_lineno": 243, "func_end_lineno": 264, "func_code": "def import_class_by_name(fully_qualified_name: str) -> Type[object]:\n \"\"\"\n Utility function to import (load) a class object based on its fully qualified class name.\n\n This function dynamically imports a class based on its string name.\n It splits the name into module path and class name, imports the module,\n and returns the class object.\n\n :param fully_qualified_name: the fully qualified class name as a string\n :returns: the class object.\n :raises ImportError: If the class cannot be imported or found.\n \"\"\"\n try:\n module_path, class_name = fully_qualified_name.rsplit(\".\", 1)\n logger.debug(\n \"Attempting to import class '{cls_name}' from module '{md_path}'\", cls_name=class_name, md_path=module_path\n )\n module = thread_safe_import(module_path)\n return getattr(module, class_name)\n except (ImportError, AttributeError) as error:\n logger.error(\"Failed to import class '{full_name}'\", full_name=fully_qualified_name)\n raise ImportError(f\"Could not import class '{fully_qualified_name}'\") from error"}, {"class_start_lineno": 1, "class_end_lineno": 39, "func_start_lineno": 11, "func_end_lineno": 39, "func_code": "def deserialize_document_store_in_init_params_inplace(data: Dict[str, Any], key: str = \"document_store\"):\n \"\"\"\n Deserializes a generic document store from the init_parameters of a serialized component in place.\n\n :param data:\n The dictionary to deserialize from.\n :param key:\n The key in the `data[\"init_parameters\"]` dictionary where the document store is specified.\n :returns:\n The dictionary, with the document store deserialized.\n\n :raises DeserializationError:\n If the document store is not properly specified in the serialization data or its type cannot be imported.\n \"\"\"\n init_params = data.get(\"init_parameters\", {})\n if key not in init_params:\n raise DeserializationError(f\"Missing '{key}' in serialization data\")\n if \"type\" not in init_params[key]:\n raise DeserializationError(f\"Missing 'type' in {key} serialization data\")\n\n doc_store_data = data[\"init_parameters\"][key]\n try:\n doc_store_class = import_class_by_name(doc_store_data[\"type\"])\n except ImportError as e:\n raise DeserializationError(f\"Class '{doc_store_data['type']}' not correctly imported\") from e\n if hasattr(doc_store_class, \"from_dict\"):\n data[\"init_parameters\"][key] = doc_store_class.from_dict(doc_store_data)\n else:\n data[\"init_parameters\"][key] = default_from_dict(doc_store_class, doc_store_data)"}], "type": ["Development"], "node": ["haystack.core.serialization.import_class_by_name", "haystack.utils.docstore_deserialization.deserialize_document_store_in_init_params_inplace"], "language": "Python", "toolfunc_count": 0, "func_count": 2, "pytest_info": {"total_num": 6, "base_passed_num": 0}} {"id": ["inference.inference.core.utils.image_utils.validate_numpy_image", "inference.inference.core.utils.image_utils.load_image_with_inferred_type"], "project": "inference", "origin_file": ["inference/core/utils/image_utils.py", "inference/core/utils/image_utils.py"], "test_list": ["tests/inference/unit_tests/core/active_learning/test_middlewares.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 599, "func_start_lineno": 353, "func_end_lineno": 377, "func_code": "def validate_numpy_image(data: np.ndarray) -> None:\n \"\"\"\n Validate if the provided data is a valid numpy image.\n\n Args:\n data (np.ndarray): The numpy array representing an image.\n\n Raises:\n InvalidNumpyInput: If the provided data is not a valid numpy image.\n \"\"\"\n if not issubclass(type(data), np.ndarray):\n raise InvalidNumpyInput(\n message=f\"Data provided as input could not be decoded into np.ndarray object.\",\n public_message=f\"Data provided as input could not be decoded into np.ndarray object.\",\n )\n if len(data.shape) != 3 and len(data.shape) != 2:\n raise InvalidNumpyInput(\n message=f\"For image given as np.ndarray expected 2 or 3 dimensions, got {len(data.shape)} dimensions.\",\n public_message=f\"For image given as np.ndarray expected 2 or 3 dimensions.\",\n )\n if data.shape[-1] != 3 and data.shape[-1] != 1:\n raise InvalidNumpyInput(\n message=f\"For image given as np.ndarray expected 1 or 3 channels, got {data.shape[-1]} channels.\",\n public_message=\"For image given as np.ndarray expected 1 or 3 channels.\",\n )"}, {"class_start_lineno": 1, "class_end_lineno": 599, "func_start_lineno": 180, "func_end_lineno": 212, "func_code": "def load_image_with_inferred_type(\n value: Any,\n cv_imread_flags: int = cv2.IMREAD_COLOR,\n) -> Tuple[np.ndarray, bool]:\n \"\"\"Load an image by inferring its type.\n\n Args:\n value (Any): The image data.\n cv_imread_flags (int): Flags used for OpenCV's imread function.\n\n Returns:\n Tuple[np.ndarray, bool]: Loaded image as a numpy array and a boolean indicating if the image is in BGR format.\n\n Raises:\n NotImplementedError: If the image type could not be inferred.\n \"\"\"\n if isinstance(value, (np.ndarray, np.generic)):\n validate_numpy_image(data=value)\n return value, True\n elif isinstance(value, Image.Image):\n return np.asarray(value.convert(\"RGB\")), False\n elif isinstance(value, str) and (value.startswith(\"http\")):\n return load_image_from_url(value=value, cv_imread_flags=cv_imread_flags), True\n elif (\n isinstance(value, str)\n and ALLOW_LOADING_IMAGES_FROM_LOCAL_FILESYSTEM\n and os.path.isfile(value)\n ):\n return cv2.imread(value, cv_imread_flags), True\n else:\n return attempt_loading_image_from_string(\n value=value, cv_imread_flags=cv_imread_flags\n )"}], "type": ["function_empty"], "node": ["inference.core.utils.image_utils.validate_numpy_image", "inference.core.utils.image_utils.load_image_with_inferred_type"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 7, "base_passed_num": 4}} {"id": ["inference.inference.core.active_learning.samplers.close_to_threshold.count_detections_close_to_threshold", "inference.inference.core.active_learning.samplers.close_to_threshold.prediction_is_close_to_threshold"], "project": "inference", "origin_file": ["inference/core/active_learning/samplers/close_to_threshold.py", "inference/core/active_learning/samplers/close_to_threshold.py", "inference/core/active_learning/samplers/close_to_threshold.py"], "test_list": ["tests/inference/unit_tests/core/active_learning/samplers/test_close_to_threshold.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 227, "func_start_lineno": 200, "func_end_lineno": 217, "func_code": "def count_detections_close_to_threshold(\n prediction: Prediction,\n selected_class_names: Optional[Set[str]],\n threshold: float,\n epsilon: float,\n) -> int:\n counter = 0\n for prediction_details in prediction[\"predictions\"]:\n if class_to_be_excluded(\n class_name=prediction_details[\"class\"],\n selected_class_names=selected_class_names,\n ):\n continue\n if is_close_to_threshold(\n value=prediction_details[\"confidence\"], threshold=threshold, epsilon=epsilon\n ):\n counter += 1\n return counter"}, {"class_start_lineno": 1, "class_end_lineno": 227, "func_start_lineno": 184, "func_end_lineno": 197, "func_code": "def detections_are_close_to_threshold(\n prediction: Prediction,\n selected_class_names: Optional[Set[str]],\n threshold: float,\n epsilon: float,\n minimum_objects_close_to_threshold: int,\n) -> bool:\n detections_close_to_threshold = count_detections_close_to_threshold(\n prediction=prediction,\n selected_class_names=selected_class_names,\n threshold=threshold,\n epsilon=epsilon,\n )\n return detections_close_to_threshold >= minimum_objects_close_to_threshold"}, {"class_start_lineno": 1, "class_end_lineno": 227, "func_start_lineno": 90, "func_end_lineno": 116, "func_code": "def prediction_is_close_to_threshold(\n prediction: Prediction,\n prediction_type: PredictionType,\n selected_class_names: Optional[Set[str]],\n threshold: float,\n epsilon: float,\n only_top_classes: bool,\n minimum_objects_close_to_threshold: int,\n) -> bool:\n if CLASSIFICATION_TASK not in prediction_type:\n return detections_are_close_to_threshold(\n prediction=prediction,\n selected_class_names=selected_class_names,\n threshold=threshold,\n epsilon=epsilon,\n minimum_objects_close_to_threshold=minimum_objects_close_to_threshold,\n )\n checker = multi_label_classification_prediction_is_close_to_threshold\n if \"top\" in prediction:\n checker = multi_class_classification_prediction_is_close_to_threshold\n return checker(\n prediction=prediction,\n selected_class_names=selected_class_names,\n threshold=threshold,\n epsilon=epsilon,\n only_top_classes=only_top_classes,\n )"}], "type": ["Development"], "node": ["inference.core.active_learning.samplers.close_to_threshold.count_detections_close_to_threshold", "inference.core.active_learning.samplers.close_to_threshold.detections_are_close_to_threshold", "inference.core.active_learning.samplers.close_to_threshold.prediction_is_close_to_threshold"], "language": "Python", "toolfunc_count": 0, "func_count": 2, "pytest_info": {"total_num": 52, "base_passed_num": 36}} {"id": ["inference.inference.core.interfaces.camera.video_source.VideoSource::read_frame", "inference.inference.core.interfaces.camera.video_source.VideoSource::__next__", "inference.inference.core.interfaces.camera.utils.get_video_frames_generator"], "project": "inference", "origin_file": ["inference/core/interfaces/camera/video_source.py", "inference/core/interfaces/camera/video_source.py", "inference/core/interfaces/camera/utils.py", "inference/core/interfaces/camera/utils.py"], "test_list": ["tests/inference/unit_tests/core/interfaces/camera/test_utils.py"], "prob_info": [{"class_start_lineno": 181, "class_end_lineno": 738, "func_start_lineno": 526, "func_end_lineno": 555, "func_code": " def read_frame(self, timeout: Optional[float] = None) -> Optional[VideoFrame]:\n \"\"\"\n Method to be used by the consumer to get decoded source frame.\n\n Returns: VideoFrame object with decoded frame and its metadata.\n Throws:\n * EndOfStreamError: when trying to get the frame from closed source.\n \"\"\"\n video_frame: Optional[Union[VideoFrame, str]] = get_from_queue(\n queue=self._frames_buffer,\n on_successful_read=self._video_consumer.notify_frame_consumed,\n timeout=timeout,\n purge=self._buffer_consumption_strategy is BufferConsumptionStrategy.EAGER,\n )\n if video_frame == POISON_PILL:\n raise EndOfStreamError(\n \"Attempted to retrieve frame from stream that already ended.\"\n )\n if video_frame is not None:\n send_video_source_status_update(\n severity=UpdateSeverity.DEBUG,\n event_type=FRAME_CONSUMED_EVENT,\n payload={\n \"frame_timestamp\": video_frame.frame_timestamp,\n \"frame_id\": video_frame.frame_id,\n \"source_id\": video_frame.source_id,\n },\n status_update_handlers=self._status_update_handlers,\n )\n return video_frame"}, {"class_start_lineno": 181, "class_end_lineno": 738, "func_start_lineno": 720, "func_end_lineno": 738, "func_code": " def __next__(self) -> VideoFrame:\n \"\"\"\n Method allowing to use `VideoSource` convenient to read frames\n\n Returns: VideoFrame\n\n Example:\n ```python\n source = VideoSource.init(video_reference=\"./some.mp4\")\n source.start()\n\n for frame in source:\n pass\n ```\n \"\"\"\n try:\n return self.read_frame()\n except EndOfStreamError:\n raise StopIteration()"}, {"class_start_lineno": 1, "class_end_lineno": 516, "func_start_lineno": 479, "func_end_lineno": 494, "func_code": "def limit_frame_rate(\n frames_generator: Iterable[T],\n max_fps: Union[float, int],\n strategy: FPSLimiterStrategy,\n) -> Generator[T, None, None]:\n rate_limiter = RateLimiter(desired_fps=max_fps)\n for frame_data in frames_generator:\n delay = rate_limiter.estimate_next_action_delay()\n if delay <= 0.0:\n rate_limiter.tick()\n yield frame_data\n continue\n if strategy is FPSLimiterStrategy.WAIT:\n time.sleep(delay)\n rate_limiter.tick()\n yield frame_data"}, {"class_start_lineno": 1, "class_end_lineno": 516, "func_start_lineno": 46, "func_end_lineno": 97, "func_code": "def get_video_frames_generator(\n video: Union[VideoSource, str, int],\n max_fps: Optional[Union[float, int]] = None,\n limiter_strategy: Optional[FPSLimiterStrategy] = None,\n) -> Generator[VideoFrame, None, None]:\n \"\"\"\n Util function to create a frames generator from `VideoSource` with possibility to\n limit FPS of consumed frames and dictate what to do if frames are produced to fast.\n\n Args:\n video (Union[VideoSource, str, int]): Either instance of VideoSource or video reference accepted\n by VideoSource.init(...)\n max_fps (Optional[Union[float, int]]): value of maximum FPS rate of generated frames - can be used to limit\n generation frequency\n limiter_strategy (Optional[FPSLimiterStrategy]): strategy used to deal with frames decoding exceeding\n limit of `max_fps`. By default - for files, in the interest of processing all frames -\n generation will be awaited, for streams - frames will be dropped on the floor.\n Returns: generator of `VideoFrame`\n\n Example:\n ```python\n from inference.core.interfaces.camera.utils import get_video_frames_generator\n\n for frame in get_video_frames_generator(\n video=\"./some.mp4\",\n max_fps=50,\n ):\n pass\n ```\n \"\"\"\n is_managed_source = False\n if issubclass(type(video), str) or issubclass(type(video), int):\n video = VideoSource.init(\n video_reference=video,\n )\n video.start()\n is_managed_source = True\n if max_fps is None:\n yield from video\n if is_managed_source:\n video.terminate(purge_frames_buffer=True)\n return None\n limiter_strategy = resolve_limiter_strategy(\n explicitly_defined_strategy=limiter_strategy,\n source_properties=video.describe_source().source_properties,\n )\n yield from limit_frame_rate(\n frames_generator=video, max_fps=max_fps, strategy=limiter_strategy\n )\n if is_managed_source:\n video.terminate(purge_frames_buffer=True)\n return None"}], "type": ["function_empty"], "node": ["inference.core.interfaces.camera.video_source.VideoSource.read_frame", "inference.core.interfaces.camera.video_source.VideoSource.__next__", "inference.core.interfaces.camera.utils.limit_frame_rate", "inference.core.interfaces.camera.utils.get_video_frames_generator"], "language": "Python", "toolfunc_count": 3, "func_count": 3, "pytest_info": {"total_num": 42, "base_passed_num": 0}} {"id": ["inference.inference.core.interfaces.camera.video_source.VideoSource::read_frame", "inference.inference.core.interfaces.camera.video_source.VideoSource::__next__", "inference.inference.core.interfaces.camera.video_source.send_video_source_status_update", "inference.inference.core.interfaces.camera.video_source.VideoConsumer::_consume_stream_frame"], "project": "inference", "origin_file": ["inference/core/interfaces/camera/video_source.py", "inference/core/interfaces/camera/video_source.py", "inference/core/interfaces/camera/video_source.py", "inference/core/interfaces/camera/video_source.py", "inference/core/interfaces/camera/video_source.py"], "test_list": ["tests/inference/unit_tests/core/interfaces/camera/test_video_source.py"], "prob_info": [{"class_start_lineno": 181, "class_end_lineno": 738, "func_start_lineno": 526, "func_end_lineno": 555, "func_code": " def read_frame(self, timeout: Optional[float] = None) -> Optional[VideoFrame]:\n \"\"\"\n Method to be used by the consumer to get decoded source frame.\n\n Returns: VideoFrame object with decoded frame and its metadata.\n Throws:\n * EndOfStreamError: when trying to get the frame from closed source.\n \"\"\"\n video_frame: Optional[Union[VideoFrame, str]] = get_from_queue(\n queue=self._frames_buffer,\n on_successful_read=self._video_consumer.notify_frame_consumed,\n timeout=timeout,\n purge=self._buffer_consumption_strategy is BufferConsumptionStrategy.EAGER,\n )\n if video_frame == POISON_PILL:\n raise EndOfStreamError(\n \"Attempted to retrieve frame from stream that already ended.\"\n )\n if video_frame is not None:\n send_video_source_status_update(\n severity=UpdateSeverity.DEBUG,\n event_type=FRAME_CONSUMED_EVENT,\n payload={\n \"frame_timestamp\": video_frame.frame_timestamp,\n \"frame_id\": video_frame.frame_id,\n \"source_id\": video_frame.source_id,\n },\n status_update_handlers=self._status_update_handlers,\n )\n return video_frame"}, {"class_start_lineno": 181, "class_end_lineno": 738, "func_start_lineno": 720, "func_end_lineno": 738, "func_code": " def __next__(self) -> VideoFrame:\n \"\"\"\n Method allowing to use `VideoSource` convenient to read frames\n\n Returns: VideoFrame\n\n Example:\n ```python\n source = VideoSource.init(video_reference=\"./some.mp4\")\n source.start()\n\n for frame in source:\n pass\n ```\n \"\"\"\n try:\n return self.read_frame()\n except EndOfStreamError:\n raise StopIteration()"}, {"class_start_lineno": 1, "class_end_lineno": 1209, "func_start_lineno": 1133, "func_end_lineno": 1156, "func_code": "def send_video_source_status_update(\n severity: UpdateSeverity,\n event_type: str,\n status_update_handlers: List[Callable[[StatusUpdate], None]],\n sub_context: Optional[str] = None,\n payload: Optional[dict] = None,\n) -> None:\n if payload is None:\n payload = {}\n context = VIDEO_SOURCE_CONTEXT\n if sub_context is not None:\n context = f\"{context}.{sub_context}\"\n status_update = StatusUpdate(\n timestamp=datetime.now(),\n severity=severity,\n event_type=event_type,\n payload=payload,\n context=context,\n )\n for handler in status_update_handlers:\n try:\n handler(status_update)\n except Exception as error:\n logger.warning(f\"Could not execute handler update. Cause: {error}\")"}, {"class_start_lineno": 1, "class_end_lineno": 1209, "func_start_lineno": 1112, "func_end_lineno": 1130, "func_code": "def send_frame_drop_update(\n frame_timestamp: datetime,\n frame_id: int,\n cause: str,\n status_update_handlers: List[Callable[[StatusUpdate], None]],\n source_id: Optional[int],\n) -> None:\n send_video_source_status_update(\n severity=UpdateSeverity.DEBUG,\n event_type=FRAME_DROPPED_EVENT,\n payload={\n \"frame_timestamp\": frame_timestamp,\n \"frame_id\": frame_id,\n \"cause\": cause,\n \"source_id\": source_id,\n },\n status_update_handlers=status_update_handlers,\n sub_context=VIDEO_CONSUMER_CONTEXT,\n )"}, {"class_start_lineno": 741, "class_end_lineno": 1061, "func_start_lineno": 919, "func_end_lineno": 985, "func_code": " def _consume_stream_frame(\n self,\n video: VideoFrameProducer,\n declared_source_fps: Optional[float],\n measured_source_fps: Optional[float],\n is_source_video_file: Optional[bool],\n frame_timestamp: datetime,\n buffer: Queue,\n frames_buffering_allowed: bool,\n source_id: Optional[int],\n ) -> bool:\n \"\"\"\n Returns: boolean flag with success status\n \"\"\"\n if not frames_buffering_allowed:\n send_frame_drop_update(\n frame_timestamp=frame_timestamp,\n frame_id=self._frame_counter,\n cause=\"Buffering not allowed at the moment\",\n status_update_handlers=self._status_update_handlers,\n source_id=source_id,\n )\n return True\n if self._frame_should_be_adaptively_dropped(\n declared_source_fps=declared_source_fps\n ):\n self._adaptive_frames_dropped_in_row += 1\n send_frame_drop_update(\n frame_timestamp=frame_timestamp,\n frame_id=self._frame_counter,\n cause=\"ADAPTIVE strategy\",\n status_update_handlers=self._status_update_handlers,\n source_id=source_id,\n )\n return True\n self._adaptive_frames_dropped_in_row = 0\n if (\n not buffer.full()\n or self._buffer_filling_strategy is BufferFillingStrategy.WAIT\n ):\n return decode_video_frame_to_buffer(\n frame_timestamp=frame_timestamp,\n frame_id=self._frame_counter,\n video=video,\n buffer=buffer,\n decoding_pace_monitor=self._decoding_pace_monitor,\n source_id=source_id,\n declared_source_fps=declared_source_fps,\n measured_source_fps=measured_source_fps,\n comes_from_video_file=is_source_video_file,\n )\n if self._buffer_filling_strategy in DROP_OLDEST_STRATEGIES:\n return self._process_stream_frame_dropping_oldest(\n frame_timestamp=frame_timestamp,\n video=video,\n buffer=buffer,\n source_id=source_id,\n is_video_file=is_source_video_file,\n )\n send_frame_drop_update(\n frame_timestamp=frame_timestamp,\n frame_id=self._frame_counter,\n cause=\"DROP_LATEST strategy\",\n status_update_handlers=self._status_update_handlers,\n source_id=source_id,\n )\n return True"}], "type": ["function_empty", "Development"], "node": ["inference.core.interfaces.camera.video_source.VideoSource.read_frame", "inference.core.interfaces.camera.video_source.VideoSource.__next__", "inference.core.interfaces.camera.video_source.send_video_source_status_update", "inference.core.interfaces.camera.video_source.send_frame_drop_update", "inference.core.interfaces.camera.video_source.VideoConsumer._consume_stream_frame"], "language": "Python", "toolfunc_count": 2, "func_count": 4, "pytest_info": {"total_num": 45, "base_passed_num": 0}} {"id": ["inference.inference.core.utils.preprocess.letterbox_image", "inference.inference.core.interfaces.stream.sinks._handle_frame_rendering"], "project": "inference", "origin_file": ["inference/core/utils/preprocess.py", "inference/core/interfaces/stream/sinks.py"], "test_list": ["tests/inference/unit_tests/core/interfaces/stream/test_sinks.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 298, "func_start_lineno": 190, "func_end_lineno": 241, "func_code": "def letterbox_image(\n image: ImageMetaType,\n desired_size: Tuple[int, int],\n color: Tuple[int, int, int] = (0, 0, 0),\n) -> ImageMetaType:\n \"\"\"\n Resize and pad image to fit the desired size, preserving its aspect ratio.\n\n Parameters:\n - image: numpy array representing the image.\n - desired_size: tuple (width, height) representing the target dimensions.\n - color: tuple (B, G, R) representing the color to pad with.\n\n Returns:\n - letterboxed image.\n \"\"\"\n resized_img = resize_image_keeping_aspect_ratio(\n image=image,\n desired_size=desired_size,\n )\n new_height, new_width = (\n resized_img.shape[:2]\n if isinstance(resized_img, np.ndarray)\n else resized_img.shape[-2:]\n )\n top_padding = (desired_size[1] - new_height) // 2\n bottom_padding = desired_size[1] - new_height - top_padding\n left_padding = (desired_size[0] - new_width) // 2\n right_padding = desired_size[0] - new_width - left_padding\n if isinstance(resized_img, np.ndarray):\n return cv2.copyMakeBorder(\n resized_img,\n top_padding,\n bottom_padding,\n left_padding,\n right_padding,\n cv2.BORDER_CONSTANT,\n value=color,\n )\n elif USE_PYTORCH_FOR_PREPROCESSING:\n return torch.nn.functional.pad(\n resized_img,\n (left_padding, right_padding, top_padding, bottom_padding),\n \"constant\",\n color[0],\n )\n else:\n raise ValueError(\n f\"Received an image of unknown type, {type(resized_img)}; \"\n \"This is most likely a bug. Contact Roboflow team through github issues \"\n \"(https://github.com/roboflow/inference/issues) providing full context of the problem\"\n )"}, {"class_start_lineno": 1, "class_end_lineno": 570, "func_start_lineno": 155, "func_end_lineno": 196, "func_code": "def _handle_frame_rendering(\n frame: Optional[VideoFrame],\n prediction: dict,\n annotators: List[BaseAnnotator],\n display_size: Optional[Tuple[int, int]],\n display_statistics: bool,\n fps_value: Optional[float],\n) -> np.ndarray:\n if frame is None:\n image = np.zeros((256, 256, 3), dtype=np.uint8)\n else:\n try:\n labels = [p[\"class\"] for p in prediction[\"predictions\"]]\n if hasattr(sv.Detections, \"from_inference\"):\n detections = sv.Detections.from_inference(prediction)\n else:\n detections = sv.Detections.from_inference(prediction)\n image = frame.image.copy()\n for annotator in annotators:\n kwargs = {\n \"scene\": image,\n \"detections\": detections,\n }\n if isinstance(annotator, sv.LabelAnnotator):\n kwargs[\"labels\"] = labels\n image = annotator.annotate(**kwargs)\n except (TypeError, KeyError):\n logger.warning(\n f\"Used `render_boxes(...)` sink, but predictions that were provided do not match the expected \"\n f\"format of object detection prediction that could be accepted by \"\n f\"`supervision.Detection.from_inference(...)\"\n )\n image = frame.image.copy()\n if display_size is not None:\n image = letterbox_image(image, desired_size=display_size)\n if display_statistics:\n image = render_statistics(\n image=image,\n frame_timestamp=(frame.frame_timestamp if frame is not None else None),\n fps=fps_value,\n )\n return image"}], "type": ["function_empty", "Development"], "node": ["inference.core.utils.preprocess.letterbox_image", "inference.core.interfaces.stream.sinks._handle_frame_rendering"], "language": "Python", "toolfunc_count": 1, "func_count": 2, "pytest_info": {"total_num": 11, "base_passed_num": 8}} {"id": ["inference.inference.core.utils.preprocess.resize_image_keeping_aspect_ratio", "inference.inference.core.utils.preprocess.letterbox_image"], "project": "inference", "origin_file": ["inference/core/utils/preprocess.py", "inference/core/utils/preprocess.py"], "test_list": ["tests/inference/unit_tests/core/utils/test_drawing.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 298, "func_start_lineno": 253, "func_end_lineno": 298, "func_code": "def resize_image_keeping_aspect_ratio(\n image: ImageMetaType,\n desired_size: Tuple[int, int],\n) -> ImageMetaType:\n \"\"\"\n Resize reserving its aspect ratio.\n\n Parameters:\n - image: numpy array representing the image.\n - desired_size: tuple (width, height) representing the target dimensions.\n \"\"\"\n if isinstance(image, np.ndarray):\n img_ratio = image.shape[1] / image.shape[0]\n elif USE_PYTORCH_FOR_PREPROCESSING:\n img_ratio = image.shape[-1] / image.shape[-2]\n else:\n raise ValueError(\n f\"Received an image of unknown type, {type(image)}; \"\n \"This is most likely a bug. Contact Roboflow team through github issues \"\n \"(https://github.com/roboflow/inference/issues) providing full context of the problem\"\n )\n desired_ratio = desired_size[0] / desired_size[1]\n\n # Determine the new dimensions\n if img_ratio >= desired_ratio:\n # Resize by width\n new_width = desired_size[0]\n new_height = int(desired_size[0] / img_ratio)\n else:\n # Resize by height\n new_height = desired_size[1]\n new_width = int(desired_size[1] * img_ratio)\n\n # Resize the image to new dimensions\n if isinstance(image, np.ndarray):\n return cv2.resize(image, (new_width, new_height))\n elif USE_PYTORCH_FOR_PREPROCESSING:\n return torch.nn.functional.interpolate(\n image, size=(new_height, new_width), mode=\"bilinear\"\n )\n else:\n raise ValueError(\n f\"Received an image of unknown type, {type(image)}; \"\n \"This is most likely a bug. Contact Roboflow team through github issues \"\n \"(https://github.com/roboflow/inference/issues) providing full context of the problem\"\n )"}, {"class_start_lineno": 1, "class_end_lineno": 298, "func_start_lineno": 190, "func_end_lineno": 241, "func_code": "def letterbox_image(\n image: ImageMetaType,\n desired_size: Tuple[int, int],\n color: Tuple[int, int, int] = (0, 0, 0),\n) -> ImageMetaType:\n \"\"\"\n Resize and pad image to fit the desired size, preserving its aspect ratio.\n\n Parameters:\n - image: numpy array representing the image.\n - desired_size: tuple (width, height) representing the target dimensions.\n - color: tuple (B, G, R) representing the color to pad with.\n\n Returns:\n - letterboxed image.\n \"\"\"\n resized_img = resize_image_keeping_aspect_ratio(\n image=image,\n desired_size=desired_size,\n )\n new_height, new_width = (\n resized_img.shape[:2]\n if isinstance(resized_img, np.ndarray)\n else resized_img.shape[-2:]\n )\n top_padding = (desired_size[1] - new_height) // 2\n bottom_padding = desired_size[1] - new_height - top_padding\n left_padding = (desired_size[0] - new_width) // 2\n right_padding = desired_size[0] - new_width - left_padding\n if isinstance(resized_img, np.ndarray):\n return cv2.copyMakeBorder(\n resized_img,\n top_padding,\n bottom_padding,\n left_padding,\n right_padding,\n cv2.BORDER_CONSTANT,\n value=color,\n )\n elif USE_PYTORCH_FOR_PREPROCESSING:\n return torch.nn.functional.pad(\n resized_img,\n (left_padding, right_padding, top_padding, bottom_padding),\n \"constant\",\n color[0],\n )\n else:\n raise ValueError(\n f\"Received an image of unknown type, {type(resized_img)}; \"\n \"This is most likely a bug. Contact Roboflow team through github issues \"\n \"(https://github.com/roboflow/inference/issues) providing full context of the problem\"\n )"}], "type": ["function_empty"], "node": ["inference.core.utils.preprocess.resize_image_keeping_aspect_ratio", "inference.core.utils.preprocess.letterbox_image"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 10, "base_passed_num": 2}} {"id": ["inference.inference.core.utils.image_utils.validate_numpy_image", "inference.inference.core.utils.image_utils.load_image_from_numpy_str", "inference.inference.core.utils.image_utils.load_image_base64", "inference.inference.core.utils.image_utils.load_image_from_encoded_bytes", "inference.inference.core.utils.image_utils.attempt_loading_image_from_string", "inference.inference.core.utils.image_utils.load_image_with_inferred_type"], "project": "inference", "origin_file": ["inference/core/utils/image_utils.py", "inference/core/utils/image_utils.py", "inference/core/utils/image_utils.py", "inference/core/utils/image_utils.py", "inference/core/utils/image_utils.py", "inference/core/utils/image_utils.py"], "test_list": ["tests/inference/unit_tests/core/utils/test_image_utils.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 599, "func_start_lineno": 353, "func_end_lineno": 377, "func_code": "def validate_numpy_image(data: np.ndarray) -> None:\n \"\"\"\n Validate if the provided data is a valid numpy image.\n\n Args:\n data (np.ndarray): The numpy array representing an image.\n\n Raises:\n InvalidNumpyInput: If the provided data is not a valid numpy image.\n \"\"\"\n if not issubclass(type(data), np.ndarray):\n raise InvalidNumpyInput(\n message=f\"Data provided as input could not be decoded into np.ndarray object.\",\n public_message=f\"Data provided as input could not be decoded into np.ndarray object.\",\n )\n if len(data.shape) != 3 and len(data.shape) != 2:\n raise InvalidNumpyInput(\n message=f\"For image given as np.ndarray expected 2 or 3 dimensions, got {len(data.shape)} dimensions.\",\n public_message=f\"For image given as np.ndarray expected 2 or 3 dimensions.\",\n )\n if data.shape[-1] != 3 and data.shape[-1] != 1:\n raise InvalidNumpyInput(\n message=f\"For image given as np.ndarray expected 1 or 3 channels, got {data.shape[-1]} channels.\",\n public_message=\"For image given as np.ndarray expected 1 or 3 channels.\",\n )"}, {"class_start_lineno": 1, "class_end_lineno": 599, "func_start_lineno": 318, "func_end_lineno": 345, "func_code": "def load_image_from_numpy_str(value: Union[bytes, str]) -> np.ndarray:\n \"\"\"Loads an image from a numpy array string.\n\n Args:\n value (Union[bytes, str]): Base64 string or byte sequence representing the pickled numpy array of the image.\n\n Returns:\n Image.Image: The loaded PIL image.\n\n Raises:\n InvalidNumpyInput: If the numpy data is invalid.\n \"\"\"\n if not ALLOW_NUMPY_INPUT:\n raise InvalidImageTypeDeclared(\n message=f\"NumPy image type is not supported in this configuration of `inference`.\",\n public_message=f\"NumPy image type is not supported in this configuration of `inference`.\",\n )\n try:\n if isinstance(value, str):\n value = pybase64.b64decode(value)\n data = pickle.loads(value)\n except (EOFError, TypeError, pickle.UnpicklingError, binascii.Error) as error:\n raise InvalidNumpyInput(\n message=f\"Could not unpickle image data. Cause: {error}\",\n public_message=\"Could not deserialize pickle payload.\",\n ) from error\n validate_numpy_image(data=data)\n return data"}, {"class_start_lineno": 1, "class_end_lineno": 599, "func_start_lineno": 258, "func_end_lineno": 292, "func_code": "def load_image_base64(\n value: Union[str, bytes], cv_imread_flags=cv2.IMREAD_COLOR\n) -> np.ndarray:\n \"\"\"Loads an image from a base64 encoded string using OpenCV.\n\n Args:\n value (str): Base64 encoded string representing the image.\n\n Returns:\n np.ndarray: The loaded image as a numpy array.\n \"\"\"\n # New routes accept images via json body (str), legacy routes accept bytes which need to be decoded as strings\n if not isinstance(value, str):\n value = value.decode(\"utf-8\")\n value = BASE64_DATA_TYPE_PATTERN.sub(\"\", value)\n try:\n value = pybase64.b64decode(value)\n except binascii.Error as error:\n raise InputImageLoadError(\n message=\"Could not load valid image from base64 string.\",\n public_message=\"Malformed base64 input image.\",\n ) from error\n if len(value) == 0:\n raise InputImageLoadError(\n message=\"Could not load valid image from base64 string.\",\n public_message=\"Empty image payload.\",\n )\n image_np = np.frombuffer(value, np.uint8)\n result = cv2.imdecode(image_np, cv_imread_flags)\n if result is None:\n raise InputImageLoadError(\n message=\"Could not load valid image from base64 string.\",\n public_message=\"Malformed base64 input image.\",\n )\n return result"}, {"class_start_lineno": 1, "class_end_lineno": 599, "func_start_lineno": 496, "func_end_lineno": 516, "func_code": "def load_image_from_encoded_bytes(\n value: bytes, cv_imread_flags: int = cv2.IMREAD_COLOR\n) -> np.ndarray:\n \"\"\"\n Load an image from encoded bytes.\n\n Args:\n value (bytes): The byte sequence representing the image.\n cv_imread_flags (int): OpenCV flags used for image reading.\n\n Returns:\n np.ndarray: The loaded image as a numpy array.\n \"\"\"\n image_np = np.asarray(bytearray(value), dtype=np.uint8)\n image = cv2.imdecode(image_np, cv_imread_flags)\n if image is None:\n raise InputImageLoadError(\n message=f\"Could not decode bytes as image.\",\n public_message=\"Data is not image.\",\n )\n return image"}, {"class_start_lineno": 1, "class_end_lineno": 599, "func_start_lineno": 215, "func_end_lineno": 255, "func_code": "def attempt_loading_image_from_string(\n value: Union[str, bytes, bytearray, _IOBase],\n cv_imread_flags: int = cv2.IMREAD_COLOR,\n) -> Tuple[np.ndarray, bool]:\n \"\"\"\n Attempt to load an image from a string.\n\n Args:\n value (Union[str, bytes, bytearray, _IOBase]): The image data in string format.\n cv_imread_flags (int): OpenCV flags used for image reading.\n\n Returns:\n Tuple[np.ndarray, bool]: A tuple of the loaded image in numpy array format and a boolean flag indicating if the image is in BGR format.\n \"\"\"\n try:\n return load_image_base64(value=value, cv_imread_flags=cv_imread_flags), True\n except:\n pass\n try:\n return (\n load_image_from_encoded_bytes(value=value, cv_imread_flags=cv_imread_flags),\n True,\n )\n except:\n pass\n try:\n return (\n load_image_from_buffer(value=value, cv_imread_flags=cv_imread_flags),\n True,\n )\n except:\n pass\n try:\n return load_image_from_numpy_str(value=value), True\n except InvalidImageTypeDeclared as error:\n raise error\n except InvalidNumpyInput as error:\n raise InputFormatInferenceFailed(\n message=\"Input image format could not be inferred from string.\",\n public_message=\"Input image format could not be inferred from string.\",\n ) from error"}, {"class_start_lineno": 1, "class_end_lineno": 599, "func_start_lineno": 180, "func_end_lineno": 212, "func_code": "def load_image_with_inferred_type(\n value: Any,\n cv_imread_flags: int = cv2.IMREAD_COLOR,\n) -> Tuple[np.ndarray, bool]:\n \"\"\"Load an image by inferring its type.\n\n Args:\n value (Any): The image data.\n cv_imread_flags (int): Flags used for OpenCV's imread function.\n\n Returns:\n Tuple[np.ndarray, bool]: Loaded image as a numpy array and a boolean indicating if the image is in BGR format.\n\n Raises:\n NotImplementedError: If the image type could not be inferred.\n \"\"\"\n if isinstance(value, (np.ndarray, np.generic)):\n validate_numpy_image(data=value)\n return value, True\n elif isinstance(value, Image.Image):\n return np.asarray(value.convert(\"RGB\")), False\n elif isinstance(value, str) and (value.startswith(\"http\")):\n return load_image_from_url(value=value, cv_imread_flags=cv_imread_flags), True\n elif (\n isinstance(value, str)\n and ALLOW_LOADING_IMAGES_FROM_LOCAL_FILESYSTEM\n and os.path.isfile(value)\n ):\n return cv2.imread(value, cv_imread_flags), True\n else:\n return attempt_loading_image_from_string(\n value=value, cv_imread_flags=cv_imread_flags\n )"}], "type": ["function_empty", "Development"], "node": ["inference.core.utils.image_utils.validate_numpy_image", "inference.core.utils.image_utils.load_image_from_numpy_str", "inference.core.utils.image_utils.load_image_base64", "inference.core.utils.image_utils.load_image_from_encoded_bytes", "inference.core.utils.image_utils.attempt_loading_image_from_string", "inference.core.utils.image_utils.load_image_with_inferred_type"], "language": "Python", "toolfunc_count": 5, "func_count": 6, "pytest_info": {"total_num": 152, "base_passed_num": 77}} {"id": ["inference.inference.core.utils.postprocess.get_static_crop_dimensions", "inference.inference.core.utils.postprocess.post_process_bboxes", "inference.inference.core.utils.postprocess.post_process_polygons", "inference.inference.core.utils.postprocess.post_process_keypoints"], "project": "inference", "origin_file": ["inference/core/utils/postprocess.py", "inference/core/utils/postprocess.py", "inference/core/utils/postprocess.py", "inference/core/utils/postprocess.py"], "test_list": ["tests/inference/unit_tests/core/utils/test_postprocess.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 658, "func_start_lineno": 473, "func_end_lineno": 513, "func_code": "def get_static_crop_dimensions(\n orig_shape: Tuple[int, int],\n preproc: dict,\n disable_preproc_static_crop: bool = False,\n) -> Tuple[Tuple[int, int], Tuple[int, int]]:\n \"\"\"\n Generates a transformation based on preprocessing configuration.\n\n Args:\n orig_shape (tuple): The original shape of the object (e.g., image) - (height, width).\n preproc (dict): Preprocessing configuration dictionary, containing information such as static cropping.\n disable_preproc_static_crop (bool, optional): If true, the static crop preprocessing step is disabled for this call. Default is False.\n\n Returns:\n tuple: A tuple containing the shift in the x and y directions, and the updated original shape after cropping.\n \"\"\"\n try:\n if static_crop_should_be_applied(\n preprocessing_config=preproc,\n disable_preproc_static_crop=disable_preproc_static_crop,\n ):\n x_min, y_min, x_max, y_max = standardise_static_crop(\n static_crop_config=preproc[STATIC_CROP_KEY]\n )\n else:\n x_min, y_min, x_max, y_max = 0, 0, 1, 1\n crop_shift_x, crop_shift_y = (\n round(x_min * orig_shape[1]),\n round(y_min * orig_shape[0]),\n )\n cropped_percent_x = x_max - x_min\n cropped_percent_y = y_max - y_min\n orig_shape = (\n round(orig_shape[0] * cropped_percent_y),\n round(orig_shape[1] * cropped_percent_x),\n )\n return (crop_shift_x, crop_shift_y), orig_shape\n except KeyError as error:\n raise PostProcessingError(\n f\"Could not find a proper configuration key {error} in post-processing.\"\n )"}, {"class_start_lineno": 1, "class_end_lineno": 658, "func_start_lineno": 98, "func_end_lineno": 163, "func_code": "def post_process_bboxes(\n predictions: List[List[List[float]]],\n infer_shape: Tuple[int, int],\n img_dims: List[Tuple[int, int]],\n preproc: dict,\n disable_preproc_static_crop: bool = False,\n resize_method: str = \"Stretch to\",\n) -> List[List[List[float]]]:\n \"\"\"\n Postprocesses each patch of detections by scaling them to the original image coordinates and by shifting them based on a static crop preproc (if applied).\n\n Args:\n predictions (List[List[List[float]]]): The predictions output from NMS, indices are: batch x prediction x [x1, y1, x2, y2, ...].\n infer_shape (Tuple[int, int]): The shape of the inference image.\n img_dims (List[Tuple[int, int]]): The dimensions of the original image for each batch, indices are: batch x [height, width].\n preproc (dict): Preprocessing configuration dictionary.\n disable_preproc_static_crop (bool, optional): If true, the static crop preprocessing step is disabled for this call. Default is False.\n resize_method (str, optional): Resize method for image. Defaults to \"Stretch to\".\n\n Returns:\n List[List[List[float]]]: The scaled and shifted predictions, indices are: batch x prediction x [x1, y1, x2, y2, ...].\n \"\"\"\n\n # Get static crop params\n scaled_predictions = []\n # Loop through batches\n for i, batch_predictions in enumerate(predictions):\n if len(batch_predictions) == 0:\n scaled_predictions.append([])\n continue\n np_batch_predictions = np.array(batch_predictions)\n # Get bboxes from predictions (x1,y1,x2,y2)\n predicted_bboxes = np_batch_predictions[:, :4]\n (crop_shift_x, crop_shift_y), origin_shape = get_static_crop_dimensions(\n img_dims[i],\n preproc,\n disable_preproc_static_crop=disable_preproc_static_crop,\n )\n if resize_method == \"Stretch to\":\n predicted_bboxes = stretch_bboxes(\n predicted_bboxes=predicted_bboxes,\n infer_shape=infer_shape,\n origin_shape=origin_shape,\n )\n elif (\n resize_method == \"Fit (black edges) in\"\n or resize_method == \"Fit (white edges) in\"\n or resize_method == \"Fit (grey edges) in\"\n ):\n predicted_bboxes = undo_image_padding_for_predicted_boxes(\n predicted_bboxes=predicted_bboxes,\n infer_shape=infer_shape,\n origin_shape=origin_shape,\n )\n predicted_bboxes = clip_boxes_coordinates(\n predicted_bboxes=predicted_bboxes,\n origin_shape=origin_shape,\n )\n predicted_bboxes = shift_bboxes(\n bboxes=predicted_bboxes,\n shift_x=crop_shift_x,\n shift_y=crop_shift_y,\n )\n np_batch_predictions[:, :4] = predicted_bboxes\n scaled_predictions.append(np_batch_predictions.tolist())\n return scaled_predictions"}, {"class_start_lineno": 1, "class_end_lineno": 658, "func_start_lineno": 393, "func_end_lineno": 441, "func_code": "def post_process_polygons(\n origin_shape: Tuple[int, int],\n polys: List[List[Tuple[float, float]]],\n infer_shape: Tuple[int, int],\n preproc: dict,\n resize_method: str = \"Stretch to\",\n) -> List[List[Tuple[float, float]]]:\n \"\"\"Scales and shifts polygons based on the given image shapes and preprocessing method.\n\n This function performs polygon scaling and shifting based on the specified resizing method and\n pre-processing steps. The polygons are transformed according to the ratio and padding between two images.\n\n Args:\n origin_shape (tuple of int): Shape of the source image (height, width).\n infer_shape (tuple of int): Shape of the target image (height, width).\n polys (list of list of tuple): List of polygons, where each polygon is represented by a list of (x, y) coordinates.\n preproc (object): Preprocessing details used for generating the transformation.\n resize_method (str, optional): Resizing method, either \"Stretch to\", \"Fit (black edges) in\", \"Fit (white edges) in\", or \"Fit (grey edges) in\". Defaults to \"Stretch to\".\n\n Returns:\n list of list of tuple: A list of shifted and scaled polygons.\n \"\"\"\n (crop_shift_x, crop_shift_y), origin_shape = get_static_crop_dimensions(\n origin_shape, preproc\n )\n new_polys = []\n if resize_method == \"Stretch to\":\n width_ratio = origin_shape[1] / infer_shape[1]\n height_ratio = origin_shape[0] / infer_shape[0]\n new_polys = scale_polygons(\n polygons=polys,\n x_scale=width_ratio,\n y_scale=height_ratio,\n )\n elif resize_method in {\n \"Fit (black edges) in\",\n \"Fit (white edges) in\",\n \"Fit (grey edges) in\",\n }:\n new_polys = undo_image_padding_for_predicted_polygons(\n polygons=polys,\n infer_shape=infer_shape,\n origin_shape=origin_shape,\n )\n shifted_polys = []\n for poly in new_polys:\n poly = [(p[0] + crop_shift_x, p[1] + crop_shift_y) for p in poly]\n shifted_polys.append(poly)\n return shifted_polys"}, {"class_start_lineno": 1, "class_end_lineno": 658, "func_start_lineno": 522, "func_end_lineno": 585, "func_code": "def post_process_keypoints(\n predictions: List[List[List[float]]],\n keypoints_start_index: int,\n infer_shape: Tuple[int, int],\n img_dims: List[Tuple[int, int]],\n preproc: dict,\n disable_preproc_static_crop: bool = False,\n resize_method: str = \"Stretch to\",\n) -> List[List[List[float]]]:\n \"\"\"Scales and shifts keypoints based on the given image shapes and preprocessing method.\n\n This function performs polygon scaling and shifting based on the specified resizing method and\n pre-processing steps. The polygons are transformed according to the ratio and padding between two images.\n\n Args:\n predictions: predictions from model\n keypoints_start_index: offset in the 3rd dimension pointing where in the prediction start keypoints [(x, y, cfg), ...] for each keypoint class\n img_dims list of (tuple of int): Shape of the source image (height, width).\n infer_shape (tuple of int): Shape of the target image (height, width).\n preproc (object): Preprocessing details used for generating the transformation.\n resize_method (str, optional): Resizing method, either \"Stretch to\", \"Fit (black edges) in\", \"Fit (white edges) in\", or \"Fit (grey edges) in\". Defaults to \"Stretch to\".\n disable_preproc_static_crop: flag to disable static crop\n Returns:\n list of list of list: predictions with post-processed keypoints\n \"\"\"\n # Get static crop params\n scaled_predictions = []\n # Loop through batches\n for i, batch_predictions in enumerate(predictions):\n if len(batch_predictions) == 0:\n scaled_predictions.append([])\n continue\n np_batch_predictions = np.array(batch_predictions)\n keypoints = np_batch_predictions[:, keypoints_start_index:]\n (crop_shift_x, crop_shift_y), origin_shape = get_static_crop_dimensions(\n img_dims[i],\n preproc,\n disable_preproc_static_crop=disable_preproc_static_crop,\n )\n if resize_method == \"Stretch to\":\n keypoints = stretch_keypoints(\n keypoints=keypoints,\n infer_shape=infer_shape,\n origin_shape=origin_shape,\n )\n elif (\n resize_method == \"Fit (black edges) in\"\n or resize_method == \"Fit (white edges) in\"\n or resize_method == \"Fit (grey edges) in\"\n ):\n keypoints = undo_image_padding_for_predicted_keypoints(\n keypoints=keypoints,\n infer_shape=infer_shape,\n origin_shape=origin_shape,\n )\n keypoints = clip_keypoints_coordinates(\n keypoints=keypoints, origin_shape=origin_shape\n )\n keypoints = shift_keypoints(\n keypoints=keypoints, shift_x=crop_shift_x, shift_y=crop_shift_y\n )\n np_batch_predictions[:, keypoints_start_index:] = keypoints\n scaled_predictions.append(np_batch_predictions.tolist())\n return scaled_predictions"}], "type": ["function_empty", "Development"], "node": ["inference.core.utils.postprocess.get_static_crop_dimensions", "inference.core.utils.postprocess.post_process_bboxes", "inference.core.utils.postprocess.post_process_polygons", "inference.core.utils.postprocess.post_process_keypoints"], "language": "Python", "toolfunc_count": 3, "func_count": 4, "pytest_info": {"total_num": 54, "base_passed_num": 24}} {"id": ["langchain.libs.langchain.langchain.agents.agent.AgentExecutor::_action_agent", "langchain.libs.langchain.langchain.agents.agent.AgentExecutor::_perform_agent_action", "langchain.libs.langchain.langchain.agents.agent.AgentExecutor::_iter_next_step", "langchain.libs.langchain.langchain.agents.agent.AgentExecutor::_take_next_step"], "project": "langchain", "origin_file": ["langchain/agents/agent.py", "langchain/agents/agent.py", "langchain/agents/agent.py", "langchain/agents/agent.py"], "test_list": ["libs/langchain/tests/unit_tests/agents/test_agent.py"], "prob_info": [{"class_start_lineno": 1047, "class_end_lineno": 1806, "func_start_lineno": 1177, "func_end_lineno": 1189, "func_code": " def _action_agent(self) -> Union[BaseSingleActionAgent, BaseMultiActionAgent]:\n \"\"\"Type cast self.agent.\n\n If the `agent` attribute is a Runnable, it will be converted one of\n RunnableAgentType in the validate_runnable_agent root_validator.\n\n To support instantiating with a Runnable, here we explicitly cast the type\n to reflect the changes made in the root_validator.\n \"\"\"\n if isinstance(self.agent, Runnable):\n return cast(RunnableAgentType, self.agent)\n else:\n return self.agent"}, {"class_start_lineno": 1047, "class_end_lineno": 1806, "func_start_lineno": 1419, "func_end_lineno": 1456, "func_code": " def _perform_agent_action(\n self,\n name_to_tool_map: Dict[str, BaseTool],\n color_mapping: Dict[str, str],\n agent_action: AgentAction,\n run_manager: Optional[CallbackManagerForChainRun] = None,\n ) -> AgentStep:\n if run_manager:\n run_manager.on_agent_action(agent_action, color=\"green\")\n # Otherwise we lookup the tool\n if agent_action.tool in name_to_tool_map:\n tool = name_to_tool_map[agent_action.tool]\n return_direct = tool.return_direct\n color = color_mapping[agent_action.tool]\n tool_run_kwargs = self._action_agent.tool_run_logging_kwargs()\n if return_direct:\n tool_run_kwargs[\"llm_prefix\"] = \"\"\n # We then call the tool on the tool input to get an observation\n observation = tool.run(\n agent_action.tool_input,\n verbose=self.verbose,\n color=color,\n callbacks=run_manager.get_child() if run_manager else None,\n **tool_run_kwargs,\n )\n else:\n tool_run_kwargs = self._action_agent.tool_run_logging_kwargs()\n observation = InvalidTool().run(\n {\n \"requested_tool_name\": agent_action.tool,\n \"available_tool_names\": list(name_to_tool_map.keys()),\n },\n verbose=self.verbose,\n color=None,\n callbacks=run_manager.get_child() if run_manager else None,\n **tool_run_kwargs,\n )\n return AgentStep(action=agent_action, observation=observation)"}, {"class_start_lineno": 1047, "class_end_lineno": 1806, "func_start_lineno": 1342, "func_end_lineno": 1417, "func_code": " def _iter_next_step(\n self,\n name_to_tool_map: Dict[str, BaseTool],\n color_mapping: Dict[str, str],\n inputs: Dict[str, str],\n intermediate_steps: List[Tuple[AgentAction, str]],\n run_manager: Optional[CallbackManagerForChainRun] = None,\n ) -> Iterator[Union[AgentFinish, AgentAction, AgentStep]]:\n \"\"\"Take a single step in the thought-action-observation loop.\n\n Override this to take control of how the agent makes and acts on choices.\n \"\"\"\n try:\n intermediate_steps = self._prepare_intermediate_steps(intermediate_steps)\n\n # Call the LLM to see what to do.\n output = self._action_agent.plan(\n intermediate_steps,\n callbacks=run_manager.get_child() if run_manager else None,\n **inputs,\n )\n except OutputParserException as e:\n if isinstance(self.handle_parsing_errors, bool):\n raise_error = not self.handle_parsing_errors\n else:\n raise_error = False\n if raise_error:\n raise ValueError(\n \"An output parsing error occurred. \"\n \"In order to pass this error back to the agent and have it try \"\n \"again, pass `handle_parsing_errors=True` to the AgentExecutor. \"\n f\"This is the error: {str(e)}\"\n )\n text = str(e)\n if isinstance(self.handle_parsing_errors, bool):\n if e.send_to_llm:\n observation = str(e.observation)\n text = str(e.llm_output)\n else:\n observation = \"Invalid or incomplete response\"\n elif isinstance(self.handle_parsing_errors, str):\n observation = self.handle_parsing_errors\n elif callable(self.handle_parsing_errors):\n observation = self.handle_parsing_errors(e)\n else:\n raise ValueError(\"Got unexpected type of `handle_parsing_errors`\")\n output = AgentAction(\"_Exception\", observation, text)\n if run_manager:\n run_manager.on_agent_action(output, color=\"green\")\n tool_run_kwargs = self._action_agent.tool_run_logging_kwargs()\n observation = ExceptionTool().run(\n output.tool_input,\n verbose=self.verbose,\n color=None,\n callbacks=run_manager.get_child() if run_manager else None,\n **tool_run_kwargs,\n )\n yield AgentStep(action=output, observation=observation)\n return\n\n # If the tool chosen is the finishing tool, then we end and return.\n if isinstance(output, AgentFinish):\n yield output\n return\n\n actions: List[AgentAction]\n if isinstance(output, AgentAction):\n actions = [output]\n else:\n actions = output\n for agent_action in actions:\n yield agent_action\n for agent_action in actions:\n yield self._perform_agent_action(\n name_to_tool_map, color_mapping, agent_action, run_manager\n )"}, {"class_start_lineno": 1047, "class_end_lineno": 1806, "func_start_lineno": 1321, "func_end_lineno": 1340, "func_code": " def _take_next_step(\n self,\n name_to_tool_map: Dict[str, BaseTool],\n color_mapping: Dict[str, str],\n inputs: Dict[str, str],\n intermediate_steps: List[Tuple[AgentAction, str]],\n run_manager: Optional[CallbackManagerForChainRun] = None,\n ) -> Union[AgentFinish, List[Tuple[AgentAction, str]]]:\n return self._consume_next_step(\n [\n a\n for a in self._iter_next_step(\n name_to_tool_map,\n color_mapping,\n inputs,\n intermediate_steps,\n run_manager,\n )\n ]\n )"}], "type": ["function_empty", "Development"], "node": ["langchain.agents.agent.AgentExecutor._action_agent", "langchain.agents.agent.AgentExecutor._perform_agent_action", "langchain.agents.agent.AgentExecutor._iter_next_step", "langchain.agents.agent.AgentExecutor._take_next_step"], "language": "Python", "toolfunc_count": 1, "func_count": 4, "pytest_info": {"total_num": 14, "base_passed_num": 2}} {"id": ["langchain.libs.langchain.langchain.agents.agent.AgentExecutor::_action_agent", "langchain.libs.langchain.langchain.agents.agent.AgentExecutor::_perform_agent_action", "langchain.libs.langchain.langchain.agents.agent.AgentExecutor::_iter_next_step"], "project": "langchain", "origin_file": ["langchain/agents/agent.py", "langchain/agents/agent.py", "langchain/agents/agent.py"], "test_list": ["libs/langchain/tests/unit_tests/agents/test_agent_iterator.py"], "prob_info": [{"class_start_lineno": 1047, "class_end_lineno": 1806, "func_start_lineno": 1177, "func_end_lineno": 1189, "func_code": " def _action_agent(self) -> Union[BaseSingleActionAgent, BaseMultiActionAgent]:\n \"\"\"Type cast self.agent.\n\n If the `agent` attribute is a Runnable, it will be converted one of\n RunnableAgentType in the validate_runnable_agent root_validator.\n\n To support instantiating with a Runnable, here we explicitly cast the type\n to reflect the changes made in the root_validator.\n \"\"\"\n if isinstance(self.agent, Runnable):\n return cast(RunnableAgentType, self.agent)\n else:\n return self.agent"}, {"class_start_lineno": 1047, "class_end_lineno": 1806, "func_start_lineno": 1419, "func_end_lineno": 1456, "func_code": " def _perform_agent_action(\n self,\n name_to_tool_map: Dict[str, BaseTool],\n color_mapping: Dict[str, str],\n agent_action: AgentAction,\n run_manager: Optional[CallbackManagerForChainRun] = None,\n ) -> AgentStep:\n if run_manager:\n run_manager.on_agent_action(agent_action, color=\"green\")\n # Otherwise we lookup the tool\n if agent_action.tool in name_to_tool_map:\n tool = name_to_tool_map[agent_action.tool]\n return_direct = tool.return_direct\n color = color_mapping[agent_action.tool]\n tool_run_kwargs = self._action_agent.tool_run_logging_kwargs()\n if return_direct:\n tool_run_kwargs[\"llm_prefix\"] = \"\"\n # We then call the tool on the tool input to get an observation\n observation = tool.run(\n agent_action.tool_input,\n verbose=self.verbose,\n color=color,\n callbacks=run_manager.get_child() if run_manager else None,\n **tool_run_kwargs,\n )\n else:\n tool_run_kwargs = self._action_agent.tool_run_logging_kwargs()\n observation = InvalidTool().run(\n {\n \"requested_tool_name\": agent_action.tool,\n \"available_tool_names\": list(name_to_tool_map.keys()),\n },\n verbose=self.verbose,\n color=None,\n callbacks=run_manager.get_child() if run_manager else None,\n **tool_run_kwargs,\n )\n return AgentStep(action=agent_action, observation=observation)"}, {"class_start_lineno": 1047, "class_end_lineno": 1806, "func_start_lineno": 1342, "func_end_lineno": 1417, "func_code": " def _iter_next_step(\n self,\n name_to_tool_map: Dict[str, BaseTool],\n color_mapping: Dict[str, str],\n inputs: Dict[str, str],\n intermediate_steps: List[Tuple[AgentAction, str]],\n run_manager: Optional[CallbackManagerForChainRun] = None,\n ) -> Iterator[Union[AgentFinish, AgentAction, AgentStep]]:\n \"\"\"Take a single step in the thought-action-observation loop.\n\n Override this to take control of how the agent makes and acts on choices.\n \"\"\"\n try:\n intermediate_steps = self._prepare_intermediate_steps(intermediate_steps)\n\n # Call the LLM to see what to do.\n output = self._action_agent.plan(\n intermediate_steps,\n callbacks=run_manager.get_child() if run_manager else None,\n **inputs,\n )\n except OutputParserException as e:\n if isinstance(self.handle_parsing_errors, bool):\n raise_error = not self.handle_parsing_errors\n else:\n raise_error = False\n if raise_error:\n raise ValueError(\n \"An output parsing error occurred. \"\n \"In order to pass this error back to the agent and have it try \"\n \"again, pass `handle_parsing_errors=True` to the AgentExecutor. \"\n f\"This is the error: {str(e)}\"\n )\n text = str(e)\n if isinstance(self.handle_parsing_errors, bool):\n if e.send_to_llm:\n observation = str(e.observation)\n text = str(e.llm_output)\n else:\n observation = \"Invalid or incomplete response\"\n elif isinstance(self.handle_parsing_errors, str):\n observation = self.handle_parsing_errors\n elif callable(self.handle_parsing_errors):\n observation = self.handle_parsing_errors(e)\n else:\n raise ValueError(\"Got unexpected type of `handle_parsing_errors`\")\n output = AgentAction(\"_Exception\", observation, text)\n if run_manager:\n run_manager.on_agent_action(output, color=\"green\")\n tool_run_kwargs = self._action_agent.tool_run_logging_kwargs()\n observation = ExceptionTool().run(\n output.tool_input,\n verbose=self.verbose,\n color=None,\n callbacks=run_manager.get_child() if run_manager else None,\n **tool_run_kwargs,\n )\n yield AgentStep(action=output, observation=observation)\n return\n\n # If the tool chosen is the finishing tool, then we end and return.\n if isinstance(output, AgentFinish):\n yield output\n return\n\n actions: List[AgentAction]\n if isinstance(output, AgentAction):\n actions = [output]\n else:\n actions = output\n for agent_action in actions:\n yield agent_action\n for agent_action in actions:\n yield self._perform_agent_action(\n name_to_tool_map, color_mapping, agent_action, run_manager\n )"}], "type": ["function_empty", "Development"], "node": ["langchain.agents.agent.AgentExecutor._action_agent", "langchain.agents.agent.AgentExecutor._perform_agent_action", "langchain.agents.agent.AgentExecutor._iter_next_step"], "language": "Python", "toolfunc_count": 1, "func_count": 3, "pytest_info": {"total_num": 14, "base_passed_num": 0}} {"id": ["langchain.libs.langchain.langchain.agents.format_scratchpad.openai_functions._create_function_message", "langchain.libs.langchain.langchain.agents.format_scratchpad.openai_functions._convert_agent_action_to_messages", "langchain.libs.langchain.langchain.agents.format_scratchpad.openai_functions.format_to_openai_function_messages"], "project": "langchain", "origin_file": ["langchain/agents/format_scratchpad/openai_functions.py", "langchain/agents/format_scratchpad/openai_functions.py", "langchain/agents/format_scratchpad/openai_functions.py"], "test_list": ["libs/langchain/tests/unit_tests/agents/format_scratchpad/test_openai_functions.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 78, "func_start_lineno": 30, "func_end_lineno": 53, "func_code": "def _create_function_message(\n agent_action: AgentAction, observation: str\n) -> FunctionMessage:\n \"\"\"Convert agent action and observation into a function message.\n Args:\n agent_action: the tool invocation request from the agent.\n observation: the result of the tool invocation.\n Returns:\n FunctionMessage that corresponds to the original tool invocation.\n\n Raises:\n ValueError: if the observation cannot be converted to a string.\n \"\"\"\n if not isinstance(observation, str):\n try:\n content = json.dumps(observation, ensure_ascii=False)\n except Exception:\n content = str(observation)\n else:\n content = observation\n return FunctionMessage(\n name=agent_action.tool,\n content=content,\n )"}, {"class_start_lineno": 1, "class_end_lineno": 78, "func_start_lineno": 8, "func_end_lineno": 27, "func_code": "def _convert_agent_action_to_messages(\n agent_action: AgentAction, observation: str\n) -> List[BaseMessage]:\n \"\"\"Convert an agent action to a message.\n\n This code is used to reconstruct the original AI message from the agent action.\n\n Args:\n agent_action: Agent action to convert.\n\n Returns:\n AIMessage or the previous messages plus a FunctionMessage that corresponds to\n the original tool invocation\n \"\"\"\n if isinstance(agent_action, AgentActionMessageLog):\n return list(agent_action.message_log) + [\n _create_function_message(agent_action, observation)\n ]\n else:\n return [AIMessage(content=agent_action.log)]"}, {"class_start_lineno": 1, "class_end_lineno": 78, "func_start_lineno": 56, "func_end_lineno": 74, "func_code": "def format_to_openai_function_messages(\n intermediate_steps: Sequence[Tuple[AgentAction, str]],\n) -> List[BaseMessage]:\n \"\"\"Convert (AgentAction, tool output) tuples into FunctionMessages.\n\n Args:\n intermediate_steps: Steps the LLM has taken to date, along with observations\n\n Returns:\n list of messages to send to the LLM for the next prediction\n Raises:\n ValueError: if the observation cannot be converted to a string.\n \"\"\"\n messages = []\n\n for agent_action, observation in intermediate_steps:\n messages.extend(_convert_agent_action_to_messages(agent_action, observation))\n\n return messages"}], "type": ["function_empty"], "node": ["langchain.agents.format_scratchpad.openai_functions._create_function_message", "langchain.agents.format_scratchpad.openai_functions._convert_agent_action_to_messages", "langchain.agents.format_scratchpad.openai_functions.format_to_openai_function_messages"], "language": "Python", "toolfunc_count": 3, "func_count": 3, "pytest_info": {"total_num": 2, "base_passed_num": 0}} {"id": ["langchain.libs.langchain.langchain.agents.format_scratchpad.tools._create_tool_message", "langchain.libs.langchain.langchain.agents.format_scratchpad.tools.format_to_tool_messages"], "project": "langchain", "origin_file": ["langchain/agents/format_scratchpad/tools.py", "langchain/agents/format_scratchpad/tools.py"], "test_list": ["libs/langchain/tests/unit_tests/agents/format_scratchpad/test_openai_tools.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 63, "func_start_lineno": 14, "func_end_lineno": 39, "func_code": "def _create_tool_message(\n agent_action: ToolAgentAction, observation: str\n) -> ToolMessage:\n \"\"\"Convert agent action and observation into a tool message.\n\n Args:\n agent_action: the tool invocation request from the agent.\n observation: the result of the tool invocation.\n Returns:\n ToolMessage that corresponds to the original tool invocation.\n\n Raises:\n ValueError: if the observation cannot be converted to a string.\n \"\"\"\n if not isinstance(observation, str):\n try:\n content = json.dumps(observation, ensure_ascii=False)\n except Exception:\n content = str(observation)\n else:\n content = observation\n return ToolMessage(\n tool_call_id=agent_action.tool_call_id,\n content=content,\n additional_kwargs={\"name\": agent_action.tool},\n )"}, {"class_start_lineno": 1, "class_end_lineno": 63, "func_start_lineno": 42, "func_end_lineno": 63, "func_code": "def format_to_tool_messages(\n intermediate_steps: Sequence[Tuple[AgentAction, str]],\n) -> List[BaseMessage]:\n \"\"\"Convert (AgentAction, tool output) tuples into ToolMessages.\n\n Args:\n intermediate_steps: Steps the LLM has taken to date, along with observations.\n\n Returns:\n list of messages to send to the LLM for the next prediction.\n\n \"\"\"\n messages = []\n for agent_action, observation in intermediate_steps:\n if isinstance(agent_action, ToolAgentAction):\n new_messages = list(agent_action.message_log) + [\n _create_tool_message(agent_action, observation)\n ]\n messages.extend([new for new in new_messages if new not in messages])\n else:\n messages.append(AIMessage(content=agent_action.log))\n return messages"}], "type": ["function_empty"], "node": ["langchain.agents.format_scratchpad.tools._create_tool_message", "langchain.agents.format_scratchpad.tools.format_to_tool_messages"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 2, "base_passed_num": 0}} {"id": ["langchain.libs.langchain.langchain.evaluation.comparison.eval_chain.PairwiseStringEvalChain::_prepare_input", "langchain.libs.langchain.langchain.evaluation.comparison.eval_chain.PairwiseStringEvalChain::_evaluate_string_pairs"], "project": "langchain", "origin_file": ["langchain/evaluation/comparison/eval_chain.py", "langchain/evaluation/comparison/eval_chain.py", "langchain/evaluation/schema.py"], "test_list": ["libs/langchain/tests/unit_tests/evaluation/comparison/test_eval_chain.py"], "prob_info": [{"class_start_lineno": 154, "class_end_lineno": 391, "func_start_lineno": 274, "func_end_lineno": 300, "func_code": " def _prepare_input(\n self,\n prediction: str,\n prediction_b: str,\n input: Optional[str],\n reference: Optional[str],\n ) -> dict:\n \"\"\"Prepare the input for the chain.\n\n Args:\n prediction (str): The output string from the first model.\n prediction_b (str): The output string from the second model.\n input (str, optional): The input or task string.\n reference (str, optional): The reference string, if any.\n\n Returns:\n dict: The prepared input for the chain.\n\n \"\"\"\n input_ = {\n \"prediction\": prediction,\n \"prediction_b\": prediction_b,\n \"input\": input,\n }\n if self.requires_reference:\n input_[\"reference\"] = reference\n return input_"}, {"class_start_lineno": 154, "class_end_lineno": 391, "func_start_lineno": 309, "func_end_lineno": 349, "func_code": " def _evaluate_string_pairs(\n self,\n *,\n prediction: str,\n prediction_b: str,\n input: Optional[str] = None,\n reference: Optional[str] = None,\n callbacks: Callbacks = None,\n tags: Optional[List[str]] = None,\n metadata: Optional[Dict[str, Any]] = None,\n include_run_info: bool = False,\n **kwargs: Any,\n ) -> dict:\n \"\"\"Evaluate whether output A is preferred to output B.\n\n Args:\n prediction (str): The output string from the first model.\n prediction_b (str): The output string from the second model.\n input (str, optional): The input or task string.\n callbacks (Callbacks, optional): The callbacks to use.\n reference (str, optional): The reference string, if any.\n **kwargs (Any): Additional keyword arguments.\n\n Returns:\n dict: A dictionary containing:\n - reasoning: The reasoning for the preference.\n - value: The preference value, which is either 'A', 'B', or None\n for no preference.\n - score: The preference score, which is 1 for 'A', 0 for 'B',\n and 0.5 for None.\n\n \"\"\"\n input_ = self._prepare_input(prediction, prediction_b, input, reference)\n result = self(\n inputs=input_,\n callbacks=callbacks,\n tags=tags,\n metadata=metadata,\n include_run_info=include_run_info,\n )\n return self._prepare_output(result)"}, {"class_start_lineno": null, "class_end_lineno": null, "func_start_lineno": null, "func_end_lineno": null, "func_code": "未找到 PairwiseStringEvalChain::evaluate_string_pairs"}], "type": ["function_empty"], "node": ["langchain.evaluation.comparison.eval_chain.PairwiseStringEvalChain._prepare_input", "langchain.evaluation.comparison.eval_chain.PairwiseStringEvalChain._evaluate_string_pairs", "langchain.evaluation.schema.PairwiseStringEvalChain.evaluate_string_pairs"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 18, "base_passed_num": 17}} {"id": ["langchain.libs.langchain.langchain.evaluation.scoring.eval_chain.ScoreStringEvalChain::_prepare_input", "langchain.libs.langchain.langchain.evaluation.scoring.eval_chain.ScoreStringEvalChain::_evaluate_strings"], "project": "langchain", "origin_file": ["langchain/evaluation/scoring/eval_chain.py", "langchain/evaluation/scoring/eval_chain.py", "langchain/evaluation/schema.py"], "test_list": ["libs/langchain/tests/unit_tests/evaluation/scoring/test_eval_chain.py"], "prob_info": [{"class_start_lineno": 147, "class_end_lineno": 396, "func_start_lineno": 289, "func_end_lineno": 313, "func_code": " def _prepare_input(\n self,\n prediction: str,\n input: Optional[str],\n reference: Optional[str],\n ) -> dict:\n \"\"\"Prepare the input for the chain.\n\n Args:\n prediction (str): The output string from the first model.\n prediction_b (str): The output string from the second model.\n input (str, optional): The input or task string.\n reference (str, optional): The reference string, if any.\n\n Returns:\n dict: The prepared input for the chain.\n\n \"\"\"\n input_ = {\n \"prediction\": prediction,\n \"input\": input,\n }\n if self.requires_reference:\n input_[\"reference\"] = reference\n return input_"}, {"class_start_lineno": 147, "class_end_lineno": 396, "func_start_lineno": 324, "func_end_lineno": 359, "func_code": " def _evaluate_strings(\n self,\n *,\n prediction: str,\n input: Optional[str] = None,\n reference: Optional[str] = None,\n callbacks: Callbacks = None,\n tags: Optional[List[str]] = None,\n metadata: Optional[Dict[str, Any]] = None,\n include_run_info: bool = False,\n **kwargs: Any,\n ) -> dict:\n \"\"\"Score the output string.\n\n Args:\n prediction (str): The output string from the first model.\n input (str, optional): The input or task string.\n callbacks (Callbacks, optional): The callbacks to use.\n reference (str, optional): The reference string, if any.\n **kwargs (Any): Additional keyword arguments.\n\n Returns:\n dict: A dictionary containing:\n - reasoning: The reasoning for the preference.\n - score: A score between 1 and 10.\n\n \"\"\"\n input_ = self._prepare_input(prediction, input, reference)\n result = self(\n inputs=input_,\n callbacks=callbacks,\n tags=tags,\n metadata=metadata,\n include_run_info=include_run_info,\n )\n return self._prepare_output(result)"}, {"class_start_lineno": null, "class_end_lineno": null, "func_start_lineno": null, "func_end_lineno": null, "func_code": "未找到 ScoreStringEvalChain::evaluate_strings"}], "type": ["function_empty"], "node": ["langchain.evaluation.scoring.eval_chain.ScoreStringEvalChain._prepare_input", "langchain.evaluation.scoring.eval_chain.ScoreStringEvalChain._evaluate_strings", "langchain.evaluation.schema.ScoreStringEvalChain.evaluate_strings"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 3, "base_passed_num": 2}} {"id": ["langchain.libs.langchain.langchain.retrievers.ensemble.unique_by_key", "langchain.libs.langchain.langchain.retrievers.ensemble.EnsembleRetriever::weighted_reciprocal_rank"], "project": "langchain", "origin_file": ["langchain/retrievers/ensemble.py", "langchain/retrievers/ensemble.py"], "test_list": ["libs/langchain/tests/unit_tests/retrievers/test_ensemble.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 337, "func_start_lineno": 40, "func_end_lineno": 54, "func_code": "def unique_by_key(iterable: Iterable[T], key: Callable[[T], H]) -> Iterator[T]:\n \"\"\"Yield unique elements of an iterable based on a key function.\n\n Args:\n iterable: The iterable to filter.\n key: A function that returns a hashable key for each element.\n\n Yields:\n Unique elements of the iterable based on the key function.\n \"\"\"\n seen = set()\n for e in iterable:\n if (k := key(e)) not in seen:\n seen.add(k)\n yield e"}, {"class_start_lineno": 57, "class_end_lineno": 337, "func_start_lineno": 288, "func_end_lineno": 337, "func_code": " def weighted_reciprocal_rank(\n self, doc_lists: List[List[Document]]\n ) -> List[Document]:\n \"\"\"\n Perform weighted Reciprocal Rank Fusion on multiple rank lists.\n You can find more details about RRF here:\n https://plg.uwaterloo.ca/~gvcormac/cormacksigir09-rrf.pdf\n\n Args:\n doc_lists: A list of rank lists, where each rank list contains unique items.\n\n Returns:\n list: The final aggregated list of items sorted by their weighted RRF\n scores in descending order.\n \"\"\"\n if len(doc_lists) != len(self.weights):\n raise ValueError(\n \"Number of rank lists must be equal to the number of weights.\"\n )\n\n # Associate each doc's content with its RRF score for later sorting by it\n # Duplicated contents across retrievers are collapsed & scored cumulatively\n rrf_score: Dict[str, float] = defaultdict(float)\n for doc_list, weight in zip(doc_lists, self.weights):\n for rank, doc in enumerate(doc_list, start=1):\n rrf_score[\n (\n doc.page_content\n if self.id_key is None\n else doc.metadata[self.id_key]\n )\n ] += weight / (rank + self.c)\n\n # Docs are deduplicated by their contents then sorted by their scores\n all_docs = chain.from_iterable(doc_lists)\n sorted_docs = sorted(\n unique_by_key(\n all_docs,\n lambda doc: (\n doc.page_content\n if self.id_key is None\n else doc.metadata[self.id_key]\n ),\n ),\n reverse=True,\n key=lambda doc: rrf_score[\n doc.page_content if self.id_key is None else doc.metadata[self.id_key]\n ],\n )\n return sorted_docs"}], "type": ["function_empty", "Development"], "node": ["langchain.retrievers.ensemble.unique_by_key", "langchain.retrievers.ensemble.EnsembleRetriever.weighted_reciprocal_rank"], "language": "Python", "toolfunc_count": 1, "func_count": 2, "pytest_info": {"total_num": 1, "base_passed_num": 0}} {"id": ["langchain.libs.langchain.langchain.smith.evaluation.runner_utils._get_prompt", "langchain.libs.langchain.langchain.smith.evaluation.runner_utils._get_messages", "langchain.libs.langchain.langchain.smith.evaluation.runner_utils._run_llm"], "project": "langchain", "origin_file": ["langchain/smith/evaluation/runner_utils.py", "langchain/smith/evaluation/runner_utils.py", "langchain/smith/evaluation/runner_utils.py"], "test_list": ["libs/langchain/tests/unit_tests/smith/evaluation/test_runner_utils.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 1523, "func_start_lineno": 232, "func_end_lineno": 279, "func_code": "def _get_prompt(inputs: Dict[str, Any]) -> str:\n \"\"\"Get prompt from inputs.\n\n Args:\n inputs: The input dictionary.\n\n Returns:\n A string prompt.\n Raises:\n InputFormatError: If the input format is invalid.\n \"\"\"\n if not inputs:\n raise InputFormatError(\"Inputs should not be empty.\")\n\n prompts = []\n if \"prompt\" in inputs:\n if not isinstance(inputs[\"prompt\"], str):\n raise InputFormatError(\n f\"Expected string for 'prompt', got {type(inputs['prompt']).__name__}\"\n )\n prompts = [inputs[\"prompt\"]]\n elif \"prompts\" in inputs:\n if not isinstance(inputs[\"prompts\"], list) or not all(\n isinstance(i, str) for i in inputs[\"prompts\"]\n ):\n raise InputFormatError(\n \"Expected list of strings for 'prompts',\"\n f\" got {type(inputs['prompts']).__name__}\"\n )\n prompts = inputs[\"prompts\"]\n elif len(inputs) == 1:\n prompt_ = next(iter(inputs.values()))\n if isinstance(prompt_, str):\n prompts = [prompt_]\n elif isinstance(prompt_, list) and all(isinstance(i, str) for i in prompt_):\n prompts = prompt_\n else:\n raise InputFormatError(f\"LLM Run expects string prompt input. Got {inputs}\")\n else:\n raise InputFormatError(\n f\"LLM Run expects 'prompt' or 'prompts' in inputs. Got {inputs}\"\n )\n if len(prompts) == 1:\n return prompts[0]\n else:\n raise InputFormatError(\n f\"LLM Run expects single prompt input. Got {len(prompts)} prompts.\"\n )"}, {"class_start_lineno": 1, "class_end_lineno": 1523, "func_start_lineno": 292, "func_end_lineno": 328, "func_code": "def _get_messages(inputs: Dict[str, Any]) -> dict:\n \"\"\"Get Chat Messages from inputs.\n\n Args:\n inputs: The input dictionary.\n\n Returns:\n A list of chat messages.\n Raises:\n InputFormatError: If the input format is invalid.\n \"\"\"\n if not inputs:\n raise InputFormatError(\"Inputs should not be empty.\")\n input_copy = inputs.copy()\n if \"messages\" in inputs:\n input_copy[\"input\"] = input_copy.pop(\"messages\")\n elif len(inputs) == 1:\n input_copy[\"input\"] = next(iter(inputs.values()))\n if \"input\" in input_copy:\n raw_messages = input_copy[\"input\"]\n if isinstance(raw_messages, list) and all(\n isinstance(i, dict) for i in raw_messages\n ):\n raw_messages = [raw_messages]\n if len(raw_messages) == 1:\n input_copy[\"input\"] = messages_from_dict(raw_messages[0])\n else:\n raise InputFormatError(\n \"Batch messages not supported. Please provide a\"\n \" single list of messages.\"\n )\n return input_copy\n else:\n raise InputFormatError(\n f\"Chat Run expects single List[dict] or List[List[dict]] 'messages'\"\n f\" input. Got {inputs}\"\n )"}, {"class_start_lineno": 1, "class_end_lineno": 1523, "func_start_lineno": 816, "func_end_lineno": 875, "func_code": "def _run_llm(\n llm: BaseLanguageModel,\n inputs: Dict[str, Any],\n callbacks: Callbacks,\n *,\n tags: Optional[List[str]] = None,\n input_mapper: Optional[Callable[[Dict], Any]] = None,\n metadata: Optional[Dict[str, Any]] = None,\n) -> Union[str, BaseMessage]:\n \"\"\"\n Run the language model on the example.\n\n Args:\n llm: The language model to run.\n inputs: The input dictionary.\n callbacks: The callbacks to use during the run.\n tags: Optional tags to add to the run.\n input_mapper: function to map to the inputs dictionary from an Example\n Returns:\n The LLMResult or ChatResult.\n Raises:\n ValueError: If the LLM type is unsupported.\n InputFormatError: If the input format is invalid.\n \"\"\"\n # Most of this is legacy code; we could probably remove a lot of it.\n if input_mapper is not None:\n prompt_or_messages = input_mapper(inputs)\n if (\n isinstance(prompt_or_messages, str)\n or isinstance(prompt_or_messages, list)\n and all(isinstance(msg, BaseMessage) for msg in prompt_or_messages)\n ):\n llm_output: Union[str, BaseMessage] = llm.invoke(\n prompt_or_messages,\n config=RunnableConfig(\n callbacks=callbacks, tags=tags or [], metadata=metadata or {}\n ),\n )\n else:\n raise InputFormatError(\n \"Input mapper returned invalid format: \"\n f\" {prompt_or_messages}\"\n \"\\nExpected a single string or list of chat messages.\"\n )\n else:\n try:\n llm_prompts = _get_prompt(inputs)\n llm_output = llm.invoke(\n llm_prompts,\n config=RunnableConfig(\n callbacks=callbacks, tags=tags or [], metadata=metadata or {}\n ),\n )\n except InputFormatError:\n llm_inputs = _get_messages(inputs)\n llm_output = llm.invoke(\n **llm_inputs,\n config=RunnableConfig(callbacks=callbacks, metadata=metadata or {}),\n )\n return llm_output"}], "type": ["function_empty"], "node": ["langchain.smith.evaluation.runner_utils._get_prompt", "langchain.smith.evaluation.runner_utils._get_messages", "langchain.smith.evaluation.runner_utils._run_llm"], "language": "Python", "toolfunc_count": 3, "func_count": 3, "pytest_info": {"total_num": 43, "base_passed_num": 36}} {"id": ["open-iris.src.iris.utils.math.estimate_diameter", "open-iris.src.iris.nodes.normalization.nonlinear_normalization.NonlinearNormalization::_generate_correspondences"], "project": "open-iris", "origin_file": ["iris/utils/math.py", "iris/nodes/normalization/nonlinear_normalization.py"], "test_list": ["tests/unit_tests/nodes/normalization/test_nonlinear_normalization.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 203, "func_start_lineno": 38, "func_end_lineno": 50, "func_code": "def estimate_diameter(polygon: np.ndarray) -> float:\n \"\"\"Estimates the diameter of an arbitrary arc by evaluating the maximum distance between any two points on the arc.\n\n Args:\n polygon (np.ndarray): Polygon points.\n\n Returns:\n float: Estimated diameter length.\n\n Reference:\n [1] https://sparrow.dev/pairwise-distance-in-numpy/\n \"\"\"\n return float(np.linalg.norm(polygon[:, None, :] - polygon[None, :, :], axis=-1).max())"}, {"class_start_lineno": 13, "class_end_lineno": 113, "func_start_lineno": 89, "func_end_lineno": 113, "func_code": " def _generate_correspondences(self, pupil_points: np.ndarray, iris_points: np.ndarray) -> np.ndarray:\n \"\"\"Generate corresponding positions in original image.\n\n Args:\n pupil_points (np.ndarray): Pupil bounding points. NumPy array of shape (num_points x 2).\n iris_points (np.ndarray): Iris bounding points. NumPy array of shape (num_points x 2).\n\n Returns:\n np.ndarray: generated corresponding points.\n \"\"\"\n pupil_diameter = math.estimate_diameter(pupil_points)\n iris_diameter = math.estimate_diameter(iris_points)\n p2i_ratio = pupil_diameter / iris_diameter\n\n if p2i_ratio <= 0 or p2i_ratio >= 1:\n raise NormalizationError(f\"Invalid pupil to iris ratio, not in the range (0,1): {p2i_ratio}.\")\n\n src_points = np.array(\n [\n pupil_points + x * (iris_points - pupil_points)\n for x in self.params.intermediate_radiuses[round(100 * (p2i_ratio))]\n ]\n )\n\n return np.round(src_points).astype(int)"}], "type": ["function_empty"], "node": ["iris.utils.math.estimate_diameter", "iris.nodes.normalization.nonlinear_normalization.NonlinearNormalization._generate_correspondences"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 3, "base_passed_num": 2}} {"id": ["open-iris.src.iris.utils.math.area", "open-iris.src.iris.nodes.vectorization.contouring.filter_polygon_areas", "open-iris.src.iris.nodes.vectorization.contouring.ContouringAlgorithm::_filter_contours"], "project": "open-iris", "origin_file": ["iris/utils/math.py", "iris/nodes/vectorization/contouring.py", "iris/nodes/vectorization/contouring.py"], "test_list": ["tests/unit_tests/nodes/vectorization/test_contouring.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 203, "func_start_lineno": 7, "func_end_lineno": 35, "func_code": "def area(array: np.ndarray, signed: bool = False) -> float:\n \"\"\"Shoelace formula for simple polygon area calculation.\n\n WARNING: This formula only works for \"simple polygons\", i.e planar polygon without self-intersection nor holes.\n These conditions are not checked within this function.\n\n Args:\n array (np.ndarray): np array representing a polygon as a list of points, i.e. of shape (_, 2).\n signed (bool): If True, the area is signed, i.e. negative if the polygon is oriented clockwise.\n\n Returns:\n float: Polygon area\n\n Raises:\n ValueError: if the input array does not have shape (_, 2)\n\n References:\n [1] https://en.wikipedia.org/wiki/Shoelace_formula\n [2] https://stackoverflow.com/questions/24467972/calculate-area-of-polygon-given-x-y-coordinates\n \"\"\"\n if len(array.shape) != 2 or array.shape[1] != 2:\n raise ValueError(f\"Unable to determine the area of a polygon with shape {array.shape}. Expecting (_, 2).\")\n\n xs, ys = array.T\n area = 0.5 * (np.dot(xs, np.roll(ys, 1)) - np.dot(ys, np.roll(xs, 1)))\n if not signed:\n area = abs(area)\n\n return float(area)"}, {"class_start_lineno": 1, "class_end_lineno": 133, "func_start_lineno": 13, "func_end_lineno": 35, "func_code": "def filter_polygon_areas(\n polygons: List[np.ndarray], rel_tr: NonNegativeFloat = 0.03, abs_tr: NonNegativeFloat = 0.0\n) -> List[np.ndarray]:\n \"\"\"Filter out polygons whose area is below either an absolute threshold or a fraction of the largest area.\n\n Args:\n polygons (List[np.ndarray]): List of polygons to filter.\n rel_tr (NonNegativeFloat, optional): Relative threshold. Defaults to 0.03.\n abs_tr (NonNegativeFloat, optional): Absolute threshold. Defaults to 0.0.\n\n Returns:\n List[np.ndarray]: Filtered polygons' list.\n \"\"\"\n areas = [area(polygon) if len(polygon) > 2 else 1.0 for polygon in polygons]\n area_factors = np.array(areas) / np.max(areas)\n\n filtered_polygons = [\n polygon\n for area, area_factor, polygon in zip(areas, area_factors, polygons)\n if area > abs_tr and area_factor > rel_tr\n ]\n\n return filtered_polygons"}, {"class_start_lineno": 38, "class_end_lineno": 133, "func_start_lineno": 121, "func_end_lineno": 133, "func_code": " def _filter_contours(self, contours: List[np.ndarray]) -> List[np.ndarray]:\n \"\"\"Filter contours based on predefined filters.\n\n Args:\n contours (List[np.ndarray]): Contours list.\n\n Returns:\n List[np.ndarray]: Filtered list of contours.\n \"\"\"\n for filter_func in self.params.contour_filters:\n contours = filter_func(contours)\n\n return contours"}], "type": ["function_empty"], "node": ["iris.utils.math.area", "iris.nodes.vectorization.contouring.filter_polygon_areas", "iris.nodes.vectorization.contouring.ContouringAlgorithm._filter_contours"], "language": "Python", "toolfunc_count": 3, "func_count": 3, "pytest_info": {"total_num": 12, "base_passed_num": 9}} {"id": ["open-iris.src.iris.utils.math.cartesian2polar", "open-iris.src.iris.nodes.geometry_estimation.linear_extrapolation.LinearExtrapolation::_estimate"], "project": "open-iris", "origin_file": ["iris/utils/math.py", "iris/nodes/geometry_estimation/linear_extrapolation.py"], "test_list": ["tests/unit_tests/nodes/geometry_estimation/test_linear_extrapolation.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 203, "func_start_lineno": 53, "func_end_lineno": 73, "func_code": "def cartesian2polar(xs: np.ndarray, ys: np.ndarray, center_x: float, center_y: float) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"Convert xs and ys cartesian coordinates to polar coordinates.\n\n Args:\n xs (np.ndarray): x values.\n ys (np.ndarray): y values.\n center_x (float): center's x.\n center_y (float): center's y.\n\n Returns:\n Tuple[np.ndarray, np.ndarray]: Converted coordinates (rhos, phis).\n \"\"\"\n x_rel: np.ndarray = xs - center_x\n y_rel: np.ndarray = ys - center_y\n\n C = np.vectorize(complex)(x_rel, y_rel)\n\n rho = np.abs(C)\n phi = np.angle(C) % (2 * np.pi)\n\n return rho, phi"}, {"class_start_lineno": 12, "class_end_lineno": 82, "func_start_lineno": 58, "func_end_lineno": 82, "func_code": " def _estimate(self, vertices: np.ndarray, center_xy: Tuple[float, float]) -> np.ndarray:\n \"\"\"Estimate a circle fit for a single contour.\n\n Args:\n vertices (np.ndarray): Contour's vertices.\n center_xy (Tuple[float, float]): Contour's center position.\n\n Returns:\n np.ndarray: Estimated polygon.\n \"\"\"\n rhos, phis = math.cartesian2polar(vertices[:, 0], vertices[:, 1], *center_xy)\n\n padded_rhos = np.concatenate([rhos, rhos, rhos])\n padded_phis = np.concatenate([phis - 2 * np.pi, phis, phis + 2 * np.pi])\n\n interpolated_phis = np.arange(padded_phis.min(), padded_phis.max(), np.radians(self.params.dphi))\n interpolated_rhos = np.interp(interpolated_phis, xp=padded_phis, fp=padded_rhos, period=2 * np.pi)\n\n mask = (interpolated_phis >= 0) & (interpolated_phis < 2 * np.pi)\n interpolated_phis, interpolated_rhos = interpolated_phis[mask], interpolated_rhos[mask]\n\n xs, ys = math.polar2cartesian(interpolated_rhos, interpolated_phis, *center_xy)\n estimated_vertices = np.column_stack([xs, ys])\n\n return estimated_vertices"}], "type": ["function_empty", "Development"], "node": ["iris.utils.math.cartesian2polar", "iris.nodes.geometry_estimation.linear_extrapolation.LinearExtrapolation._estimate"], "language": "Python", "toolfunc_count": 1, "func_count": 2, "pytest_info": {"total_num": 12, "base_passed_num": 0}} {"id": ["open-iris.src.iris.callbacks.pipeline_trace.PipelineCallTraceStorage::get", "open-iris.src.iris.callbacks.pipeline_trace.PipelineCallTraceStorage::__getitem__"], "project": "open-iris", "origin_file": ["iris/callbacks/pipeline_trace.py", "iris/callbacks/pipeline_trace.py"], "test_list": ["tests/unit_tests/callbacks/test_pipeline_trace.py"], "prob_info": [{"class_start_lineno": 16, "class_end_lineno": 146, "func_start_lineno": 52, "func_end_lineno": 67, "func_code": " def get(self, result_name: str) -> Any:\n \"\"\"Get result_name result.\n\n Args:\n result_name (str): Result name.\n\n Raises:\n PipelineCallTraceStorageError: Raised if result_name is not found.\n\n Returns:\n Any: Result object.\n \"\"\"\n if result_name not in self._storage.keys():\n raise PipelineCallTraceStorageError(f\"Unknown result name: {result_name}\")\n\n return self._storage[result_name]"}, {"class_start_lineno": 16, "class_end_lineno": 146, "func_start_lineno": 30, "func_end_lineno": 42, "func_code": " def __getitem__(self, result_name: str) -> Any:\n \"\"\"Get result_name result.\n\n Args:\n result_name (str): Result name.\n\n Raises:\n PipelineCallTraceStorageError: Raised if result_name is not found.\n\n Returns:\n Any: Result object.\n \"\"\"\n return self.get(result_name)"}], "type": ["function_empty"], "node": ["iris.callbacks.pipeline_trace.PipelineCallTraceStorage.get", "iris.callbacks.pipeline_trace.PipelineCallTraceStorage.__getitem__"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 8, "base_passed_num": 2}} {"id": ["open-iris.src.iris.utils.math.cartesian2polar", "open-iris.src.iris.nodes.eye_properties_estimation.occlusion_calculator.OcclusionCalculator::_get_quantile_points"], "project": "open-iris", "origin_file": ["iris/utils/math.py", "iris/nodes/eye_properties_estimation/occlusion_calculator.py"], "test_list": ["tests/unit_tests/nodes/eye_properties_estimation/test_occlusion_calculator.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 203, "func_start_lineno": 53, "func_end_lineno": 73, "func_code": "def cartesian2polar(xs: np.ndarray, ys: np.ndarray, center_x: float, center_y: float) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"Convert xs and ys cartesian coordinates to polar coordinates.\n\n Args:\n xs (np.ndarray): x values.\n ys (np.ndarray): y values.\n center_x (float): center's x.\n center_y (float): center's y.\n\n Returns:\n Tuple[np.ndarray, np.ndarray]: Converted coordinates (rhos, phis).\n \"\"\"\n x_rel: np.ndarray = xs - center_x\n y_rel: np.ndarray = ys - center_y\n\n C = np.vectorize(complex)(x_rel, y_rel)\n\n rho = np.abs(C)\n phi = np.angle(C) % (2 * np.pi)\n\n return rho, phi"}, {"class_start_lineno": 12, "class_end_lineno": 142, "func_start_lineno": 99, "func_end_lineno": 142, "func_code": " def _get_quantile_points(\n self, iris_coords: np.ndarray, eye_orientation: EyeOrientation, eye_centers: EyeCenters\n ) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"Get those iris's points which fall into a specified quantile.\n\n Args:\n iris_coords (np.ndarray): Iris polygon coordinates.\n eye_orientation: (EyeOrientation): Eye orientation.\n eye_centers: (EyeCenters): Eye centers.\n\n Returns:\n Tuple[np.ndarray, np.ndarray]: Tuple with xs and ys that falls into quantile region.\n \"\"\"\n orientation_angle = np.degrees(eye_orientation.angle)\n num_rotations = -round(orientation_angle * len(iris_coords) / 360.0)\n\n iris_xs, iris_ys = iris_coords[:, 0], iris_coords[:, 1]\n iris_rhos, iris_phis = math.cartesian2polar(iris_xs, iris_ys, eye_centers.iris_x, eye_centers.iris_y)\n\n iris_phis = np.roll(iris_phis, num_rotations, axis=0)\n iris_rhos = np.roll(iris_rhos, num_rotations, axis=0)\n\n scaled_quantile = round(self.params.quantile_angle * len(iris_coords) / 360.0)\n\n phis2mask = np.concatenate(\n [\n iris_phis[:scaled_quantile],\n iris_phis[-scaled_quantile:],\n iris_phis[len(iris_phis) // 2 : len(iris_phis) // 2 + scaled_quantile],\n iris_phis[len(iris_phis) // 2 - scaled_quantile : len(iris_phis) // 2],\n ]\n )\n rhos2mask = np.concatenate(\n [\n iris_rhos[:scaled_quantile],\n iris_rhos[-scaled_quantile:],\n iris_rhos[len(iris_rhos) // 2 : len(iris_rhos) // 2 + scaled_quantile],\n iris_rhos[len(iris_rhos) // 2 - scaled_quantile : len(iris_rhos) // 2],\n ]\n )\n phis2mask, rhos2mask = zip(*sorted(zip(phis2mask, rhos2mask)))\n xs2mask, ys2mask = math.polar2cartesian(rhos2mask, phis2mask, eye_centers.iris_x, eye_centers.iris_y)\n\n return xs2mask, ys2mask"}], "type": ["function_empty", "Development"], "node": ["iris.utils.math.cartesian2polar", "iris.nodes.eye_properties_estimation.occlusion_calculator.OcclusionCalculator._get_quantile_points"], "language": "Python", "toolfunc_count": 1, "func_count": 2, "pytest_info": {"total_num": 19, "base_passed_num": 1}} {"id": ["open-iris.src.iris.nodes.eye_properties_estimation.bisectors_method.BisectorsMethod::_calculate_perpendicular_bisectors", "open-iris.src.iris.nodes.eye_properties_estimation.bisectors_method.BisectorsMethod::_find_center_coords"], "project": "open-iris", "origin_file": ["iris/nodes/eye_properties_estimation/bisectors_method.py", "iris/nodes/eye_properties_estimation/bisectors_method.py"], "test_list": ["tests/unit_tests/nodes/eye_properties_estimation/test_bisectors_method.py"], "prob_info": [{"class_start_lineno": 11, "class_end_lineno": 170, "func_start_lineno": 84, "func_end_lineno": 140, "func_code": " def _calculate_perpendicular_bisectors(\n self, polygon: np.ndarray, min_distance_between_sector_points_in_px: float\n ) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"Calculate the perpendicular bisector of self.params.num_bisectors randomly chosen points from a polygon's vertices.\n A pair of points is used if their distance is larger then min_distance_between_sector_points_in_px.\n\n Args:\n polygon (np.ndarray): np.ndarray based on which we are searching the center of a circular shape.\n min_distance_between_sector_points_in_px (float): Minimum distance between sector points.\n\n Raises:\n EyeCentersEstimationError: Raised if not able to find enough random pairs of points on the arc with a large enough distance!\n\n Returns:\n Tuple[np.ndarray, np.ndarray]: Calculated perpendicular bisectors.\n \"\"\"\n np.random.seed(142857)\n\n bisectors_first_points = np.empty([0, 2])\n bisectors_second_points = np.empty([0, 2])\n for _ in range(self.params.max_iterations):\n random_indices = np.random.choice(len(polygon), size=(self.params.num_bisectors, 2))\n\n first_drawn_points = polygon[random_indices[:, 0]]\n second_drawn_points = polygon[random_indices[:, 1]]\n\n norms = np.linalg.norm(first_drawn_points - second_drawn_points, axis=1)\n mask = norms > min_distance_between_sector_points_in_px\n\n bisectors_first_points = np.vstack([bisectors_first_points, first_drawn_points[mask]])\n bisectors_second_points = np.vstack([bisectors_second_points, second_drawn_points[mask]])\n\n if len(bisectors_first_points) >= self.params.num_bisectors:\n break\n else:\n raise EyeCentersEstimationError(\n \"Not able to find enough random pairs of points on the arc with a large enough distance!\"\n )\n\n bisectors_first_points = bisectors_first_points[: self.params.num_bisectors]\n bisectors_second_points = bisectors_second_points[: self.params.num_bisectors]\n\n bisectors_center = (bisectors_first_points + bisectors_second_points) / 2\n\n # Flip xs with ys and flip sign of on of them to create a 90deg rotation\n inv_bisectors_center_slope = np.fliplr(bisectors_second_points - bisectors_first_points)\n inv_bisectors_center_slope[:, 1] = -inv_bisectors_center_slope[:, 1]\n\n # Add perpendicular vector to center and normalize\n norm = np.linalg.norm(inv_bisectors_center_slope, axis=1)\n inv_bisectors_center_slope[:, 0] /= norm\n inv_bisectors_center_slope[:, 1] /= norm\n\n first_bisectors_point = bisectors_center - inv_bisectors_center_slope\n second_bisectors_point = bisectors_center + inv_bisectors_center_slope\n\n return first_bisectors_point, second_bisectors_point"}, {"class_start_lineno": 11, "class_end_lineno": 170, "func_start_lineno": 66, "func_end_lineno": 82, "func_code": " def _find_center_coords(self, polygon: np.ndarray, diameter: float) -> Tuple[float, float]:\n \"\"\"Find center coordinates of a polygon.\n\n Args:\n polygon (np.ndarray): np.ndarray.\n diameter (float): diameter of the polygon.\n\n Returns:\n Tuple[float, float]: Tuple with the center location coordinates (x, y).\n \"\"\"\n min_distance_between_sector_points_in_px = self.params.min_distance_between_sector_points * diameter\n\n first_bisectors_point, second_bisectors_point = self._calculate_perpendicular_bisectors(\n polygon, min_distance_between_sector_points_in_px\n )\n\n return self._find_best_intersection(first_bisectors_point, second_bisectors_point)"}], "type": ["function_empty", "Development"], "node": ["iris.nodes.eye_properties_estimation.bisectors_method.BisectorsMethod._calculate_perpendicular_bisectors", "iris.nodes.eye_properties_estimation.bisectors_method.BisectorsMethod._find_center_coords"], "language": "Python", "toolfunc_count": 1, "func_count": 2, "pytest_info": {"total_num": 7, "base_passed_num": 4}} {"id": ["open-iris.src.iris.utils.math.cartesian2polar", "open-iris.src.iris.nodes.geometry_refinement.smoothing.Smoothing::_cut_into_arcs", "open-iris.src.iris.nodes.geometry_refinement.smoothing.Smoothing::_smooth_arc", "open-iris.src.iris.nodes.geometry_refinement.smoothing.Smoothing::_smooth_circular_shape"], "project": "open-iris", "origin_file": ["iris/utils/math.py", "iris/nodes/geometry_refinement/smoothing.py", "iris/nodes/geometry_refinement/smoothing.py", "iris/nodes/geometry_refinement/smoothing.py"], "test_list": ["tests/unit_tests/nodes/geometry_refinement/test_smoothing.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 203, "func_start_lineno": 53, "func_end_lineno": 73, "func_code": "def cartesian2polar(xs: np.ndarray, ys: np.ndarray, center_x: float, center_y: float) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"Convert xs and ys cartesian coordinates to polar coordinates.\n\n Args:\n xs (np.ndarray): x values.\n ys (np.ndarray): y values.\n center_x (float): center's x.\n center_y (float): center's y.\n\n Returns:\n Tuple[np.ndarray, np.ndarray]: Converted coordinates (rhos, phis).\n \"\"\"\n x_rel: np.ndarray = xs - center_x\n y_rel: np.ndarray = ys - center_y\n\n C = np.vectorize(complex)(x_rel, y_rel)\n\n rho = np.abs(C)\n phi = np.angle(C) % (2 * np.pi)\n\n return rho, phi"}, {"class_start_lineno": 12, "class_end_lineno": 256, "func_start_lineno": 84, "func_end_lineno": 119, "func_code": " def _cut_into_arcs(self, polygon: np.ndarray, center_xy: Tuple[float, float]) -> Tuple[List[np.ndarray], int]:\n \"\"\"Cut contour into arcs.\n\n Args:\n polygon (np.ndarray): Contour polygon.\n center_xy (Tuple[float, float]): Polygon's center.\n\n Returns:\n Tuple[List[np.ndarray], int]: Tuple with: (list of list of vertices, number of gaps detected in a contour).\n \"\"\"\n rho, phi = math.cartesian2polar(polygon[:, 0], polygon[:, 1], *center_xy)\n phi, rho = self._sort_two_arrays(phi, rho)\n\n differences = np.abs(phi - np.roll(phi, -1))\n # True distance between first and last point\n differences[-1] = 2 * np.pi - differences[-1]\n\n gap_indices = np.argwhere(differences > np.radians(self.params.gap_threshold)).flatten()\n\n if gap_indices.size < 2:\n return [polygon], gap_indices.size\n\n gap_indices += 1\n phi, rho = np.split(phi, gap_indices), np.split(rho, gap_indices)\n\n arcs = [\n np.column_stack(math.polar2cartesian(rho_coords, phi_coords, *center_xy))\n for rho_coords, phi_coords in zip(rho, phi)\n ]\n\n # Connect arc which lies between 0 and 2π.\n if len(arcs) == gap_indices.size + 1:\n arcs[0] = np.vstack([arcs[0], arcs[-1]])\n arcs = arcs[:-1]\n\n return arcs, gap_indices.size"}, {"class_start_lineno": 12, "class_end_lineno": 256, "func_start_lineno": 121, "func_end_lineno": 144, "func_code": " def _smooth_arc(self, vertices: np.ndarray, center_xy: Tuple[float, float]) -> np.ndarray:\n \"\"\"Smooth a single contour arc.\n\n Args:\n vertices (np.ndarray): Arc's vertices.\n center_xy (Tuple[float, float]): Center of an entire contour.\n\n Returns:\n np.ndarray: Smoothed arc's vertices.\n \"\"\"\n rho, phi = math.cartesian2polar(vertices[:, 0], vertices[:, 1], *center_xy)\n phi, rho = self._sort_two_arrays(phi, rho)\n\n idx = self._find_start_index(phi)\n offset = phi[idx]\n relative_phi = (phi - offset) % (2 * np.pi)\n\n smoothed_relative_phi, smoothed_rho = self._smooth_array(relative_phi, rho)\n\n smoothed_phi = (smoothed_relative_phi + offset) % (2 * np.pi)\n\n x_smoothed, y_smoothed = math.polar2cartesian(smoothed_rho, smoothed_phi, *center_xy)\n\n return np.column_stack([x_smoothed, y_smoothed])"}, {"class_start_lineno": 12, "class_end_lineno": 256, "func_start_lineno": 146, "func_end_lineno": 168, "func_code": " def _smooth_circular_shape(self, vertices: np.ndarray, center_xy: Tuple[float, float]) -> np.ndarray:\n \"\"\"Smooth arc in a form of a circular shape.\n\n Args:\n vertices (np.ndarray): Arc's vertices.\n center_xy (Tuple[float, float]): Center of an entire contour.\n\n Returns:\n np.ndarray: Smoothed arc's vertices.\n \"\"\"\n rho, phi = math.cartesian2polar(vertices[:, 0], vertices[:, 1], *center_xy)\n\n padded_phi = np.concatenate([phi - 2 * np.pi, phi, phi + 2 * np.pi])\n padded_rho = np.concatenate([rho, rho, rho])\n\n smoothed_phi, smoothed_rho = self._smooth_array(padded_phi, padded_rho)\n\n mask = (smoothed_phi >= 0) & (smoothed_phi < 2 * np.pi)\n rho_smoothed, phi_smoothed = smoothed_rho[mask], smoothed_phi[mask]\n\n x_smoothed, y_smoothed = math.polar2cartesian(rho_smoothed, phi_smoothed, *center_xy)\n\n return np.column_stack([x_smoothed, y_smoothed])"}], "type": ["function_empty", "Development"], "node": ["iris.utils.math.cartesian2polar", "iris.nodes.geometry_refinement.smoothing.Smoothing._cut_into_arcs", "iris.nodes.geometry_refinement.smoothing.Smoothing._smooth_arc", "iris.nodes.geometry_refinement.smoothing.Smoothing._smooth_circular_shape"], "language": "Python", "toolfunc_count": 3, "func_count": 4, "pytest_info": {"total_num": 12, "base_passed_num": 5}} {"id": ["open-iris.src.iris.pipelines.iris_pipeline.IRISPipeline::instanciate_class", "open-iris.src.iris.pipelines.iris_pipeline.IRISPipeline::instanciate_pipeline", "open-iris.src.iris.pipelines.iris_pipeline.IRISPipeline::instanciate_node", "open-iris.src.iris.pipelines.iris_pipeline.IRISPipeline::instanciate_nodes"], "project": "open-iris", "origin_file": ["iris/pipelines/iris_pipeline.py", "iris/pipelines/iris_pipeline.py", "iris/pipelines/iris_pipeline.py", "iris/pipelines/iris_pipeline.py"], "test_list": ["tests/unit_tests/pipelines/test_iris_pipeline.py"], "prob_info": [{"class_start_lineno": 27, "class_end_lineno": 324, "func_start_lineno": 225, "func_end_lineno": 245, "func_code": " def instanciate_class(self, class_name: str, kwargs: Dict[str, Any]) -> Callable:\n \"\"\"Instanciate a class from its string definition and its kwargs.\n\n This function relies on pydoc.locate, a safe way to instanciate a class from its string definition, which itself relies on pydoc.safe_import.\n\n Args:\n class_name (str): name of the class.\n kwargs (Dict): kwargs to pass to the class at instanciation time\n\n Returns:\n Callable: the instanciated class\n\n Raises:\n IRISPipelineError: Raised if the class cannot be located.\n \"\"\"\n object_class = pydoc.locate(class_name)\n\n if object_class is None:\n raise IRISPipelineError(f\"Could not locate class {class_name}\")\n\n return object_class(**kwargs)"}, {"class_start_lineno": 27, "class_end_lineno": 324, "func_start_lineno": 179, "func_end_lineno": 200, "func_code": " def instanciate_pipeline(self) -> List[PipelineNode]:\n \"\"\"Given a list of PipelineNodes, crawl the parameters and instanciate the PipelineClass available.\n\n Returns:\n List[PipelineNode]: pipeline with instanciated parameters\n \"\"\"\n instanciated_pipeline = []\n for node in self.params.pipeline:\n current_node = node\n for param_name, param_value in node.algorithm.params.items():\n if isinstance(param_value, (tuple, list)):\n for i, value in enumerate(param_value):\n if isinstance(value, PipelineClass):\n current_node.algorithm.params[param_name][i] = self.instanciate_class(\n class_name=value.class_name, kwargs=value.params\n )\n elif isinstance(param_value, PipelineClass):\n current_node.algorithm.params[param_name] = self.instanciate_class(\n class_name=param_value.class_name, kwargs=param_value.params\n )\n instanciated_pipeline.append(current_node)\n return instanciated_pipeline"}, {"class_start_lineno": 27, "class_end_lineno": 324, "func_start_lineno": 202, "func_end_lineno": 223, "func_code": " def instanciate_node(\n self, node_class: str, algorithm_params: Dict[str, Any], callbacks: Optional[List[PipelineClass]]\n ) -> Algorithm:\n \"\"\"Instanciate an Algorithm from its class, kwargs and optional Callbacks.\n\n NOTE: All callbacks of type listed in self.env.disabled_qa will be filtered out. This allows one config file to be used in various QA standards levels.\n\n Args:\n node_class (str): Node's class.\n algorithm_params (Dict[str, Any]): Node's kwargs.\n callbacks (Optional[List[PipelineClass]]): list of callbacks.\n\n Returns:\n Algorithm: instanciated node.\n \"\"\"\n if callbacks is not None and len(callbacks):\n instanciated_callbacks = [self.instanciate_class(cb.class_name, cb.params) for cb in callbacks]\n instanciated_callbacks = [cb for cb in instanciated_callbacks if type(cb) not in self.env.disabled_qa]\n\n algorithm_params = {**algorithm_params, **{\"callbacks\": instanciated_callbacks}}\n\n return self.instanciate_class(node_class, algorithm_params)"}, {"class_start_lineno": 27, "class_end_lineno": 324, "func_start_lineno": 159, "func_end_lineno": 177, "func_code": " def instanciate_nodes(self) -> Dict[str, Algorithm]:\n \"\"\"Given a list of PipelineNode, return the associated instanciated nodes.\n\n NOTE: All nodes of type listed in self.env.disabled_qa will be filtered out. This allows one config file to be used in various QA standards levels.\n\n Returns:\n Dict[str, Algorithm]: instanciated nodes.\n \"\"\"\n instanciated_pipeline = self.instanciate_pipeline()\n nodes = {\n node.name: self.instanciate_node(\n node_class=node.algorithm.class_name,\n algorithm_params=node.algorithm.params,\n callbacks=node.callbacks,\n )\n for node in instanciated_pipeline\n }\n nodes = {node_name: node for node_name, node in nodes.items() if type(node) not in self.env.disabled_qa}\n return nodes"}], "type": ["function_empty", "Development"], "node": ["iris.pipelines.iris_pipeline.IRISPipeline.instanciate_class", "iris.pipelines.iris_pipeline.IRISPipeline.instanciate_pipeline", "iris.pipelines.iris_pipeline.IRISPipeline.instanciate_node", "iris.pipelines.iris_pipeline.IRISPipeline.instanciate_nodes"], "language": "Python", "toolfunc_count": 3, "func_count": 4, "pytest_info": {"total_num": 33, "base_passed_num": 0}} {"id": ["open-iris.src.iris.io.validators.is_binary", "open-iris.src.iris.nodes.binarization.specular_reflection_detection.SpecularReflectionDetection::run"], "project": "open-iris", "origin_file": ["iris/io/validators.py", "iris/nodes/binarization/specular_reflection_detection.py"], "test_list": ["tests/unit_tests/nodes/binarization/test_specular_reflection_detection.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 277, "func_start_lineno": 40, "func_end_lineno": 57, "func_code": "def is_binary(cls: type, v: np.ndarray, field: fields.ModelField) -> np.ndarray:\n \"\"\"Check if array has only boolean values, i.e. is binary.\n\n Args:\n cls (type): Class type.\n v (np.ndarray): Value to check.\n field (fields.ModelField): Field descriptor.\n\n Raises:\n ValueError: Exception raised if array doesn't contain bool datatypes.\n\n Returns:\n np.ndarray: `v` sent for further processing.\n \"\"\"\n if v.dtype != np.dtype(\"bool\"):\n raise ValueError(f\"{cls.__name__}: {field.name} must be binary. got dtype {v.dtype}\")\n\n return v"}, {"class_start_lineno": 8, "class_end_lineno": 40, "func_start_lineno": 26, "func_end_lineno": 40, "func_code": " def run(self, ir_image: IRImage) -> NoiseMask:\n \"\"\"Thresholds an IRImage to detect Specular Reflection.\n\n Args:\n ir_image (IRImage): Infrared image object.\n\n Returns:\n NoiseMask: a binary map of the thresholded IRImage.\n \"\"\"\n _, reflection_segmap = cv2.threshold(\n ir_image.img_data, self.params.reflection_threshold, 255, cv2.THRESH_BINARY\n )\n reflection_segmap = (reflection_segmap / 255.0).astype(bool)\n\n return NoiseMask(mask=reflection_segmap)"}], "type": ["function_empty"], "node": ["iris.io.validators.is_binary", "iris.nodes.binarization.specular_reflection_detection.SpecularReflectionDetection.run"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 4, "base_passed_num": 0}} {"id": ["open-iris.src.iris.nodes.eye_properties_estimation.bisectors_method.BisectorsMethod::_calculate_perpendicular_bisectors", "open-iris.src.iris.nodes.eye_properties_estimation.bisectors_method.BisectorsMethod::_find_center_coords"], "project": "open-iris", "origin_file": ["iris/nodes/eye_properties_estimation/bisectors_method.py", "iris/nodes/eye_properties_estimation/bisectors_method.py"], "test_list": ["tests/unit_tests/nodes/eye_properties_estimation/test_pupil_iris_property_calculator.py"], "prob_info": [{"class_start_lineno": 11, "class_end_lineno": 170, "func_start_lineno": 84, "func_end_lineno": 140, "func_code": " def _calculate_perpendicular_bisectors(\n self, polygon: np.ndarray, min_distance_between_sector_points_in_px: float\n ) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"Calculate the perpendicular bisector of self.params.num_bisectors randomly chosen points from a polygon's vertices.\n A pair of points is used if their distance is larger then min_distance_between_sector_points_in_px.\n\n Args:\n polygon (np.ndarray): np.ndarray based on which we are searching the center of a circular shape.\n min_distance_between_sector_points_in_px (float): Minimum distance between sector points.\n\n Raises:\n EyeCentersEstimationError: Raised if not able to find enough random pairs of points on the arc with a large enough distance!\n\n Returns:\n Tuple[np.ndarray, np.ndarray]: Calculated perpendicular bisectors.\n \"\"\"\n np.random.seed(142857)\n\n bisectors_first_points = np.empty([0, 2])\n bisectors_second_points = np.empty([0, 2])\n for _ in range(self.params.max_iterations):\n random_indices = np.random.choice(len(polygon), size=(self.params.num_bisectors, 2))\n\n first_drawn_points = polygon[random_indices[:, 0]]\n second_drawn_points = polygon[random_indices[:, 1]]\n\n norms = np.linalg.norm(first_drawn_points - second_drawn_points, axis=1)\n mask = norms > min_distance_between_sector_points_in_px\n\n bisectors_first_points = np.vstack([bisectors_first_points, first_drawn_points[mask]])\n bisectors_second_points = np.vstack([bisectors_second_points, second_drawn_points[mask]])\n\n if len(bisectors_first_points) >= self.params.num_bisectors:\n break\n else:\n raise EyeCentersEstimationError(\n \"Not able to find enough random pairs of points on the arc with a large enough distance!\"\n )\n\n bisectors_first_points = bisectors_first_points[: self.params.num_bisectors]\n bisectors_second_points = bisectors_second_points[: self.params.num_bisectors]\n\n bisectors_center = (bisectors_first_points + bisectors_second_points) / 2\n\n # Flip xs with ys and flip sign of on of them to create a 90deg rotation\n inv_bisectors_center_slope = np.fliplr(bisectors_second_points - bisectors_first_points)\n inv_bisectors_center_slope[:, 1] = -inv_bisectors_center_slope[:, 1]\n\n # Add perpendicular vector to center and normalize\n norm = np.linalg.norm(inv_bisectors_center_slope, axis=1)\n inv_bisectors_center_slope[:, 0] /= norm\n inv_bisectors_center_slope[:, 1] /= norm\n\n first_bisectors_point = bisectors_center - inv_bisectors_center_slope\n second_bisectors_point = bisectors_center + inv_bisectors_center_slope\n\n return first_bisectors_point, second_bisectors_point"}, {"class_start_lineno": 11, "class_end_lineno": 170, "func_start_lineno": 66, "func_end_lineno": 82, "func_code": " def _find_center_coords(self, polygon: np.ndarray, diameter: float) -> Tuple[float, float]:\n \"\"\"Find center coordinates of a polygon.\n\n Args:\n polygon (np.ndarray): np.ndarray.\n diameter (float): diameter of the polygon.\n\n Returns:\n Tuple[float, float]: Tuple with the center location coordinates (x, y).\n \"\"\"\n min_distance_between_sector_points_in_px = self.params.min_distance_between_sector_points * diameter\n\n first_bisectors_point, second_bisectors_point = self._calculate_perpendicular_bisectors(\n polygon, min_distance_between_sector_points_in_px\n )\n\n return self._find_best_intersection(first_bisectors_point, second_bisectors_point)"}], "type": ["function_empty", "Development"], "node": ["iris.nodes.eye_properties_estimation.bisectors_method.BisectorsMethod._calculate_perpendicular_bisectors", "iris.nodes.eye_properties_estimation.bisectors_method.BisectorsMethod._find_center_coords"], "language": "Python", "toolfunc_count": 1, "func_count": 2, "pytest_info": {"total_num": 13, "base_passed_num": 8}} {"id": ["rdt.rdt.transformers.utils.strings_from_regex", "rdt.rdt.transformers.id.RegexGenerator::__setstate__"], "project": "rdt", "origin_file": ["rdt/transformers/utils.py", "rdt/transformers/id.py"], "test_list": ["tests/unit/transformers/test___init__.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 385, "func_start_lineno": 141, "func_end_lineno": 171, "func_code": "def strings_from_regex(regex, max_repeat=16):\n \"\"\"Generate strings that match the given regular expression.\n\n The output is a generator that produces regular expressions that match\n the indicated regular expressions alongside an integer indicating the\n total length of the generator.\n\n WARNING: Subpatterns are currently not supported.\n\n Args:\n regex (str):\n String representing a valid python regular expression.\n max_repeat (int):\n Maximum number of repetitions to produce when the regular\n expression allows an infinte amount. Defaults to 16.\n\n Returns:\n tuple:\n * Generator that produces strings that match the given regex.\n * Total length of the generator.\n \"\"\"\n parsed = sre_parse.parse(regex, flags=sre_parse.SRE_FLAG_UNICODE)\n generators = []\n sizes = []\n for option, args in reversed(parsed):\n if option != sre_parse.AT:\n generator, size = _GENERATORS[option](args, max_repeat)\n generators.append((generator, option, args))\n sizes.append(size)\n\n return _from_generators(generators, max_repeat), np.prod(sizes, dtype=np.complex128).real"}, {"class_start_lineno": 93, "class_end_lineno": 285, "func_start_lineno": 127, "func_end_lineno": 142, "func_code": " def __setstate__(self, state):\n \"\"\"Set the generator when pickling.\"\"\"\n generator_size = state.get('generator_size')\n generated = state.get('generated')\n generator, size = strings_from_regex(state.get('regex_format'))\n if generator_size is None:\n state['generator_size'] = size\n if generated is None:\n state['generated'] = 0\n\n if generated:\n for _ in range(generated):\n next(generator)\n\n state['generator'] = generator\n self.__dict__ = state"}], "type": ["Development"], "node": ["rdt.transformers.utils.strings_from_regex", "rdt.transformers.id.RegexGenerator.__setstate__"], "language": "Python", "toolfunc_count": 0, "func_count": 2, "pytest_info": {"total_num": 5, "base_passed_num": 4}} {"id": ["rdt.rdt.transformers.null.NullTransformer::_get_missing_value_replacement", "rdt.rdt.transformers.null.NullTransformer::fit", "rdt.rdt.transformers.boolean.BinaryEncoder::_fit"], "project": "rdt", "origin_file": ["rdt/transformers/null.py", "rdt/transformers/null.py", "rdt/transformers/boolean.py"], "test_list": ["tests/unit/transformers/test_boolean.py"], "prob_info": [{"class_start_lineno": 13, "class_end_lineno": 194, "func_start_lineno": 60, "func_end_lineno": 93, "func_code": " def _get_missing_value_replacement(self, data):\n \"\"\"Get the fill value to use for the given data.\n\n Args:\n data (pd.Series):\n The data that is being transformed.\n\n Return:\n object:\n The fill value that needs to be used.\n\n Raise:\n TransformerInputError:\n Error raised when data only contains nans and ``_missing_value_replacement``\n is set to 'mean' or 'mode'.\n \"\"\"\n if self._missing_value_replacement is None:\n return None\n\n if self._missing_value_replacement in {'mean', 'mode', 'random'} and pd.isna(data).all():\n msg = (\n f\"'missing_value_replacement' cannot be set to '{self._missing_value_replacement}'\"\n ' when the provided data only contains NaNs. Using 0 instead.'\n )\n LOGGER.info(msg)\n return 0\n\n if self._missing_value_replacement == 'mean':\n return data.mean()\n\n if self._missing_value_replacement == 'mode':\n return data.mode(dropna=True)[0]\n\n return self._missing_value_replacement"}, {"class_start_lineno": 13, "class_end_lineno": 194, "func_start_lineno": 95, "func_end_lineno": 122, "func_code": " def fit(self, data):\n \"\"\"Fit the transformer to the data.\n\n Evaluate if the transformer has to create the null column or not.\n\n Args:\n data (pandas.Series):\n Data to transform.\n \"\"\"\n self._missing_value_replacement = self._get_missing_value_replacement(data)\n if self._missing_value_replacement == 'random':\n self._min_value = data.min()\n self._max_value = data.max()\n\n if self._missing_value_generation is not None:\n null_values = data.isna().to_numpy()\n self.nulls = null_values.any()\n\n if not self.nulls and self.models_missing_values():\n self._missing_value_generation = None\n guidance_message = (\n f'Guidance: There are no missing values in column {data.name}. '\n 'Extra column not created.'\n )\n LOGGER.info(guidance_message)\n\n if self._missing_value_generation == 'random':\n self._null_percentage = null_values.sum() / len(data)"}, {"class_start_lineno": 10, "class_end_lineno": 129, "func_start_lineno": 54, "func_end_lineno": 69, "func_code": " def _fit(self, data):\n \"\"\"Fit the transformer to the data.\n\n Args:\n data (pandas.Series):\n Data to fit to.\n \"\"\"\n self.null_transformer = NullTransformer(\n self.missing_value_replacement, self.missing_value_generation\n )\n self.null_transformer.fit(data)\n if self.null_transformer.models_missing_values():\n self.output_properties['is_null'] = {\n 'sdtype': 'float',\n 'next_transformer': None,\n }"}], "type": ["function_empty", "Development"], "node": ["rdt.transformers.null.NullTransformer._get_missing_value_replacement", "rdt.transformers.null.NullTransformer.fit", "rdt.transformers.boolean.BinaryEncoder._fit"], "language": "Python", "toolfunc_count": 2, "func_count": 3, "pytest_info": {"total_num": 16, "base_passed_num": 13}} {"id": ["rdt.rdt.transformers.utils.check_nan_in_transform", "rdt.rdt.transformers.categorical.UniformEncoder::_reverse_transform", "rdt.rdt.transformers.categorical.OneHotEncoder::_reverse_transform", "rdt.rdt.transformers.categorical.LabelEncoder::_reverse_transform"], "project": "rdt", "origin_file": ["rdt/transformers/utils.py", "rdt/transformers/categorical.py", "rdt/transformers/categorical.py", "rdt/transformers/categorical.py"], "test_list": ["tests/unit/transformers/test_categorical.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 385, "func_start_lineno": 208, "func_end_lineno": 228, "func_code": "def check_nan_in_transform(data, dtype):\n \"\"\"Check if there are null values in the transformed data.\n\n Args:\n data (pd.Series or numpy.ndarray):\n Data that has been transformed.\n dtype (str):\n Data type of the transformed data.\n \"\"\"\n if pd.isna(data).any().any():\n message = (\n 'There are null values in the transformed data. The reversed '\n 'transformed data will contain null values'\n )\n is_integer = pd.api.types.is_integer_dtype(dtype)\n if is_integer:\n message += \" of type 'float'.\"\n else:\n message += '.'\n\n warnings.warn(message)"}, {"class_start_lineno": 21, "class_end_lineno": 223, "func_start_lineno": 192, "func_end_lineno": 223, "func_code": " def _reverse_transform(self, data):\n \"\"\"Convert float values back to the original categorical values.\n\n Args:\n data (pandas.Series):\n Data to revert.\n\n Returns:\n pandas.Series\n \"\"\"\n check_nan_in_transform(data, self.dtype)\n data = data.clip(0, 1)\n bins = [0]\n labels = []\n nan_name = 'NaN'\n while nan_name in self.intervals.keys():\n nan_name += '_'\n\n for key, interval in self.intervals.items():\n bins.append(interval[1])\n if pd.isna(key):\n labels.append(nan_name)\n else:\n labels.append(key)\n\n result = pd.cut(data, bins=bins, labels=labels, include_lowest=True)\n if nan_name in result.cat.categories:\n result = result.cat.remove_categories(nan_name)\n\n result = try_convert_to_dtype(result, self.dtype)\n\n return result"}, {"class_start_lineno": 562, "class_end_lineno": 705, "func_start_lineno": 684, "func_end_lineno": 705, "func_code": " def _reverse_transform(self, data):\n \"\"\"Convert float values back to the original categorical values.\n\n Args:\n data (pd.Series or numpy.ndarray):\n Data to revert.\n\n Returns:\n pandas.Series\n \"\"\"\n check_nan_in_transform(data, self.dtype)\n if not isinstance(data, np.ndarray):\n data = data.to_numpy()\n\n if data.ndim == 1:\n data = data.reshape(-1, 1)\n\n indices = np.argmax(data, axis=1)\n result = pd.Series(indices).map(self.dummies.__getitem__)\n result = try_convert_to_dtype(result, self.dtype)\n\n return result"}, {"class_start_lineno": 708, "class_end_lineno": 845, "func_start_lineno": 827, "func_end_lineno": 845, "func_code": " def _reverse_transform(self, data):\n \"\"\"Convert float values back to the original categorical values.\n\n Args:\n data (pd.Series or numpy.ndarray):\n Data to revert.\n\n Returns:\n pandas.Series\n \"\"\"\n check_nan_in_transform(data, self.dtype)\n if self.add_noise:\n data = np.floor(data)\n\n data = data.clip(min(self.values_to_categories), max(self.values_to_categories))\n data = data.round().map(self.values_to_categories)\n data = try_convert_to_dtype(data, self.dtype)\n\n return data"}], "type": ["function_empty", "Development"], "node": ["rdt.transformers.utils.check_nan_in_transform", "rdt.transformers.categorical.UniformEncoder._reverse_transform", "rdt.transformers.categorical.OneHotEncoder._reverse_transform", "rdt.transformers.categorical.LabelEncoder._reverse_transform"], "language": "Python", "toolfunc_count": 3, "func_count": 4, "pytest_info": {"total_num": 95, "base_passed_num": 85}} {"id": ["rdt.rdt.transformers.null.NullTransformer::_get_missing_value_replacement", "rdt.rdt.transformers.null.NullTransformer::fit", "rdt.rdt.transformers.datetime.UnixTimestampEncoder::_convert_to_datetime", "rdt.rdt.transformers.datetime.UnixTimestampEncoder::_transform"], "project": "rdt", "origin_file": ["rdt/transformers/null.py", "rdt/transformers/null.py", "rdt/transformers/datetime.py", "rdt/transformers/datetime.py", "rdt/transformers/datetime.py"], "test_list": ["tests/unit/transformers/test_datetime.py"], "prob_info": [{"class_start_lineno": 13, "class_end_lineno": 194, "func_start_lineno": 60, "func_end_lineno": 93, "func_code": " def _get_missing_value_replacement(self, data):\n \"\"\"Get the fill value to use for the given data.\n\n Args:\n data (pd.Series):\n The data that is being transformed.\n\n Return:\n object:\n The fill value that needs to be used.\n\n Raise:\n TransformerInputError:\n Error raised when data only contains nans and ``_missing_value_replacement``\n is set to 'mean' or 'mode'.\n \"\"\"\n if self._missing_value_replacement is None:\n return None\n\n if self._missing_value_replacement in {'mean', 'mode', 'random'} and pd.isna(data).all():\n msg = (\n f\"'missing_value_replacement' cannot be set to '{self._missing_value_replacement}'\"\n ' when the provided data only contains NaNs. Using 0 instead.'\n )\n LOGGER.info(msg)\n return 0\n\n if self._missing_value_replacement == 'mean':\n return data.mean()\n\n if self._missing_value_replacement == 'mode':\n return data.mode(dropna=True)[0]\n\n return self._missing_value_replacement"}, {"class_start_lineno": 13, "class_end_lineno": 194, "func_start_lineno": 95, "func_end_lineno": 122, "func_code": " def fit(self, data):\n \"\"\"Fit the transformer to the data.\n\n Evaluate if the transformer has to create the null column or not.\n\n Args:\n data (pandas.Series):\n Data to transform.\n \"\"\"\n self._missing_value_replacement = self._get_missing_value_replacement(data)\n if self._missing_value_replacement == 'random':\n self._min_value = data.min()\n self._max_value = data.max()\n\n if self._missing_value_generation is not None:\n null_values = data.isna().to_numpy()\n self.nulls = null_values.any()\n\n if not self.nulls and self.models_missing_values():\n self._missing_value_generation = None\n guidance_message = (\n f'Guidance: There are no missing values in column {data.name}. '\n 'Extra column not created.'\n )\n LOGGER.info(guidance_message)\n\n if self._missing_value_generation == 'random':\n self._null_percentage = null_values.sum() / len(data)"}, {"class_start_lineno": 13, "class_end_lineno": 230, "func_start_lineno": 72, "func_end_lineno": 107, "func_code": " def _convert_to_datetime(self, data):\n \"\"\"Convert datetime column into datetime dtype.\n\n Convert the datetime column to datetime dtype using the ``datetime_format``.\n All non-numeric columns will automatically be cast to datetimes. Numeric columns\n with a ``datetime_format`` will be treated as strings and cast to datetime. Numeric\n columns without a ``datetime_format`` will be treated as already converted datetimes.\n\n Args:\n data (pandas.Series):\n The datetime column.\n\n Raises:\n - ``TypeError`` if data cannot be converted to datetime.\n - ``ValueError`` if data does not match the specified datetime format\n\n Returns:\n pandas.Series:\n The datetime column converted to the datetime dtype.\n \"\"\"\n if self.datetime_format or not is_numeric_dtype(data):\n try:\n pandas_datetime_format = None\n if self.datetime_format:\n pandas_datetime_format = self.datetime_format.replace('%-', '%')\n\n data = pd.to_datetime(data, format=pandas_datetime_format)\n\n except ValueError as error:\n if 'Unknown string' in str(error) or 'Unknown datetime string' in str(error):\n message = 'Data must be of dtype datetime, or castable to datetime.'\n raise TypeError(message) from None\n\n raise ValueError('Data does not match specified datetime format.') from None\n\n return data"}, {"class_start_lineno": 13, "class_end_lineno": 230, "func_start_lineno": 109, "func_end_lineno": 117, "func_code": " def _transform_helper(self, datetimes):\n \"\"\"Transform datetime values to integer.\"\"\"\n datetimes = self._convert_to_datetime(datetimes)\n nulls = datetimes.isna()\n integers = pd.to_numeric(datetimes, errors='coerce').to_numpy().astype(np.float64)\n integers[nulls] = np.nan\n transformed = pd.Series(integers)\n\n return transformed"}, {"class_start_lineno": 13, "class_end_lineno": 230, "func_start_lineno": 190, "func_end_lineno": 201, "func_code": " def _transform(self, data):\n \"\"\"Transform datetime values to float values.\n\n Args:\n data (pandas.Series):\n Data to transform.\n\n Returns:\n numpy.ndarray\n \"\"\"\n data = self._transform_helper(data)\n return self.null_transformer.transform(data)"}], "type": ["function_empty", "Development"], "node": ["rdt.transformers.null.NullTransformer._get_missing_value_replacement", "rdt.transformers.null.NullTransformer.fit", "rdt.transformers.datetime.UnixTimestampEncoder._convert_to_datetime", "rdt.transformers.datetime.UnixTimestampEncoder._transform_helper", "rdt.transformers.datetime.UnixTimestampEncoder._transform"], "language": "Python", "toolfunc_count": 3, "func_count": 4, "pytest_info": {"total_num": 32, "base_passed_num": 21}} {"id": ["rdt.rdt.transformers.null.NullTransformer::_get_missing_value_replacement", "rdt.rdt.transformers.null.NullTransformer::fit"], "project": "rdt", "origin_file": ["rdt/transformers/null.py", "rdt/transformers/null.py"], "test_list": ["tests/unit/transformers/test_null.py"], "prob_info": [{"class_start_lineno": 13, "class_end_lineno": 194, "func_start_lineno": 60, "func_end_lineno": 93, "func_code": " def _get_missing_value_replacement(self, data):\n \"\"\"Get the fill value to use for the given data.\n\n Args:\n data (pd.Series):\n The data that is being transformed.\n\n Return:\n object:\n The fill value that needs to be used.\n\n Raise:\n TransformerInputError:\n Error raised when data only contains nans and ``_missing_value_replacement``\n is set to 'mean' or 'mode'.\n \"\"\"\n if self._missing_value_replacement is None:\n return None\n\n if self._missing_value_replacement in {'mean', 'mode', 'random'} and pd.isna(data).all():\n msg = (\n f\"'missing_value_replacement' cannot be set to '{self._missing_value_replacement}'\"\n ' when the provided data only contains NaNs. Using 0 instead.'\n )\n LOGGER.info(msg)\n return 0\n\n if self._missing_value_replacement == 'mean':\n return data.mean()\n\n if self._missing_value_replacement == 'mode':\n return data.mode(dropna=True)[0]\n\n return self._missing_value_replacement"}, {"class_start_lineno": 13, "class_end_lineno": 194, "func_start_lineno": 95, "func_end_lineno": 122, "func_code": " def fit(self, data):\n \"\"\"Fit the transformer to the data.\n\n Evaluate if the transformer has to create the null column or not.\n\n Args:\n data (pandas.Series):\n Data to transform.\n \"\"\"\n self._missing_value_replacement = self._get_missing_value_replacement(data)\n if self._missing_value_replacement == 'random':\n self._min_value = data.min()\n self._max_value = data.max()\n\n if self._missing_value_generation is not None:\n null_values = data.isna().to_numpy()\n self.nulls = null_values.any()\n\n if not self.nulls and self.models_missing_values():\n self._missing_value_generation = None\n guidance_message = (\n f'Guidance: There are no missing values in column {data.name}. '\n 'Extra column not created.'\n )\n LOGGER.info(guidance_message)\n\n if self._missing_value_generation == 'random':\n self._null_percentage = null_values.sum() / len(data)"}], "type": ["function_empty"], "node": ["rdt.transformers.null.NullTransformer._get_missing_value_replacement", "rdt.transformers.null.NullTransformer.fit"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 24, "base_passed_num": 13}} {"id": ["rdt.rdt.transformers.null.NullTransformer::_get_missing_value_replacement", "rdt.rdt.transformers.null.NullTransformer::fit", "rdt.rdt.transformers.null.NullTransformer::reverse_transform", "rdt.rdt.transformers.numerical.FloatFormatter::_reverse_transform"], "project": "rdt", "origin_file": ["rdt/transformers/null.py", "rdt/transformers/null.py", "rdt/transformers/null.py", "rdt/transformers/numerical.py"], "test_list": ["tests/unit/transformers/test_numerical.py"], "prob_info": [{"class_start_lineno": 13, "class_end_lineno": 194, "func_start_lineno": 60, "func_end_lineno": 93, "func_code": " def _get_missing_value_replacement(self, data):\n \"\"\"Get the fill value to use for the given data.\n\n Args:\n data (pd.Series):\n The data that is being transformed.\n\n Return:\n object:\n The fill value that needs to be used.\n\n Raise:\n TransformerInputError:\n Error raised when data only contains nans and ``_missing_value_replacement``\n is set to 'mean' or 'mode'.\n \"\"\"\n if self._missing_value_replacement is None:\n return None\n\n if self._missing_value_replacement in {'mean', 'mode', 'random'} and pd.isna(data).all():\n msg = (\n f\"'missing_value_replacement' cannot be set to '{self._missing_value_replacement}'\"\n ' when the provided data only contains NaNs. Using 0 instead.'\n )\n LOGGER.info(msg)\n return 0\n\n if self._missing_value_replacement == 'mean':\n return data.mean()\n\n if self._missing_value_replacement == 'mode':\n return data.mode(dropna=True)[0]\n\n return self._missing_value_replacement"}, {"class_start_lineno": 13, "class_end_lineno": 194, "func_start_lineno": 95, "func_end_lineno": 122, "func_code": " def fit(self, data):\n \"\"\"Fit the transformer to the data.\n\n Evaluate if the transformer has to create the null column or not.\n\n Args:\n data (pandas.Series):\n Data to transform.\n \"\"\"\n self._missing_value_replacement = self._get_missing_value_replacement(data)\n if self._missing_value_replacement == 'random':\n self._min_value = data.min()\n self._max_value = data.max()\n\n if self._missing_value_generation is not None:\n null_values = data.isna().to_numpy()\n self.nulls = null_values.any()\n\n if not self.nulls and self.models_missing_values():\n self._missing_value_generation = None\n guidance_message = (\n f'Guidance: There are no missing values in column {data.name}. '\n 'Extra column not created.'\n )\n LOGGER.info(guidance_message)\n\n if self._missing_value_generation == 'random':\n self._null_percentage = null_values.sum() / len(data)"}, {"class_start_lineno": 13, "class_end_lineno": 194, "func_start_lineno": 165, "func_end_lineno": 194, "func_code": " def reverse_transform(self, data):\n \"\"\"Restore null values to the data.\n\n If a null indicator column was created during fit, use it as a reference.\n Otherwise, randomly replace values with ``np.nan``. The percentage of values\n that will be replaced is the percentage of null values seen in the fitted data.\n\n Args:\n data (numpy.ndarray):\n Data to transform.\n\n Returns:\n pandas.Series\n \"\"\"\n data = data.copy()\n if self._missing_value_generation == 'from_column':\n if self.nulls:\n isna = data[:, 1] > 0.5\n\n data = data[:, 0]\n\n elif self.nulls:\n isna = np.random.random((len(data),)) < self._null_percentage\n\n data = pd.Series(data)\n\n if self.nulls and isna.any():\n data.loc[isna] = np.nan\n\n return data"}, {"class_start_lineno": 29, "class_end_lineno": 245, "func_start_lineno": 170, "func_end_lineno": 201, "func_code": " def _reverse_transform(self, data):\n \"\"\"Convert data back into the original format.\n\n Args:\n data (pd.Series or numpy.ndarray):\n Data to transform.\n\n Returns:\n numpy.ndarray\n \"\"\"\n if not isinstance(data, np.ndarray):\n data = data.to_numpy()\n\n data = self.null_transformer.reverse_transform(data)\n if self.enforce_min_max_values:\n data = data.clip(self._min_value, self._max_value)\n elif not self.computer_representation.startswith('Float'):\n min_bound, max_bound = INTEGER_BOUNDS[self.computer_representation]\n data = data.clip(min_bound, max_bound)\n\n is_integer = pd.api.types.is_integer_dtype(self._dtype)\n np_integer_with_nans = (\n not pd.api.types.is_extension_array_dtype(self._dtype)\n and is_integer\n and pd.isna(data).any()\n )\n if self.learn_rounding_scheme and self._rounding_digits is not None:\n data = data.round(self._rounding_digits)\n elif is_integer:\n data = data.round(0)\n\n return data.astype(self._dtype if not np_integer_with_nans else 'float64')"}], "type": ["function_empty"], "node": ["rdt.transformers.null.NullTransformer._get_missing_value_replacement", "rdt.transformers.null.NullTransformer.fit", "rdt.transformers.null.NullTransformer.reverse_transform", "rdt.transformers.numerical.FloatFormatter._reverse_transform"], "language": "Python", "toolfunc_count": 4, "func_count": 4, "pytest_info": {"total_num": 90, "base_passed_num": 61}} {"id": ["transformers.src.transformers.image_utils.infer_channel_dimension_format", "transformers.src.transformers.image_transforms.to_channel_dimension_format", "transformers.src.transformers.image_utils.get_image_size"], "project": "transformers", "origin_file": ["transformers/image_utils.py", "transformers/image_transforms.py", "transformers/image_utils.py", "transformers/image_transforms.py", "transformers/image_transforms.py"], "test_list": ["tests/test_image_transforms.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 811, "func_start_lineno": 220, "func_end_lineno": 254, "func_code": "def infer_channel_dimension_format(\n image: np.ndarray, num_channels: Optional[Union[int, Tuple[int, ...]]] = None\n) -> ChannelDimension:\n \"\"\"\n Infers the channel dimension format of `image`.\n\n Args:\n image (`np.ndarray`):\n The image to infer the channel dimension of.\n num_channels (`int` or `Tuple[int, ...]`, *optional*, defaults to `(1, 3)`):\n The number of channels of the image.\n\n Returns:\n The channel dimension of the image.\n \"\"\"\n num_channels = num_channels if num_channels is not None else (1, 3)\n num_channels = (num_channels,) if isinstance(num_channels, int) else num_channels\n\n if image.ndim == 3:\n first_dim, last_dim = 0, 2\n elif image.ndim == 4:\n first_dim, last_dim = 1, 3\n else:\n raise ValueError(f\"Unsupported number of image dimensions: {image.ndim}\")\n\n if image.shape[first_dim] in num_channels and image.shape[last_dim] in num_channels:\n logger.warning(\n f\"The channel dimension is ambiguous. Got image shape {image.shape}. Assuming channels are the first dimension.\"\n )\n return ChannelDimension.FIRST\n elif image.shape[first_dim] in num_channels:\n return ChannelDimension.FIRST\n elif image.shape[last_dim] in num_channels:\n return ChannelDimension.LAST\n raise ValueError(\"Unable to infer channel dimension format\")"}, {"class_start_lineno": 1, "class_end_lineno": 854, "func_start_lineno": 58, "func_end_lineno": 94, "func_code": "def to_channel_dimension_format(\n image: np.ndarray,\n channel_dim: Union[ChannelDimension, str],\n input_channel_dim: Optional[Union[ChannelDimension, str]] = None,\n) -> np.ndarray:\n \"\"\"\n Converts `image` to the channel dimension format specified by `channel_dim`.\n\n Args:\n image (`numpy.ndarray`):\n The image to have its channel dimension set.\n channel_dim (`ChannelDimension`):\n The channel dimension format to use.\n input_channel_dim (`ChannelDimension`, *optional*):\n The channel dimension format of the input image. If not provided, it will be inferred from the input image.\n\n Returns:\n `np.ndarray`: The image with the channel dimension set to `channel_dim`.\n \"\"\"\n if not isinstance(image, np.ndarray):\n raise TypeError(f\"Input image must be of type np.ndarray, got {type(image)}\")\n\n if input_channel_dim is None:\n input_channel_dim = infer_channel_dimension_format(image)\n\n target_channel_dim = ChannelDimension(channel_dim)\n if input_channel_dim == target_channel_dim:\n return image\n\n if target_channel_dim == ChannelDimension.FIRST:\n image = image.transpose((2, 0, 1))\n elif target_channel_dim == ChannelDimension.LAST:\n image = image.transpose((1, 2, 0))\n else:\n raise ValueError(\"Unsupported channel dimension format: {}\".format(channel_dim))\n\n return image"}, {"class_start_lineno": 1, "class_end_lineno": 811, "func_start_lineno": 281, "func_end_lineno": 302, "func_code": "def get_image_size(image: np.ndarray, channel_dim: ChannelDimension = None) -> Tuple[int, int]:\n \"\"\"\n Returns the (height, width) dimensions of the image.\n\n Args:\n image (`np.ndarray`):\n The image to get the dimensions of.\n channel_dim (`ChannelDimension`, *optional*):\n Which dimension the channel dimension is in. If `None`, will infer the channel dimension from the image.\n\n Returns:\n A tuple of the image's height and width.\n \"\"\"\n if channel_dim is None:\n channel_dim = infer_channel_dimension_format(image)\n\n if channel_dim == ChannelDimension.FIRST:\n return image.shape[-2], image.shape[-1]\n elif channel_dim == ChannelDimension.LAST:\n return image.shape[-3], image.shape[-2]\n else:\n raise ValueError(f\"Unsupported data format: {channel_dim}\")"}, {"class_start_lineno": 1, "class_end_lineno": 854, "func_start_lineno": 774, "func_end_lineno": 809, "func_code": "def flip_channel_order(\n image: np.ndarray,\n data_format: Optional[ChannelDimension] = None,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n) -> np.ndarray:\n \"\"\"\n Flips the channel order of the image.\n\n If the image is in RGB format, it will be converted to BGR and vice versa.\n\n Args:\n image (`np.ndarray`):\n The image to flip.\n data_format (`ChannelDimension`, *optional*):\n The channel dimension format for the output image. Can be one of:\n - `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n If unset, will use same as the input image.\n input_data_format (`ChannelDimension`, *optional*):\n The channel dimension format for the input image. Can be one of:\n - `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n If unset, will use the inferred format of the input image.\n \"\"\"\n input_data_format = infer_channel_dimension_format(image) if input_data_format is None else input_data_format\n\n if input_data_format == ChannelDimension.LAST:\n image = image[..., ::-1]\n elif input_data_format == ChannelDimension.FIRST:\n image = image[::-1, ...]\n else:\n raise ValueError(f\"Unsupported channel dimension: {input_data_format}\")\n\n if data_format is not None:\n image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)\n return image"}, {"class_start_lineno": 1, "class_end_lineno": 854, "func_start_lineno": 214, "func_end_lineno": 278, "func_code": "def get_resize_output_image_size(\n input_image: np.ndarray,\n size: Union[int, Tuple[int, int], List[int], Tuple[int]],\n default_to_square: bool = True,\n max_size: Optional[int] = None,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n) -> tuple:\n \"\"\"\n Find the target (height, width) dimension of the output image after resizing given the input image and the desired\n size.\n\n Args:\n input_image (`np.ndarray`):\n The image to resize.\n size (`int` or `Tuple[int, int]` or List[int] or `Tuple[int]`):\n The size to use for resizing the image. If `size` is a sequence like (h, w), output size will be matched to\n this.\n\n If `size` is an int and `default_to_square` is `True`, then image will be resized to (size, size). If\n `size` is an int and `default_to_square` is `False`, then smaller edge of the image will be matched to this\n number. i.e, if height > width, then image will be rescaled to (size * height / width, size).\n default_to_square (`bool`, *optional*, defaults to `True`):\n How to convert `size` when it is a single int. If set to `True`, the `size` will be converted to a square\n (`size`,`size`). If set to `False`, will replicate\n [`torchvision.transforms.Resize`](https://pytorch.org/vision/stable/transforms.html#torchvision.transforms.Resize)\n with support for resizing only the smallest edge and providing an optional `max_size`.\n max_size (`int`, *optional*):\n The maximum allowed for the longer edge of the resized image: if the longer edge of the image is greater\n than `max_size` after being resized according to `size`, then the image is resized again so that the longer\n edge is equal to `max_size`. As a result, `size` might be overruled, i.e the smaller edge may be shorter\n than `size`. Only used if `default_to_square` is `False`.\n input_data_format (`ChannelDimension`, *optional*):\n The channel dimension format of the input image. If unset, will use the inferred format from the input.\n\n Returns:\n `tuple`: The target (height, width) dimension of the output image after resizing.\n \"\"\"\n if isinstance(size, (tuple, list)):\n if len(size) == 2:\n return tuple(size)\n elif len(size) == 1:\n # Perform same logic as if size was an int\n size = size[0]\n else:\n raise ValueError(\"size must have 1 or 2 elements if it is a list or tuple\")\n\n if default_to_square:\n return (size, size)\n\n height, width = get_image_size(input_image, input_data_format)\n short, long = (width, height) if width <= height else (height, width)\n requested_new_short = size\n\n new_short, new_long = requested_new_short, int(requested_new_short * long / short)\n\n if max_size is not None:\n if max_size <= requested_new_short:\n raise ValueError(\n f\"max_size = {max_size} must be strictly greater than the requested \"\n f\"size for the smaller edge size = {size}\"\n )\n if new_long > max_size:\n new_short, new_long = int(max_size * new_short / new_long), max_size\n\n return (new_long, new_short) if width <= height else (new_short, new_long)"}], "type": ["function_empty"], "node": ["transformers.image_utils.infer_channel_dimension_format", "transformers.image_transforms.to_channel_dimension_format", "transformers.image_utils.get_image_size", "transformers.image_transforms.flip_channel_order", "transformers.image_transforms.get_resize_output_image_size"], "language": "Python", "toolfunc_count": 3, "func_count": 3, "pytest_info": {"total_num": 24, "base_passed_num": 5}} {"id": ["transformers.src.transformers.audio_utils.hertz_to_mel", "transformers.src.transformers.audio_utils.mel_filter_bank"], "project": "transformers", "origin_file": ["transformers/audio_utils.py", "transformers/audio_utils.py", "transformers/models/clap/feature_extraction_clap.py"], "test_list": ["tests/models/audio_spectrogram_transformer/test_feature_extraction_audio_spectrogram_transformer.py", "tests/models/clap/test_feature_extraction_clap.py", "tests/models/univnet/test_feature_extraction_univnet.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 1127, "func_start_lineno": 26, "func_end_lineno": 59, "func_code": "def hertz_to_mel(freq: Union[float, np.ndarray], mel_scale: str = \"htk\") -> Union[float, np.ndarray]:\n \"\"\"\n Convert frequency from hertz to mels.\n\n Args:\n freq (`float` or `np.ndarray`):\n The frequency, or multiple frequencies, in hertz (Hz).\n mel_scale (`str`, *optional*, defaults to `\"htk\"`):\n The mel frequency scale to use, `\"htk\"`, `\"kaldi\"` or `\"slaney\"`.\n\n Returns:\n `float` or `np.ndarray`: The frequencies on the mel scale.\n \"\"\"\n\n if mel_scale not in [\"slaney\", \"htk\", \"kaldi\"]:\n raise ValueError('mel_scale should be one of \"htk\", \"slaney\" or \"kaldi\".')\n\n if mel_scale == \"htk\":\n return 2595.0 * np.log10(1.0 + (freq / 700.0))\n elif mel_scale == \"kaldi\":\n return 1127.0 * np.log(1.0 + (freq / 700.0))\n\n min_log_hertz = 1000.0\n min_log_mel = 15.0\n logstep = 27.0 / np.log(6.4)\n mels = 3.0 * freq / 200.0\n\n if isinstance(freq, np.ndarray):\n log_region = freq >= min_log_hertz\n mels[log_region] = min_log_mel + np.log(freq[log_region] / min_log_hertz) * logstep\n elif freq >= min_log_hertz:\n mels = min_log_mel + np.log(freq / min_log_hertz) * logstep\n\n return mels"}, {"class_start_lineno": 1, "class_end_lineno": 1127, "func_start_lineno": 218, "func_end_lineno": 303, "func_code": "def mel_filter_bank(\n num_frequency_bins: int,\n num_mel_filters: int,\n min_frequency: float,\n max_frequency: float,\n sampling_rate: int,\n norm: Optional[str] = None,\n mel_scale: str = \"htk\",\n triangularize_in_mel_space: bool = False,\n) -> np.ndarray:\n \"\"\"\n Creates a frequency bin conversion matrix used to obtain a mel spectrogram. This is called a *mel filter bank*, and\n various implementation exist, which differ in the number of filters, the shape of the filters, the way the filters\n are spaced, the bandwidth of the filters, and the manner in which the spectrum is warped. The goal of these\n features is to approximate the non-linear human perception of the variation in pitch with respect to the frequency.\n\n Different banks of mel filters were introduced in the literature. The following variations are supported:\n\n - MFCC FB-20: introduced in 1980 by Davis and Mermelstein, it assumes a sampling frequency of 10 kHz and a speech\n bandwidth of `[0, 4600]` Hz.\n - MFCC FB-24 HTK: from the Cambridge HMM Toolkit (HTK) (1995) uses a filter bank of 24 filters for a speech\n bandwidth of `[0, 8000]` Hz. This assumes sampling rate ≥ 16 kHz.\n - MFCC FB-40: from the Auditory Toolbox for MATLAB written by Slaney in 1998, assumes a sampling rate of 16 kHz and\n speech bandwidth of `[133, 6854]` Hz. This version also includes area normalization.\n - HFCC-E FB-29 (Human Factor Cepstral Coefficients) of Skowronski and Harris (2004), assumes a sampling rate of\n 12.5 kHz and speech bandwidth of `[0, 6250]` Hz.\n\n This code is adapted from *torchaudio* and *librosa*. Note that the default parameters of torchaudio's\n `melscale_fbanks` implement the `\"htk\"` filters while librosa uses the `\"slaney\"` implementation.\n\n Args:\n num_frequency_bins (`int`):\n Number of frequencies used to compute the spectrogram (should be the same as in `stft`).\n num_mel_filters (`int`):\n Number of mel filters to generate.\n min_frequency (`float`):\n Lowest frequency of interest in Hz.\n max_frequency (`float`):\n Highest frequency of interest in Hz. This should not exceed `sampling_rate / 2`.\n sampling_rate (`int`):\n Sample rate of the audio waveform.\n norm (`str`, *optional*):\n If `\"slaney\"`, divide the triangular mel weights by the width of the mel band (area normalization).\n mel_scale (`str`, *optional*, defaults to `\"htk\"`):\n The mel frequency scale to use, `\"htk\"`, `\"kaldi\"` or `\"slaney\"`.\n triangularize_in_mel_space (`bool`, *optional*, defaults to `False`):\n If this option is enabled, the triangular filter is applied in mel space rather than frequency space. This\n should be set to `true` in order to get the same results as `torchaudio` when computing mel filters.\n\n Returns:\n `np.ndarray` of shape (`num_frequency_bins`, `num_mel_filters`): Triangular filter bank matrix. This is a\n projection matrix to go from a spectrogram to a mel spectrogram.\n \"\"\"\n if norm is not None and norm != \"slaney\":\n raise ValueError('norm must be one of None or \"slaney\"')\n\n # center points of the triangular mel filters\n mel_min = hertz_to_mel(min_frequency, mel_scale=mel_scale)\n mel_max = hertz_to_mel(max_frequency, mel_scale=mel_scale)\n mel_freqs = np.linspace(mel_min, mel_max, num_mel_filters + 2)\n filter_freqs = mel_to_hertz(mel_freqs, mel_scale=mel_scale)\n\n if triangularize_in_mel_space:\n # frequencies of FFT bins in Hz, but filters triangularized in mel space\n fft_bin_width = sampling_rate / (num_frequency_bins * 2)\n fft_freqs = hertz_to_mel(fft_bin_width * np.arange(num_frequency_bins), mel_scale=mel_scale)\n filter_freqs = mel_freqs\n else:\n # frequencies of FFT bins in Hz\n fft_freqs = np.linspace(0, sampling_rate // 2, num_frequency_bins)\n\n mel_filters = _create_triangular_filter_bank(fft_freqs, filter_freqs)\n\n if norm is not None and norm == \"slaney\":\n # Slaney-style mel is scaled to be approx constant energy per channel\n enorm = 2.0 / (filter_freqs[2 : num_mel_filters + 2] - filter_freqs[:num_mel_filters])\n mel_filters *= np.expand_dims(enorm, 0)\n\n if (mel_filters.max(axis=0) == 0.0).any():\n warnings.warn(\n \"At least one mel filter has all zero values. \"\n f\"The value for `num_mel_filters` ({num_mel_filters}) may be set too high. \"\n f\"Or, the value for `num_frequency_bins` ({num_frequency_bins}) may be set too low.\"\n )\n\n return mel_filters"}, {"class_start_lineno": 32, "class_end_lineno": 362, "func_start_lineno": 84, "func_end_lineno": 135, "func_code": " def __init__(\n self,\n feature_size=64,\n sampling_rate=48_000,\n hop_length=480,\n max_length_s=10,\n fft_window_size=1024,\n padding_value=0.0,\n return_attention_mask=False, # pad inputs to max length with silence token (zero) and no attention mask\n frequency_min: float = 0,\n frequency_max: float = 14_000,\n top_db: int = None,\n truncation: str = \"fusion\",\n padding: str = \"repeatpad\",\n **kwargs,\n ):\n super().__init__(\n feature_size=feature_size,\n sampling_rate=sampling_rate,\n padding_value=padding_value,\n return_attention_mask=return_attention_mask,\n **kwargs,\n )\n self.top_db = top_db\n self.truncation = truncation\n self.padding = padding\n self.fft_window_size = fft_window_size\n self.nb_frequency_bins = (fft_window_size >> 1) + 1\n self.hop_length = hop_length\n self.max_length_s = max_length_s\n self.nb_max_samples = max_length_s * sampling_rate\n self.sampling_rate = sampling_rate\n self.frequency_min = frequency_min\n self.frequency_max = frequency_max\n self.mel_filters = mel_filter_bank(\n num_frequency_bins=self.nb_frequency_bins,\n num_mel_filters=feature_size,\n min_frequency=frequency_min,\n max_frequency=frequency_max,\n sampling_rate=sampling_rate,\n norm=None,\n mel_scale=\"htk\",\n )\n self.mel_filters_slaney = mel_filter_bank(\n num_frequency_bins=self.nb_frequency_bins,\n num_mel_filters=feature_size,\n min_frequency=frequency_min,\n max_frequency=frequency_max,\n sampling_rate=sampling_rate,\n norm=\"slaney\",\n mel_scale=\"slaney\",\n )"}], "type": ["function_empty"], "node": ["transformers.audio_utils.hertz_to_mel", "transformers.audio_utils.mel_filter_bank", "transformers.models.clap.feature_extraction_clap.ClapFeatureExtractor.__init__"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 77, "base_passed_num": 47}} {"id": ["transformers.src.transformers.image_processing_utils.get_size_dict", "transformers.src.transformers.image_transforms.resize", "transformers.src.transformers.models.blip.image_processing_blip.BlipImageProcessor::resize", "transformers.src.transformers.models.blip.image_processing_blip.BlipImageProcessor::preprocess"], "project": "transformers", "origin_file": ["transformers/image_processing_utils.py", "transformers/image_transforms.py", "transformers/models/blip/image_processing_blip.py", "transformers/models/blip/image_processing_blip.py"], "test_list": ["tests/models/blip/test_image_processing_blip.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 287, "func_start_lineno": 208, "func_end_lineno": 249, "func_code": "def get_size_dict(\n size: Union[int, Iterable[int], Dict[str, int]] = None,\n max_size: Optional[int] = None,\n height_width_order: bool = True,\n default_to_square: bool = True,\n param_name=\"size\",\n) -> dict:\n \"\"\"\n Converts the old size parameter in the config into the new dict expected in the config. This is to ensure backwards\n compatibility with the old image processor configs and removes ambiguity over whether the tuple is in (height,\n width) or (width, height) format.\n\n - If `size` is tuple, it is converted to `{\"height\": size[0], \"width\": size[1]}` or `{\"height\": size[1], \"width\":\n size[0]}` if `height_width_order` is `False`.\n - If `size` is an int, and `default_to_square` is `True`, it is converted to `{\"height\": size, \"width\": size}`.\n - If `size` is an int and `default_to_square` is False, it is converted to `{\"shortest_edge\": size}`. If `max_size`\n is set, it is added to the dict as `{\"longest_edge\": max_size}`.\n\n Args:\n size (`Union[int, Iterable[int], Dict[str, int]]`, *optional*):\n The `size` parameter to be cast into a size dictionary.\n max_size (`Optional[int]`, *optional*):\n The `max_size` parameter to be cast into a size dictionary.\n height_width_order (`bool`, *optional*, defaults to `True`):\n If `size` is a tuple, whether it's in (height, width) or (width, height) order.\n default_to_square (`bool`, *optional*, defaults to `True`):\n If `size` is an int, whether to default to a square image or not.\n \"\"\"\n if not isinstance(size, dict):\n size_dict = convert_to_size_dict(size, max_size, default_to_square, height_width_order)\n logger.info(\n f\"{param_name} should be a dictionary on of the following set of keys: {VALID_SIZE_DICT_KEYS}, got {size}.\"\n f\" Converted to {size_dict}.\",\n )\n else:\n size_dict = size\n\n if not is_valid_size_dict(size_dict):\n raise ValueError(\n f\"{param_name} must have one of the following set of keys: {VALID_SIZE_DICT_KEYS}, got {size_dict.keys()}\"\n )\n return size_dict"}, {"class_start_lineno": 1, "class_end_lineno": 854, "func_start_lineno": 281, "func_end_lineno": 349, "func_code": "def resize(\n image: np.ndarray,\n size: Tuple[int, int],\n resample: \"PILImageResampling\" = None,\n reducing_gap: Optional[int] = None,\n data_format: Optional[ChannelDimension] = None,\n return_numpy: bool = True,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n) -> np.ndarray:\n \"\"\"\n Resizes `image` to `(height, width)` specified by `size` using the PIL library.\n\n Args:\n image (`np.ndarray`):\n The image to resize.\n size (`Tuple[int, int]`):\n The size to use for resizing the image.\n resample (`int`, *optional*, defaults to `PILImageResampling.BILINEAR`):\n The filter to user for resampling.\n reducing_gap (`int`, *optional*):\n Apply optimization by resizing the image in two steps. The bigger `reducing_gap`, the closer the result to\n the fair resampling. See corresponding Pillow documentation for more details.\n data_format (`ChannelDimension`, *optional*):\n The channel dimension format of the output image. If unset, will use the inferred format from the input.\n return_numpy (`bool`, *optional*, defaults to `True`):\n Whether or not to return the resized image as a numpy array. If False a `PIL.Image.Image` object is\n returned.\n input_data_format (`ChannelDimension`, *optional*):\n The channel dimension format of the input image. If unset, will use the inferred format from the input.\n\n Returns:\n `np.ndarray`: The resized image.\n \"\"\"\n requires_backends(resize, [\"vision\"])\n\n resample = resample if resample is not None else PILImageResampling.BILINEAR\n\n if not len(size) == 2:\n raise ValueError(\"size must have 2 elements\")\n\n # For all transformations, we want to keep the same data format as the input image unless otherwise specified.\n # The resized image from PIL will always have channels last, so find the input format first.\n if input_data_format is None:\n input_data_format = infer_channel_dimension_format(image)\n data_format = input_data_format if data_format is None else data_format\n\n # To maintain backwards compatibility with the resizing done in previous image feature extractors, we use\n # the pillow library to resize the image and then convert back to numpy\n do_rescale = False\n if not isinstance(image, PIL.Image.Image):\n do_rescale = _rescale_for_pil_conversion(image)\n image = to_pil_image(image, do_rescale=do_rescale, input_data_format=input_data_format)\n height, width = size\n # PIL images are in the format (width, height)\n resized_image = image.resize((width, height), resample=resample, reducing_gap=reducing_gap)\n\n if return_numpy:\n resized_image = np.array(resized_image)\n # If the input image channel dimension was of size 1, then it is dropped when converting to a PIL image\n # so we need to add it back if necessary.\n resized_image = np.expand_dims(resized_image, axis=-1) if resized_image.ndim == 2 else resized_image\n # The image is always in channels last format after converting from a PIL image\n resized_image = to_channel_dimension_format(\n resized_image, data_format, input_channel_dim=ChannelDimension.LAST\n )\n # If an image was rescaled to be in the range [0, 255] before converting to a PIL image, then we need to\n # rescale it back to the original range.\n resized_image = rescale(resized_image, 1 / 255) if do_rescale else resized_image\n return resized_image"}, {"class_start_lineno": 46, "class_end_lineno": 294, "func_start_lineno": 111, "func_end_lineno": 157, "func_code": " def resize(\n self,\n image: np.ndarray,\n size: Dict[str, int],\n resample: PILImageResampling = PILImageResampling.BICUBIC,\n data_format: Optional[Union[str, ChannelDimension]] = None,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n **kwargs,\n ) -> np.ndarray:\n \"\"\"\n Resize an image to `(size[\"height\"], size[\"width\"])`.\n\n Args:\n image (`np.ndarray`):\n Image to resize.\n size (`Dict[str, int]`):\n Dictionary in the format `{\"height\": int, \"width\": int}` specifying the size of the output image.\n resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):\n `PILImageResampling` filter to use when resizing the image e.g. `PILImageResampling.BICUBIC`.\n data_format (`ChannelDimension` or `str`, *optional*):\n The channel dimension format for the output image. If unset, the channel dimension format of the input\n image is used. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n - `\"none\"` or `ChannelDimension.NONE`: image in (height, width) format.\n input_data_format (`ChannelDimension` or `str`, *optional*):\n The channel dimension format for the input image. If unset, the channel dimension format is inferred\n from the input image. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n - `\"none\"` or `ChannelDimension.NONE`: image in (height, width) format.\n\n Returns:\n `np.ndarray`: The resized image.\n \"\"\"\n size = get_size_dict(size)\n if \"height\" not in size or \"width\" not in size:\n raise ValueError(f\"The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}\")\n output_size = (size[\"height\"], size[\"width\"])\n return resize(\n image,\n size=output_size,\n resample=resample,\n data_format=data_format,\n input_data_format=input_data_format,\n **kwargs,\n )"}, {"class_start_lineno": 46, "class_end_lineno": 294, "func_start_lineno": 160, "func_end_lineno": 294, "func_code": " def preprocess(\n self,\n images: ImageInput,\n do_resize: Optional[bool] = None,\n size: Optional[Dict[str, int]] = None,\n resample: PILImageResampling = None,\n do_rescale: Optional[bool] = None,\n rescale_factor: Optional[float] = None,\n do_normalize: Optional[bool] = None,\n image_mean: Optional[Union[float, List[float]]] = None,\n image_std: Optional[Union[float, List[float]]] = None,\n return_tensors: Optional[Union[str, TensorType]] = None,\n do_convert_rgb: bool = None,\n data_format: ChannelDimension = ChannelDimension.FIRST,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n ) -> PIL.Image.Image:\n \"\"\"\n Preprocess an image or batch of images.\n\n Args:\n images (`ImageInput`):\n Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If\n passing in images with pixel values between 0 and 1, set `do_rescale=False`.\n do_resize (`bool`, *optional*, defaults to `self.do_resize`):\n Whether to resize the image.\n size (`Dict[str, int]`, *optional*, defaults to `self.size`):\n Controls the size of the image after `resize`. The shortest edge of the image is resized to\n `size[\"shortest_edge\"]` whilst preserving the aspect ratio. If the longest edge of this resized image\n is > `int(size[\"shortest_edge\"] * (1333 / 800))`, then the image is resized again to make the longest\n edge equal to `int(size[\"shortest_edge\"] * (1333 / 800))`.\n resample (`PILImageResampling`, *optional*, defaults to `self.resample`):\n Resampling filter to use if resizing the image. Only has an effect if `do_resize` is set to `True`.\n do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):\n Whether to rescale the image values between [0 - 1].\n rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):\n Rescale factor to rescale the image by if `do_rescale` is set to `True`.\n do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):\n Whether to normalize the image.\n image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):\n Image mean to normalize the image by if `do_normalize` is set to `True`.\n image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):\n Image standard deviation to normalize the image by if `do_normalize` is set to `True`.\n do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):\n Whether to convert the image to RGB.\n return_tensors (`str` or `TensorType`, *optional*):\n The type of tensors to return. Can be one of:\n - Unset: Return a list of `np.ndarray`.\n - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.\n - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.\n - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.\n - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.\n data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):\n The channel dimension format for the output image. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n - Unset: Use the channel dimension format of the input image.\n input_data_format (`ChannelDimension` or `str`, *optional*):\n The channel dimension format for the input image. If unset, the channel dimension format is inferred\n from the input image. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n - `\"none\"` or `ChannelDimension.NONE`: image in (height, width) format.\n \"\"\"\n do_resize = do_resize if do_resize is not None else self.do_resize\n resample = resample if resample is not None else self.resample\n do_rescale = do_rescale if do_rescale is not None else self.do_rescale\n rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor\n do_normalize = do_normalize if do_normalize is not None else self.do_normalize\n image_mean = image_mean if image_mean is not None else self.image_mean\n image_std = image_std if image_std is not None else self.image_std\n do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb\n\n size = size if size is not None else self.size\n size = get_size_dict(size, default_to_square=False)\n\n images = make_list_of_images(images)\n\n if not valid_images(images):\n raise ValueError(\n \"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, \"\n \"torch.Tensor, tf.Tensor or jax.ndarray.\"\n )\n\n validate_preprocess_arguments(\n do_rescale=do_rescale,\n rescale_factor=rescale_factor,\n do_normalize=do_normalize,\n image_mean=image_mean,\n image_std=image_std,\n do_resize=do_resize,\n size=size,\n resample=resample,\n )\n # PIL RGBA images are converted to RGB\n if do_convert_rgb:\n images = [convert_to_rgb(image) for image in images]\n\n # All transformations expect numpy arrays.\n images = [to_numpy_array(image) for image in images]\n\n if is_scaled_image(images[0]) and do_rescale:\n logger.warning_once(\n \"It looks like you are trying to rescale already rescaled images. If the input\"\n \" images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again.\"\n )\n\n if input_data_format is None:\n # We assume that all images have the same channel dimension format.\n input_data_format = infer_channel_dimension_format(images[0])\n\n if do_resize:\n images = [\n self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)\n for image in images\n ]\n\n if do_rescale:\n images = [\n self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)\n for image in images\n ]\n\n if do_normalize:\n images = [\n self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)\n for image in images\n ]\n\n images = [\n to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) for image in images\n ]\n\n encoded_outputs = BatchFeature(data={\"pixel_values\": images}, tensor_type=return_tensors)\n\n return encoded_outputs"}], "type": ["function_empty", "Development"], "node": ["transformers.image_processing_utils.get_size_dict", "transformers.image_transforms.resize", "transformers.models.blip.image_processing_blip.BlipImageProcessor.resize", "transformers.models.blip.image_processing_blip.BlipImageProcessor.preprocess"], "language": "Python", "toolfunc_count": 3, "func_count": 4, "pytest_info": {"total_num": 20, "base_passed_num": 12}} {"id": ["transformers.src.transformers.image_processing_utils.get_size_dict", "transformers.src.transformers.image_transforms.get_resize_output_image_size", "transformers.src.transformers.image_transforms.resize", "transformers.src.transformers.models.chinese_clip.image_processing_chinese_clip.ChineseCLIPImageProcessor::resize"], "project": "transformers", "origin_file": ["transformers/image_processing_utils.py", "transformers/image_transforms.py", "transformers/image_transforms.py", "transformers/models/chinese_clip/image_processing_chinese_clip.py"], "test_list": ["tests/models/chinese_clip/test_image_processing_chinese_clip.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 287, "func_start_lineno": 208, "func_end_lineno": 249, "func_code": "def get_size_dict(\n size: Union[int, Iterable[int], Dict[str, int]] = None,\n max_size: Optional[int] = None,\n height_width_order: bool = True,\n default_to_square: bool = True,\n param_name=\"size\",\n) -> dict:\n \"\"\"\n Converts the old size parameter in the config into the new dict expected in the config. This is to ensure backwards\n compatibility with the old image processor configs and removes ambiguity over whether the tuple is in (height,\n width) or (width, height) format.\n\n - If `size` is tuple, it is converted to `{\"height\": size[0], \"width\": size[1]}` or `{\"height\": size[1], \"width\":\n size[0]}` if `height_width_order` is `False`.\n - If `size` is an int, and `default_to_square` is `True`, it is converted to `{\"height\": size, \"width\": size}`.\n - If `size` is an int and `default_to_square` is False, it is converted to `{\"shortest_edge\": size}`. If `max_size`\n is set, it is added to the dict as `{\"longest_edge\": max_size}`.\n\n Args:\n size (`Union[int, Iterable[int], Dict[str, int]]`, *optional*):\n The `size` parameter to be cast into a size dictionary.\n max_size (`Optional[int]`, *optional*):\n The `max_size` parameter to be cast into a size dictionary.\n height_width_order (`bool`, *optional*, defaults to `True`):\n If `size` is a tuple, whether it's in (height, width) or (width, height) order.\n default_to_square (`bool`, *optional*, defaults to `True`):\n If `size` is an int, whether to default to a square image or not.\n \"\"\"\n if not isinstance(size, dict):\n size_dict = convert_to_size_dict(size, max_size, default_to_square, height_width_order)\n logger.info(\n f\"{param_name} should be a dictionary on of the following set of keys: {VALID_SIZE_DICT_KEYS}, got {size}.\"\n f\" Converted to {size_dict}.\",\n )\n else:\n size_dict = size\n\n if not is_valid_size_dict(size_dict):\n raise ValueError(\n f\"{param_name} must have one of the following set of keys: {VALID_SIZE_DICT_KEYS}, got {size_dict.keys()}\"\n )\n return size_dict"}, {"class_start_lineno": 1, "class_end_lineno": 854, "func_start_lineno": 214, "func_end_lineno": 278, "func_code": "def get_resize_output_image_size(\n input_image: np.ndarray,\n size: Union[int, Tuple[int, int], List[int], Tuple[int]],\n default_to_square: bool = True,\n max_size: Optional[int] = None,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n) -> tuple:\n \"\"\"\n Find the target (height, width) dimension of the output image after resizing given the input image and the desired\n size.\n\n Args:\n input_image (`np.ndarray`):\n The image to resize.\n size (`int` or `Tuple[int, int]` or List[int] or `Tuple[int]`):\n The size to use for resizing the image. If `size` is a sequence like (h, w), output size will be matched to\n this.\n\n If `size` is an int and `default_to_square` is `True`, then image will be resized to (size, size). If\n `size` is an int and `default_to_square` is `False`, then smaller edge of the image will be matched to this\n number. i.e, if height > width, then image will be rescaled to (size * height / width, size).\n default_to_square (`bool`, *optional*, defaults to `True`):\n How to convert `size` when it is a single int. If set to `True`, the `size` will be converted to a square\n (`size`,`size`). If set to `False`, will replicate\n [`torchvision.transforms.Resize`](https://pytorch.org/vision/stable/transforms.html#torchvision.transforms.Resize)\n with support for resizing only the smallest edge and providing an optional `max_size`.\n max_size (`int`, *optional*):\n The maximum allowed for the longer edge of the resized image: if the longer edge of the image is greater\n than `max_size` after being resized according to `size`, then the image is resized again so that the longer\n edge is equal to `max_size`. As a result, `size` might be overruled, i.e the smaller edge may be shorter\n than `size`. Only used if `default_to_square` is `False`.\n input_data_format (`ChannelDimension`, *optional*):\n The channel dimension format of the input image. If unset, will use the inferred format from the input.\n\n Returns:\n `tuple`: The target (height, width) dimension of the output image after resizing.\n \"\"\"\n if isinstance(size, (tuple, list)):\n if len(size) == 2:\n return tuple(size)\n elif len(size) == 1:\n # Perform same logic as if size was an int\n size = size[0]\n else:\n raise ValueError(\"size must have 1 or 2 elements if it is a list or tuple\")\n\n if default_to_square:\n return (size, size)\n\n height, width = get_image_size(input_image, input_data_format)\n short, long = (width, height) if width <= height else (height, width)\n requested_new_short = size\n\n new_short, new_long = requested_new_short, int(requested_new_short * long / short)\n\n if max_size is not None:\n if max_size <= requested_new_short:\n raise ValueError(\n f\"max_size = {max_size} must be strictly greater than the requested \"\n f\"size for the smaller edge size = {size}\"\n )\n if new_long > max_size:\n new_short, new_long = int(max_size * new_short / new_long), max_size\n\n return (new_long, new_short) if width <= height else (new_short, new_long)"}, {"class_start_lineno": 1, "class_end_lineno": 854, "func_start_lineno": 281, "func_end_lineno": 349, "func_code": "def resize(\n image: np.ndarray,\n size: Tuple[int, int],\n resample: \"PILImageResampling\" = None,\n reducing_gap: Optional[int] = None,\n data_format: Optional[ChannelDimension] = None,\n return_numpy: bool = True,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n) -> np.ndarray:\n \"\"\"\n Resizes `image` to `(height, width)` specified by `size` using the PIL library.\n\n Args:\n image (`np.ndarray`):\n The image to resize.\n size (`Tuple[int, int]`):\n The size to use for resizing the image.\n resample (`int`, *optional*, defaults to `PILImageResampling.BILINEAR`):\n The filter to user for resampling.\n reducing_gap (`int`, *optional*):\n Apply optimization by resizing the image in two steps. The bigger `reducing_gap`, the closer the result to\n the fair resampling. See corresponding Pillow documentation for more details.\n data_format (`ChannelDimension`, *optional*):\n The channel dimension format of the output image. If unset, will use the inferred format from the input.\n return_numpy (`bool`, *optional*, defaults to `True`):\n Whether or not to return the resized image as a numpy array. If False a `PIL.Image.Image` object is\n returned.\n input_data_format (`ChannelDimension`, *optional*):\n The channel dimension format of the input image. If unset, will use the inferred format from the input.\n\n Returns:\n `np.ndarray`: The resized image.\n \"\"\"\n requires_backends(resize, [\"vision\"])\n\n resample = resample if resample is not None else PILImageResampling.BILINEAR\n\n if not len(size) == 2:\n raise ValueError(\"size must have 2 elements\")\n\n # For all transformations, we want to keep the same data format as the input image unless otherwise specified.\n # The resized image from PIL will always have channels last, so find the input format first.\n if input_data_format is None:\n input_data_format = infer_channel_dimension_format(image)\n data_format = input_data_format if data_format is None else data_format\n\n # To maintain backwards compatibility with the resizing done in previous image feature extractors, we use\n # the pillow library to resize the image and then convert back to numpy\n do_rescale = False\n if not isinstance(image, PIL.Image.Image):\n do_rescale = _rescale_for_pil_conversion(image)\n image = to_pil_image(image, do_rescale=do_rescale, input_data_format=input_data_format)\n height, width = size\n # PIL images are in the format (width, height)\n resized_image = image.resize((width, height), resample=resample, reducing_gap=reducing_gap)\n\n if return_numpy:\n resized_image = np.array(resized_image)\n # If the input image channel dimension was of size 1, then it is dropped when converting to a PIL image\n # so we need to add it back if necessary.\n resized_image = np.expand_dims(resized_image, axis=-1) if resized_image.ndim == 2 else resized_image\n # The image is always in channels last format after converting from a PIL image\n resized_image = to_channel_dimension_format(\n resized_image, data_format, input_channel_dim=ChannelDimension.LAST\n )\n # If an image was rescaled to be in the range [0, 255] before converting to a PIL image, then we need to\n # rescale it back to the original range.\n resized_image = rescale(resized_image, 1 / 255) if do_rescale else resized_image\n return resized_image"}, {"class_start_lineno": 51, "class_end_lineno": 306, "func_start_lineno": 125, "func_end_lineno": 162, "func_code": " def resize(\n self,\n image: np.ndarray,\n size: Dict[str, int],\n resample: PILImageResampling = PILImageResampling.BICUBIC,\n data_format: Optional[Union[str, ChannelDimension]] = None,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n **kwargs,\n ) -> np.ndarray:\n \"\"\"\n Resize an image. The shortest edge of the image is resized to size[\"shortest_edge\"], with the longest edge\n resized to keep the input aspect ratio.\n\n Args:\n image (`np.ndarray`):\n Image to resize.\n size (`Dict[str, int]`):\n Size of the output image.\n resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):\n Resampling filter to use when resiizing the image.\n data_format (`str` or `ChannelDimension`, *optional*):\n The channel dimension format of the image. If not provided, it will be the same as the input image.\n input_data_format (`ChannelDimension` or `str`, *optional*):\n The channel dimension format of the input image. If not provided, it will be inferred from the input\n image.\n \"\"\"\n size = get_size_dict(size, default_to_square=False)\n output_size = get_resize_output_image_size(\n image, size=(size[\"height\"], size[\"width\"]), default_to_square=False, input_data_format=input_data_format\n )\n return resize(\n image,\n size=output_size,\n resample=resample,\n data_format=data_format,\n input_data_format=input_data_format,\n **kwargs,\n )"}], "type": ["function_empty", "Development"], "node": ["transformers.image_processing_utils.get_size_dict", "transformers.image_transforms.get_resize_output_image_size", "transformers.image_transforms.resize", "transformers.models.chinese_clip.image_processing_chinese_clip.ChineseCLIPImageProcessor.resize"], "language": "Python", "toolfunc_count": 3, "func_count": 4, "pytest_info": {"total_num": 21, "base_passed_num": 12}} {"id": ["transformers.src.transformers.image_utils.infer_channel_dimension_format", "transformers.src.transformers.image_utils.get_image_size", "transformers.src.transformers.image_transforms.resize", "transformers.src.transformers.models.fuyu.image_processing_fuyu.FuyuImageProcessor::resize"], "project": "transformers", "origin_file": ["transformers/image_utils.py", "transformers/image_utils.py", "transformers/image_transforms.py", "transformers/models/fuyu/image_processing_fuyu.py"], "test_list": ["tests/models/fuyu/test_image_processing_fuyu.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 811, "func_start_lineno": 220, "func_end_lineno": 254, "func_code": "def infer_channel_dimension_format(\n image: np.ndarray, num_channels: Optional[Union[int, Tuple[int, ...]]] = None\n) -> ChannelDimension:\n \"\"\"\n Infers the channel dimension format of `image`.\n\n Args:\n image (`np.ndarray`):\n The image to infer the channel dimension of.\n num_channels (`int` or `Tuple[int, ...]`, *optional*, defaults to `(1, 3)`):\n The number of channels of the image.\n\n Returns:\n The channel dimension of the image.\n \"\"\"\n num_channels = num_channels if num_channels is not None else (1, 3)\n num_channels = (num_channels,) if isinstance(num_channels, int) else num_channels\n\n if image.ndim == 3:\n first_dim, last_dim = 0, 2\n elif image.ndim == 4:\n first_dim, last_dim = 1, 3\n else:\n raise ValueError(f\"Unsupported number of image dimensions: {image.ndim}\")\n\n if image.shape[first_dim] in num_channels and image.shape[last_dim] in num_channels:\n logger.warning(\n f\"The channel dimension is ambiguous. Got image shape {image.shape}. Assuming channels are the first dimension.\"\n )\n return ChannelDimension.FIRST\n elif image.shape[first_dim] in num_channels:\n return ChannelDimension.FIRST\n elif image.shape[last_dim] in num_channels:\n return ChannelDimension.LAST\n raise ValueError(\"Unable to infer channel dimension format\")"}, {"class_start_lineno": 1, "class_end_lineno": 811, "func_start_lineno": 281, "func_end_lineno": 302, "func_code": "def get_image_size(image: np.ndarray, channel_dim: ChannelDimension = None) -> Tuple[int, int]:\n \"\"\"\n Returns the (height, width) dimensions of the image.\n\n Args:\n image (`np.ndarray`):\n The image to get the dimensions of.\n channel_dim (`ChannelDimension`, *optional*):\n Which dimension the channel dimension is in. If `None`, will infer the channel dimension from the image.\n\n Returns:\n A tuple of the image's height and width.\n \"\"\"\n if channel_dim is None:\n channel_dim = infer_channel_dimension_format(image)\n\n if channel_dim == ChannelDimension.FIRST:\n return image.shape[-2], image.shape[-1]\n elif channel_dim == ChannelDimension.LAST:\n return image.shape[-3], image.shape[-2]\n else:\n raise ValueError(f\"Unsupported data format: {channel_dim}\")"}, {"class_start_lineno": 1, "class_end_lineno": 854, "func_start_lineno": 281, "func_end_lineno": 349, "func_code": "def resize(\n image: np.ndarray,\n size: Tuple[int, int],\n resample: \"PILImageResampling\" = None,\n reducing_gap: Optional[int] = None,\n data_format: Optional[ChannelDimension] = None,\n return_numpy: bool = True,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n) -> np.ndarray:\n \"\"\"\n Resizes `image` to `(height, width)` specified by `size` using the PIL library.\n\n Args:\n image (`np.ndarray`):\n The image to resize.\n size (`Tuple[int, int]`):\n The size to use for resizing the image.\n resample (`int`, *optional*, defaults to `PILImageResampling.BILINEAR`):\n The filter to user for resampling.\n reducing_gap (`int`, *optional*):\n Apply optimization by resizing the image in two steps. The bigger `reducing_gap`, the closer the result to\n the fair resampling. See corresponding Pillow documentation for more details.\n data_format (`ChannelDimension`, *optional*):\n The channel dimension format of the output image. If unset, will use the inferred format from the input.\n return_numpy (`bool`, *optional*, defaults to `True`):\n Whether or not to return the resized image as a numpy array. If False a `PIL.Image.Image` object is\n returned.\n input_data_format (`ChannelDimension`, *optional*):\n The channel dimension format of the input image. If unset, will use the inferred format from the input.\n\n Returns:\n `np.ndarray`: The resized image.\n \"\"\"\n requires_backends(resize, [\"vision\"])\n\n resample = resample if resample is not None else PILImageResampling.BILINEAR\n\n if not len(size) == 2:\n raise ValueError(\"size must have 2 elements\")\n\n # For all transformations, we want to keep the same data format as the input image unless otherwise specified.\n # The resized image from PIL will always have channels last, so find the input format first.\n if input_data_format is None:\n input_data_format = infer_channel_dimension_format(image)\n data_format = input_data_format if data_format is None else data_format\n\n # To maintain backwards compatibility with the resizing done in previous image feature extractors, we use\n # the pillow library to resize the image and then convert back to numpy\n do_rescale = False\n if not isinstance(image, PIL.Image.Image):\n do_rescale = _rescale_for_pil_conversion(image)\n image = to_pil_image(image, do_rescale=do_rescale, input_data_format=input_data_format)\n height, width = size\n # PIL images are in the format (width, height)\n resized_image = image.resize((width, height), resample=resample, reducing_gap=reducing_gap)\n\n if return_numpy:\n resized_image = np.array(resized_image)\n # If the input image channel dimension was of size 1, then it is dropped when converting to a PIL image\n # so we need to add it back if necessary.\n resized_image = np.expand_dims(resized_image, axis=-1) if resized_image.ndim == 2 else resized_image\n # The image is always in channels last format after converting from a PIL image\n resized_image = to_channel_dimension_format(\n resized_image, data_format, input_channel_dim=ChannelDimension.LAST\n )\n # If an image was rescaled to be in the range [0, 255] before converting to a PIL image, then we need to\n # rescale it back to the original range.\n resized_image = rescale(resized_image, 1 / 255) if do_rescale else resized_image\n return resized_image"}, {"class_start_lineno": 182, "class_end_lineno": 720, "func_start_lineno": 266, "func_end_lineno": 322, "func_code": " def resize(\n self,\n image: np.ndarray,\n size: Dict[str, int],\n resample: PILImageResampling = PILImageResampling.BILINEAR,\n data_format: Optional[Union[str, ChannelDimension]] = None,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n **kwargs,\n ) -> np.ndarray:\n \"\"\"\n Resize an image to `(size[\"height\"], size[\"width\"])`.\n\n Args:\n image (`np.ndarray`):\n Image to resize.\n size (`Dict[str, int]`):\n Dictionary in the format `{\"height\": int, \"width\": int}` specifying the size of the output image.\n resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):\n `PILImageResampling` filter to use when resizing the image e.g. `PILImageResampling.BILINEAR`.\n data_format (`ChannelDimension` or `str`, *optional*):\n The channel dimension format for the output image. If unset, the channel dimension format of the input\n image is used. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n - `\"none\"` or `ChannelDimension.NONE`: image in (height, width) format.\n input_data_format (`ChannelDimension` or `str`, *optional*):\n The channel dimension format for the input image. If unset, the channel dimension format is inferred\n from the input image. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n - `\"none\"` or `ChannelDimension.NONE`: image in (height, width) format.\n\n Returns:\n `np.ndarray`: The resized image.\n \"\"\"\n image_height, image_width = get_image_size(image, input_data_format)\n target_height, target_width = size[\"height\"], size[\"width\"]\n\n if image_width <= target_width and image_height <= target_height:\n return image\n\n height_scale_factor = target_height / image_height\n width_scale_factor = target_width / image_width\n optimal_scale_factor = min(height_scale_factor, width_scale_factor)\n\n new_height = int(image_height * optimal_scale_factor)\n new_width = int(image_width * optimal_scale_factor)\n\n scaled_image = resize(\n image=image,\n size=(new_height, new_width),\n resample=resample,\n data_format=data_format,\n input_data_format=input_data_format,\n **kwargs,\n )\n return scaled_image"}], "type": ["function_empty"], "node": ["transformers.image_utils.infer_channel_dimension_format", "transformers.image_utils.get_image_size", "transformers.image_transforms.resize", "transformers.models.fuyu.image_processing_fuyu.FuyuImageProcessor.resize"], "language": "Python", "toolfunc_count": 4, "func_count": 4, "pytest_info": {"total_num": 4, "base_passed_num": 1}} {"id": ["transformers.src.transformers.models.musicgen_melody.feature_extraction_musicgen_melody.MusicgenMelodyFeatureExtractor::_extract_stem_indices", "transformers.src.transformers.models.musicgen_melody.feature_extraction_musicgen_melody.MusicgenMelodyFeatureExtractor::__call__"], "project": "transformers", "origin_file": ["transformers/models/musicgen_melody/feature_extraction_musicgen_melody.py", "transformers/models/musicgen_melody/feature_extraction_musicgen_melody.py"], "test_list": ["tests/models/musicgen_melody/test_feature_extraction_musicgen_melody.py"], "prob_info": [{"class_start_lineno": 39, "class_end_lineno": 331, "func_start_lineno": 146, "func_end_lineno": 179, "func_code": " def _extract_stem_indices(self, audio, sampling_rate=None):\n \"\"\"\n Extracts stems from the output of the [Demucs](https://github.com/adefossez/demucs/tree/main) audio separation model,\n then converts to mono-channel and resample to the feature extractor sampling rate.\n\n Args:\n audio (`torch.Tensor` of shape `(batch_size, num_stems, channel_size, audio_length)`):\n The output of the Demucs model to be processed.\n sampling_rate (`int`, *optional*):\n Demucs sampling rate. If not specified, defaults to `44000`.\n \"\"\"\n sampling_rate = 44000 if sampling_rate is None else sampling_rate\n\n # extract \"vocals\" and \"others\" sources from audio encoder (demucs) output\n # [batch_size, num_stems, channel_size, audio_length]\n wav = audio[:, torch.tensor(self.stem_indices)]\n\n # merge extracted stems to single waveform\n wav = wav.sum(1)\n\n # convert to mono-channel waveform\n wav = wav.mean(dim=1, keepdim=True)\n\n # resample to model sampling rate\n # not equivalent to julius.resample\n if sampling_rate != self.sampling_rate:\n wav = torchaudio.functional.resample(\n wav, sampling_rate, self.sampling_rate, rolloff=0.945, lowpass_filter_width=24\n )\n\n # [batch_size, 1, audio_length] -> [batch_size, audio_length]\n wav = wav.squeeze(1)\n\n return wav"}, {"class_start_lineno": 39, "class_end_lineno": 331, "func_start_lineno": 181, "func_end_lineno": 314, "func_code": " def __call__(\n self,\n audio: Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]],\n truncation: bool = True,\n pad_to_multiple_of: Optional[int] = None,\n return_tensors: Optional[Union[str, TensorType]] = None,\n return_attention_mask: Optional[bool] = None,\n padding: Optional[str] = True,\n max_length: Optional[int] = None,\n sampling_rate: Optional[int] = None,\n **kwargs,\n ) -> BatchFeature:\n \"\"\"\n Main method to featurize and prepare for the model one or several sequence(s).\n\n Args:\n audio (`torch.Tensor`, `np.ndarray`, `List[float]`, `List[np.ndarray]`, `List[torch.Tensor]`, `List[List[float]]`):\n The sequence or batch of sequences to be padded. Each sequence can be a torch tensor, a numpy array, a list of float\n values, a list of numpy arrays, a list of torch tensors, or a list of list of float values.\n If `audio` is the output of Demucs, it has to be a torch tensor of shape `(batch_size, num_stems, channel_size, audio_length)`.\n Otherwise, it must be mono or stereo channel audio.\n truncation (`bool`, *optional*, default to `True`):\n Activates truncation to cut input sequences longer than *max_length* to *max_length*.\n pad_to_multiple_of (`int`, *optional*, defaults to None):\n If set will pad the sequence to a multiple of the provided value.\n\n This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability\n `>= 7.5` (Volta), or on TPUs which benefit from having sequence lengths be a multiple of 128.\n return_tensors (`str` or [`~utils.TensorType`], *optional*):\n If set, will return tensors instead of list of python integers. Acceptable values are:\n\n - `'tf'`: Return TensorFlow `tf.constant` objects.\n - `'pt'`: Return PyTorch `torch.Tensor` objects.\n - `'np'`: Return Numpy `np.ndarray` objects.\n return_attention_mask (`bool`, *optional*):\n Whether to return the attention mask. If left to the default, will return the attention mask according\n to the specific feature_extractor's default.\n\n [What are attention masks?](../glossary#attention-mask)\n\n \n For Musicgen Melody models, audio `attention_mask` is not necessary.\n \n\n padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `True`):\n Select a strategy to pad the returned sequences (according to the model's padding side and padding\n index) among:\n\n - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single\n sequence if provided).\n - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided.\n - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different\n lengths).\n max_length (`int`, *optional*):\n Maximum length of the returned list and optionally padding length (see above).\n sampling_rate (`int`, *optional*):\n The sampling rate at which the `audio` input was sampled. It is strongly recommended to pass\n `sampling_rate` at the forward call to prevent silent errors.\n Note that if `audio` is the output of Demucs, `sampling_rate` must be the sampling rate at which Demucs operates.\n \"\"\"\n\n if sampling_rate is None:\n logger.warning_once(\n \"It is strongly recommended to pass the `sampling_rate` argument to this function. \"\n \"Failing to do so can result in silent errors that might be hard to debug.\"\n )\n\n if isinstance(audio, torch.Tensor) and len(audio.shape) == 4:\n logger.warning_once(\n \"`audio` is a 4-dimensional torch tensor and has thus been recognized as the output of `Demucs`. \"\n \"If this is not the case, make sure to read Musicgen Melody docstrings and \"\n \"to correct `audio` to get the right behaviour.\"\n \"Link to the docstrings: https://huggingface.co/docs/transformers/main/en/model_doc/musicgen_melody\"\n )\n audio = self._extract_stem_indices(audio, sampling_rate=sampling_rate)\n elif sampling_rate is not None and sampling_rate != self.sampling_rate:\n audio = torchaudio.functional.resample(\n audio, sampling_rate, self.sampling_rate, rolloff=0.945, lowpass_filter_width=24\n )\n\n is_batched = isinstance(audio, (np.ndarray, torch.Tensor)) and len(audio.shape) > 1\n is_batched = is_batched or (\n isinstance(audio, (list, tuple)) and (isinstance(audio[0], (torch.Tensor, np.ndarray, tuple, list)))\n )\n\n if is_batched and not isinstance(audio[0], torch.Tensor):\n audio = [torch.tensor(speech, dtype=torch.float32).unsqueeze(-1) for speech in audio]\n elif is_batched:\n audio = [speech.unsqueeze(-1) for speech in audio]\n elif not is_batched and not isinstance(audio, torch.Tensor):\n audio = torch.tensor(audio, dtype=torch.float32).unsqueeze(-1)\n\n if isinstance(audio[0], torch.Tensor) and audio[0].dtype is torch.float64:\n audio = [speech.to(torch.float32) for speech in audio]\n\n # always return batch\n if not is_batched:\n audio = [audio]\n\n if len(audio[0].shape) == 3:\n logger.warning_once(\n \"`audio` has been detected as a batch of stereo signals. Will be convert to mono signals. \"\n \"If this is an undesired behaviour, make sure to read Musicgen Melody docstrings and \"\n \"to correct `audio` to get the right behaviour.\"\n \"Link to the docstrings: https://huggingface.co/docs/transformers/main/en/model_doc/musicgen_melody\"\n )\n # convert to mono-channel waveform\n audio = [stereo.mean(dim=0) for stereo in audio]\n\n batched_speech = BatchFeature({\"input_features\": audio})\n\n padded_inputs = self.pad(\n batched_speech,\n padding=padding,\n max_length=max_length if max_length else self.n_samples,\n truncation=truncation,\n pad_to_multiple_of=pad_to_multiple_of,\n return_attention_mask=return_attention_mask,\n return_tensors=\"pt\",\n )\n\n input_features = self._torch_extract_fbank_features(padded_inputs[\"input_features\"].squeeze(-1))\n\n padded_inputs[\"input_features\"] = input_features\n\n if return_attention_mask:\n # rescale from raw audio length to spectrogram length\n padded_inputs[\"attention_mask\"] = padded_inputs[\"attention_mask\"][:, :: self.hop_length]\n\n if return_tensors is not None:\n padded_inputs = padded_inputs.convert_to_tensors(return_tensors)\n\n return padded_inputs"}], "type": ["function_empty"], "node": ["transformers.models.musicgen_melody.feature_extraction_musicgen_melody.MusicgenMelodyFeatureExtractor._extract_stem_indices", "transformers.models.musicgen_melody.feature_extraction_musicgen_melody.MusicgenMelodyFeatureExtractor.__call__"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 18, "base_passed_num": 15}} {"id": ["transformers.src.transformers.utils.backbone_utils._align_output_features_output_indices", "transformers.src.transformers.utils.backbone_utils.get_aligned_output_features_output_indices"], "project": "transformers", "origin_file": ["transformers/utils/backbone_utils.py", "transformers/utils/backbone_utils.py", "transformers/models/rt_detr/configuration_rt_detr_resnet.py"], "test_list": ["tests/models/rt_detr/test_modeling_rt_detr_resnet.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 377, "func_start_lineno": 77, "func_end_lineno": 105, "func_code": "def _align_output_features_output_indices(\n out_features: Optional[List[str]],\n out_indices: Optional[Union[List[int], Tuple[int]]],\n stage_names: List[str],\n):\n \"\"\"\n Finds the corresponding `out_features` and `out_indices` for the given `stage_names`.\n\n The logic is as follows:\n - `out_features` not set, `out_indices` set: `out_features` is set to the `out_features` corresponding to the\n `out_indices`.\n - `out_indices` not set, `out_features` set: `out_indices` is set to the `out_indices` corresponding to the\n `out_features`.\n - `out_indices` and `out_features` not set: `out_indices` and `out_features` are set to the last stage.\n - `out_indices` and `out_features` set: input `out_indices` and `out_features` are returned.\n\n Args:\n out_features (`List[str]`): The names of the features for the backbone to output.\n out_indices (`List[int]` or `Tuple[int]`): The indices of the features for the backbone to output.\n stage_names (`List[str]`): The names of the stages of the backbone.\n \"\"\"\n if out_indices is None and out_features is None:\n out_indices = [len(stage_names) - 1]\n out_features = [stage_names[-1]]\n elif out_indices is None and out_features is not None:\n out_indices = [stage_names.index(layer) for layer in out_features]\n elif out_features is None and out_indices is not None:\n out_features = [stage_names[idx] for idx in out_indices]\n return out_features, out_indices"}, {"class_start_lineno": 1, "class_end_lineno": 377, "func_start_lineno": 108, "func_end_lineno": 137, "func_code": "def get_aligned_output_features_output_indices(\n out_features: Optional[List[str]],\n out_indices: Optional[Union[List[int], Tuple[int]]],\n stage_names: List[str],\n) -> Tuple[List[str], List[int]]:\n \"\"\"\n Get the `out_features` and `out_indices` so that they are aligned.\n\n The logic is as follows:\n - `out_features` not set, `out_indices` set: `out_features` is set to the `out_features` corresponding to the\n `out_indices`.\n - `out_indices` not set, `out_features` set: `out_indices` is set to the `out_indices` corresponding to the\n `out_features`.\n - `out_indices` and `out_features` not set: `out_indices` and `out_features` are set to the last stage.\n - `out_indices` and `out_features` set: they are verified to be aligned.\n\n Args:\n out_features (`List[str]`): The names of the features for the backbone to output.\n out_indices (`List[int]` or `Tuple[int]`): The indices of the features for the backbone to output.\n stage_names (`List[str]`): The names of the stages of the backbone.\n \"\"\"\n out_indices = list(out_indices) if out_indices is not None else None\n # First verify that the out_features and out_indices are valid\n verify_out_features_out_indices(out_features=out_features, out_indices=out_indices, stage_names=stage_names)\n output_features, output_indices = _align_output_features_output_indices(\n out_features=out_features, out_indices=out_indices, stage_names=stage_names\n )\n # Verify that the aligned out_features and out_indices are valid\n verify_out_features_out_indices(out_features=output_features, out_indices=output_indices, stage_names=stage_names)\n return output_features, output_indices"}, {"class_start_lineno": 25, "class_end_lineno": 111, "func_start_lineno": 83, "func_end_lineno": 111, "func_code": " def __init__(\n self,\n num_channels=3,\n embedding_size=64,\n hidden_sizes=[256, 512, 1024, 2048],\n depths=[3, 4, 6, 3],\n layer_type=\"bottleneck\",\n hidden_act=\"relu\",\n downsample_in_first_stage=False,\n downsample_in_bottleneck=False,\n out_features=None,\n out_indices=None,\n **kwargs,\n ):\n super().__init__(**kwargs)\n if layer_type not in self.layer_types:\n raise ValueError(f\"layer_type={layer_type} is not one of {','.join(self.layer_types)}\")\n self.num_channels = num_channels\n self.embedding_size = embedding_size\n self.hidden_sizes = hidden_sizes\n self.depths = depths\n self.layer_type = layer_type\n self.hidden_act = hidden_act\n self.downsample_in_first_stage = downsample_in_first_stage\n self.downsample_in_bottleneck = downsample_in_bottleneck\n self.stage_names = [\"stem\"] + [f\"stage{idx}\" for idx in range(1, len(depths) + 1)]\n self._out_features, self._out_indices = get_aligned_output_features_output_indices(\n out_features=out_features, out_indices=out_indices, stage_names=self.stage_names\n )"}], "type": ["function_empty"], "node": ["transformers.utils.backbone_utils._align_output_features_output_indices", "transformers.utils.backbone_utils.get_aligned_output_features_output_indices", "transformers.models.rt_detr.configuration_rt_detr_resnet.RTDetrResNetConfig.__init__"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 8, "base_passed_num": 0}} {"id": ["transformers.src.transformers.image_utils.get_image_size", "transformers.src.transformers.image_transforms.get_resize_output_image_size", "transformers.src.transformers.image_transforms.resize", "transformers.src.transformers.models.video_llava.image_processing_video_llava.VideoLlavaImageProcessor::resize"], "project": "transformers", "origin_file": ["transformers/image_utils.py", "transformers/image_transforms.py", "transformers/image_transforms.py", "transformers/models/video_llava/image_processing_video_llava.py"], "test_list": ["tests/models/video_llava/test_image_processing_video_llava.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 811, "func_start_lineno": 281, "func_end_lineno": 302, "func_code": "def get_image_size(image: np.ndarray, channel_dim: ChannelDimension = None) -> Tuple[int, int]:\n \"\"\"\n Returns the (height, width) dimensions of the image.\n\n Args:\n image (`np.ndarray`):\n The image to get the dimensions of.\n channel_dim (`ChannelDimension`, *optional*):\n Which dimension the channel dimension is in. If `None`, will infer the channel dimension from the image.\n\n Returns:\n A tuple of the image's height and width.\n \"\"\"\n if channel_dim is None:\n channel_dim = infer_channel_dimension_format(image)\n\n if channel_dim == ChannelDimension.FIRST:\n return image.shape[-2], image.shape[-1]\n elif channel_dim == ChannelDimension.LAST:\n return image.shape[-3], image.shape[-2]\n else:\n raise ValueError(f\"Unsupported data format: {channel_dim}\")"}, {"class_start_lineno": 1, "class_end_lineno": 854, "func_start_lineno": 214, "func_end_lineno": 278, "func_code": "def get_resize_output_image_size(\n input_image: np.ndarray,\n size: Union[int, Tuple[int, int], List[int], Tuple[int]],\n default_to_square: bool = True,\n max_size: Optional[int] = None,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n) -> tuple:\n \"\"\"\n Find the target (height, width) dimension of the output image after resizing given the input image and the desired\n size.\n\n Args:\n input_image (`np.ndarray`):\n The image to resize.\n size (`int` or `Tuple[int, int]` or List[int] or `Tuple[int]`):\n The size to use for resizing the image. If `size` is a sequence like (h, w), output size will be matched to\n this.\n\n If `size` is an int and `default_to_square` is `True`, then image will be resized to (size, size). If\n `size` is an int and `default_to_square` is `False`, then smaller edge of the image will be matched to this\n number. i.e, if height > width, then image will be rescaled to (size * height / width, size).\n default_to_square (`bool`, *optional*, defaults to `True`):\n How to convert `size` when it is a single int. If set to `True`, the `size` will be converted to a square\n (`size`,`size`). If set to `False`, will replicate\n [`torchvision.transforms.Resize`](https://pytorch.org/vision/stable/transforms.html#torchvision.transforms.Resize)\n with support for resizing only the smallest edge and providing an optional `max_size`.\n max_size (`int`, *optional*):\n The maximum allowed for the longer edge of the resized image: if the longer edge of the image is greater\n than `max_size` after being resized according to `size`, then the image is resized again so that the longer\n edge is equal to `max_size`. As a result, `size` might be overruled, i.e the smaller edge may be shorter\n than `size`. Only used if `default_to_square` is `False`.\n input_data_format (`ChannelDimension`, *optional*):\n The channel dimension format of the input image. If unset, will use the inferred format from the input.\n\n Returns:\n `tuple`: The target (height, width) dimension of the output image after resizing.\n \"\"\"\n if isinstance(size, (tuple, list)):\n if len(size) == 2:\n return tuple(size)\n elif len(size) == 1:\n # Perform same logic as if size was an int\n size = size[0]\n else:\n raise ValueError(\"size must have 1 or 2 elements if it is a list or tuple\")\n\n if default_to_square:\n return (size, size)\n\n height, width = get_image_size(input_image, input_data_format)\n short, long = (width, height) if width <= height else (height, width)\n requested_new_short = size\n\n new_short, new_long = requested_new_short, int(requested_new_short * long / short)\n\n if max_size is not None:\n if max_size <= requested_new_short:\n raise ValueError(\n f\"max_size = {max_size} must be strictly greater than the requested \"\n f\"size for the smaller edge size = {size}\"\n )\n if new_long > max_size:\n new_short, new_long = int(max_size * new_short / new_long), max_size\n\n return (new_long, new_short) if width <= height else (new_short, new_long)"}, {"class_start_lineno": 1, "class_end_lineno": 854, "func_start_lineno": 281, "func_end_lineno": 349, "func_code": "def resize(\n image: np.ndarray,\n size: Tuple[int, int],\n resample: \"PILImageResampling\" = None,\n reducing_gap: Optional[int] = None,\n data_format: Optional[ChannelDimension] = None,\n return_numpy: bool = True,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n) -> np.ndarray:\n \"\"\"\n Resizes `image` to `(height, width)` specified by `size` using the PIL library.\n\n Args:\n image (`np.ndarray`):\n The image to resize.\n size (`Tuple[int, int]`):\n The size to use for resizing the image.\n resample (`int`, *optional*, defaults to `PILImageResampling.BILINEAR`):\n The filter to user for resampling.\n reducing_gap (`int`, *optional*):\n Apply optimization by resizing the image in two steps. The bigger `reducing_gap`, the closer the result to\n the fair resampling. See corresponding Pillow documentation for more details.\n data_format (`ChannelDimension`, *optional*):\n The channel dimension format of the output image. If unset, will use the inferred format from the input.\n return_numpy (`bool`, *optional*, defaults to `True`):\n Whether or not to return the resized image as a numpy array. If False a `PIL.Image.Image` object is\n returned.\n input_data_format (`ChannelDimension`, *optional*):\n The channel dimension format of the input image. If unset, will use the inferred format from the input.\n\n Returns:\n `np.ndarray`: The resized image.\n \"\"\"\n requires_backends(resize, [\"vision\"])\n\n resample = resample if resample is not None else PILImageResampling.BILINEAR\n\n if not len(size) == 2:\n raise ValueError(\"size must have 2 elements\")\n\n # For all transformations, we want to keep the same data format as the input image unless otherwise specified.\n # The resized image from PIL will always have channels last, so find the input format first.\n if input_data_format is None:\n input_data_format = infer_channel_dimension_format(image)\n data_format = input_data_format if data_format is None else data_format\n\n # To maintain backwards compatibility with the resizing done in previous image feature extractors, we use\n # the pillow library to resize the image and then convert back to numpy\n do_rescale = False\n if not isinstance(image, PIL.Image.Image):\n do_rescale = _rescale_for_pil_conversion(image)\n image = to_pil_image(image, do_rescale=do_rescale, input_data_format=input_data_format)\n height, width = size\n # PIL images are in the format (width, height)\n resized_image = image.resize((width, height), resample=resample, reducing_gap=reducing_gap)\n\n if return_numpy:\n resized_image = np.array(resized_image)\n # If the input image channel dimension was of size 1, then it is dropped when converting to a PIL image\n # so we need to add it back if necessary.\n resized_image = np.expand_dims(resized_image, axis=-1) if resized_image.ndim == 2 else resized_image\n # The image is always in channels last format after converting from a PIL image\n resized_image = to_channel_dimension_format(\n resized_image, data_format, input_channel_dim=ChannelDimension.LAST\n )\n # If an image was rescaled to be in the range [0, 255] before converting to a PIL image, then we need to\n # rescale it back to the original range.\n resized_image = rescale(resized_image, 1 / 255) if do_rescale else resized_image\n return resized_image"}, {"class_start_lineno": 69, "class_end_lineno": 404, "func_start_lineno": 143, "func_end_lineno": 190, "func_code": " def resize(\n self,\n image: np.ndarray,\n size: Dict[str, int],\n resample: PILImageResampling = PILImageResampling.BICUBIC,\n data_format: Optional[Union[str, ChannelDimension]] = None,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n **kwargs,\n ) -> np.ndarray:\n \"\"\"\n Resize an image. The shortest edge of the image is resized to size[\"shortest_edge\"], with the longest edge\n resized to keep the input aspect ratio.\n\n Args:\n image (`np.ndarray`):\n Image to resize.\n size (`Dict[str, int]`):\n Size of the output image.\n resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):\n Resampling filter to use when resiizing the image.\n data_format (`str` or `ChannelDimension`, *optional*):\n The channel dimension format of the image. If not provided, it will be the same as the input image.\n input_data_format (`ChannelDimension` or `str`, *optional*):\n The channel dimension format of the input image. If not provided, it will be inferred.\n \"\"\"\n default_to_square = True\n if \"shortest_edge\" in size:\n size = size[\"shortest_edge\"]\n default_to_square = False\n elif \"height\" in size and \"width\" in size:\n size = (size[\"height\"], size[\"width\"])\n else:\n raise ValueError(\"Size must contain either 'shortest_edge' or 'height' and 'width'.\")\n\n output_size = get_resize_output_image_size(\n image,\n size=size,\n default_to_square=default_to_square,\n input_data_format=input_data_format,\n )\n return resize(\n image,\n size=output_size,\n resample=resample,\n data_format=data_format,\n input_data_format=input_data_format,\n **kwargs,\n )"}], "type": ["function_empty"], "node": ["transformers.image_utils.get_image_size", "transformers.image_transforms.get_resize_output_image_size", "transformers.image_transforms.resize", "transformers.models.video_llava.image_processing_video_llava.VideoLlavaImageProcessor.resize"], "language": "Python", "toolfunc_count": 4, "func_count": 4, "pytest_info": {"total_num": 18, "base_passed_num": 6}} {"id": ["transformers.src.transformers.image_processing_utils.get_size_dict", "transformers.src.transformers.image_utils.get_image_size", "transformers.src.transformers.image_transforms.get_resize_output_image_size", "transformers.src.transformers.image_transforms.resize", "transformers.src.transformers.models.videomae.image_processing_videomae.VideoMAEImageProcessor::resize"], "project": "transformers", "origin_file": ["transformers/image_processing_utils.py", "transformers/image_utils.py", "transformers/image_transforms.py", "transformers/image_transforms.py", "transformers/models/videomae/image_processing_videomae.py"], "test_list": ["tests/models/videomae/test_image_processing_videomae.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 287, "func_start_lineno": 208, "func_end_lineno": 249, "func_code": "def get_size_dict(\n size: Union[int, Iterable[int], Dict[str, int]] = None,\n max_size: Optional[int] = None,\n height_width_order: bool = True,\n default_to_square: bool = True,\n param_name=\"size\",\n) -> dict:\n \"\"\"\n Converts the old size parameter in the config into the new dict expected in the config. This is to ensure backwards\n compatibility with the old image processor configs and removes ambiguity over whether the tuple is in (height,\n width) or (width, height) format.\n\n - If `size` is tuple, it is converted to `{\"height\": size[0], \"width\": size[1]}` or `{\"height\": size[1], \"width\":\n size[0]}` if `height_width_order` is `False`.\n - If `size` is an int, and `default_to_square` is `True`, it is converted to `{\"height\": size, \"width\": size}`.\n - If `size` is an int and `default_to_square` is False, it is converted to `{\"shortest_edge\": size}`. If `max_size`\n is set, it is added to the dict as `{\"longest_edge\": max_size}`.\n\n Args:\n size (`Union[int, Iterable[int], Dict[str, int]]`, *optional*):\n The `size` parameter to be cast into a size dictionary.\n max_size (`Optional[int]`, *optional*):\n The `max_size` parameter to be cast into a size dictionary.\n height_width_order (`bool`, *optional*, defaults to `True`):\n If `size` is a tuple, whether it's in (height, width) or (width, height) order.\n default_to_square (`bool`, *optional*, defaults to `True`):\n If `size` is an int, whether to default to a square image or not.\n \"\"\"\n if not isinstance(size, dict):\n size_dict = convert_to_size_dict(size, max_size, default_to_square, height_width_order)\n logger.info(\n f\"{param_name} should be a dictionary on of the following set of keys: {VALID_SIZE_DICT_KEYS}, got {size}.\"\n f\" Converted to {size_dict}.\",\n )\n else:\n size_dict = size\n\n if not is_valid_size_dict(size_dict):\n raise ValueError(\n f\"{param_name} must have one of the following set of keys: {VALID_SIZE_DICT_KEYS}, got {size_dict.keys()}\"\n )\n return size_dict"}, {"class_start_lineno": 1, "class_end_lineno": 811, "func_start_lineno": 281, "func_end_lineno": 302, "func_code": "def get_image_size(image: np.ndarray, channel_dim: ChannelDimension = None) -> Tuple[int, int]:\n \"\"\"\n Returns the (height, width) dimensions of the image.\n\n Args:\n image (`np.ndarray`):\n The image to get the dimensions of.\n channel_dim (`ChannelDimension`, *optional*):\n Which dimension the channel dimension is in. If `None`, will infer the channel dimension from the image.\n\n Returns:\n A tuple of the image's height and width.\n \"\"\"\n if channel_dim is None:\n channel_dim = infer_channel_dimension_format(image)\n\n if channel_dim == ChannelDimension.FIRST:\n return image.shape[-2], image.shape[-1]\n elif channel_dim == ChannelDimension.LAST:\n return image.shape[-3], image.shape[-2]\n else:\n raise ValueError(f\"Unsupported data format: {channel_dim}\")"}, {"class_start_lineno": 1, "class_end_lineno": 854, "func_start_lineno": 214, "func_end_lineno": 278, "func_code": "def get_resize_output_image_size(\n input_image: np.ndarray,\n size: Union[int, Tuple[int, int], List[int], Tuple[int]],\n default_to_square: bool = True,\n max_size: Optional[int] = None,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n) -> tuple:\n \"\"\"\n Find the target (height, width) dimension of the output image after resizing given the input image and the desired\n size.\n\n Args:\n input_image (`np.ndarray`):\n The image to resize.\n size (`int` or `Tuple[int, int]` or List[int] or `Tuple[int]`):\n The size to use for resizing the image. If `size` is a sequence like (h, w), output size will be matched to\n this.\n\n If `size` is an int and `default_to_square` is `True`, then image will be resized to (size, size). If\n `size` is an int and `default_to_square` is `False`, then smaller edge of the image will be matched to this\n number. i.e, if height > width, then image will be rescaled to (size * height / width, size).\n default_to_square (`bool`, *optional*, defaults to `True`):\n How to convert `size` when it is a single int. If set to `True`, the `size` will be converted to a square\n (`size`,`size`). If set to `False`, will replicate\n [`torchvision.transforms.Resize`](https://pytorch.org/vision/stable/transforms.html#torchvision.transforms.Resize)\n with support for resizing only the smallest edge and providing an optional `max_size`.\n max_size (`int`, *optional*):\n The maximum allowed for the longer edge of the resized image: if the longer edge of the image is greater\n than `max_size` after being resized according to `size`, then the image is resized again so that the longer\n edge is equal to `max_size`. As a result, `size` might be overruled, i.e the smaller edge may be shorter\n than `size`. Only used if `default_to_square` is `False`.\n input_data_format (`ChannelDimension`, *optional*):\n The channel dimension format of the input image. If unset, will use the inferred format from the input.\n\n Returns:\n `tuple`: The target (height, width) dimension of the output image after resizing.\n \"\"\"\n if isinstance(size, (tuple, list)):\n if len(size) == 2:\n return tuple(size)\n elif len(size) == 1:\n # Perform same logic as if size was an int\n size = size[0]\n else:\n raise ValueError(\"size must have 1 or 2 elements if it is a list or tuple\")\n\n if default_to_square:\n return (size, size)\n\n height, width = get_image_size(input_image, input_data_format)\n short, long = (width, height) if width <= height else (height, width)\n requested_new_short = size\n\n new_short, new_long = requested_new_short, int(requested_new_short * long / short)\n\n if max_size is not None:\n if max_size <= requested_new_short:\n raise ValueError(\n f\"max_size = {max_size} must be strictly greater than the requested \"\n f\"size for the smaller edge size = {size}\"\n )\n if new_long > max_size:\n new_short, new_long = int(max_size * new_short / new_long), max_size\n\n return (new_long, new_short) if width <= height else (new_short, new_long)"}, {"class_start_lineno": 1, "class_end_lineno": 854, "func_start_lineno": 281, "func_end_lineno": 349, "func_code": "def resize(\n image: np.ndarray,\n size: Tuple[int, int],\n resample: \"PILImageResampling\" = None,\n reducing_gap: Optional[int] = None,\n data_format: Optional[ChannelDimension] = None,\n return_numpy: bool = True,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n) -> np.ndarray:\n \"\"\"\n Resizes `image` to `(height, width)` specified by `size` using the PIL library.\n\n Args:\n image (`np.ndarray`):\n The image to resize.\n size (`Tuple[int, int]`):\n The size to use for resizing the image.\n resample (`int`, *optional*, defaults to `PILImageResampling.BILINEAR`):\n The filter to user for resampling.\n reducing_gap (`int`, *optional*):\n Apply optimization by resizing the image in two steps. The bigger `reducing_gap`, the closer the result to\n the fair resampling. See corresponding Pillow documentation for more details.\n data_format (`ChannelDimension`, *optional*):\n The channel dimension format of the output image. If unset, will use the inferred format from the input.\n return_numpy (`bool`, *optional*, defaults to `True`):\n Whether or not to return the resized image as a numpy array. If False a `PIL.Image.Image` object is\n returned.\n input_data_format (`ChannelDimension`, *optional*):\n The channel dimension format of the input image. If unset, will use the inferred format from the input.\n\n Returns:\n `np.ndarray`: The resized image.\n \"\"\"\n requires_backends(resize, [\"vision\"])\n\n resample = resample if resample is not None else PILImageResampling.BILINEAR\n\n if not len(size) == 2:\n raise ValueError(\"size must have 2 elements\")\n\n # For all transformations, we want to keep the same data format as the input image unless otherwise specified.\n # The resized image from PIL will always have channels last, so find the input format first.\n if input_data_format is None:\n input_data_format = infer_channel_dimension_format(image)\n data_format = input_data_format if data_format is None else data_format\n\n # To maintain backwards compatibility with the resizing done in previous image feature extractors, we use\n # the pillow library to resize the image and then convert back to numpy\n do_rescale = False\n if not isinstance(image, PIL.Image.Image):\n do_rescale = _rescale_for_pil_conversion(image)\n image = to_pil_image(image, do_rescale=do_rescale, input_data_format=input_data_format)\n height, width = size\n # PIL images are in the format (width, height)\n resized_image = image.resize((width, height), resample=resample, reducing_gap=reducing_gap)\n\n if return_numpy:\n resized_image = np.array(resized_image)\n # If the input image channel dimension was of size 1, then it is dropped when converting to a PIL image\n # so we need to add it back if necessary.\n resized_image = np.expand_dims(resized_image, axis=-1) if resized_image.ndim == 2 else resized_image\n # The image is always in channels last format after converting from a PIL image\n resized_image = to_channel_dimension_format(\n resized_image, data_format, input_channel_dim=ChannelDimension.LAST\n )\n # If an image was rescaled to be in the range [0, 255] before converting to a PIL image, then we need to\n # rescale it back to the original range.\n resized_image = rescale(resized_image, 1 / 255) if do_rescale else resized_image\n return resized_image"}, {"class_start_lineno": 63, "class_end_lineno": 345, "func_start_lineno": 134, "func_end_lineno": 176, "func_code": " def resize(\n self,\n image: np.ndarray,\n size: Dict[str, int],\n resample: PILImageResampling = PILImageResampling.BILINEAR,\n data_format: Optional[Union[str, ChannelDimension]] = None,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n **kwargs,\n ) -> np.ndarray:\n \"\"\"\n Resize an image.\n\n Args:\n image (`np.ndarray`):\n Image to resize.\n size (`Dict[str, int]`):\n Size of the output image. If `size` is of the form `{\"height\": h, \"width\": w}`, the output image will\n have the size `(h, w)`. If `size` is of the form `{\"shortest_edge\": s}`, the output image will have its\n shortest edge of length `s` while keeping the aspect ratio of the original image.\n resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):\n Resampling filter to use when resiizing the image.\n data_format (`str` or `ChannelDimension`, *optional*):\n The channel dimension format of the image. If not provided, it will be the same as the input image.\n input_data_format (`str` or `ChannelDimension`, *optional*):\n The channel dimension format of the input image. If not provided, it will be inferred.\n \"\"\"\n size = get_size_dict(size, default_to_square=False)\n if \"shortest_edge\" in size:\n output_size = get_resize_output_image_size(\n image, size[\"shortest_edge\"], default_to_square=False, input_data_format=input_data_format\n )\n elif \"height\" in size and \"width\" in size:\n output_size = (size[\"height\"], size[\"width\"])\n else:\n raise ValueError(f\"Size must have 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}\")\n return resize(\n image,\n size=output_size,\n resample=resample,\n data_format=data_format,\n input_data_format=input_data_format,\n **kwargs,\n )"}], "type": ["function_empty"], "node": ["transformers.image_processing_utils.get_size_dict", "transformers.image_utils.get_image_size", "transformers.image_transforms.get_resize_output_image_size", "transformers.image_transforms.resize", "transformers.models.videomae.image_processing_videomae.VideoMAEImageProcessor.resize"], "language": "Python", "toolfunc_count": 5, "func_count": 5, "pytest_info": {"total_num": 13, "base_passed_num": 6}} {"id": ["transformers.src.transformers.image_processing_utils.get_size_dict", "transformers.src.transformers.image_utils.get_image_size", "transformers.src.transformers.image_transforms.get_resize_output_image_size", "transformers.src.transformers.image_transforms.resize", "transformers.src.transformers.models.vivit.image_processing_vivit.VivitImageProcessor::resize"], "project": "transformers", "origin_file": ["transformers/image_processing_utils.py", "transformers/image_utils.py", "transformers/image_transforms.py", "transformers/image_transforms.py", "transformers/models/vivit/image_processing_vivit.py"], "test_list": ["tests/models/vivit/test_image_processing_vivit.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 287, "func_start_lineno": 208, "func_end_lineno": 249, "func_code": "def get_size_dict(\n size: Union[int, Iterable[int], Dict[str, int]] = None,\n max_size: Optional[int] = None,\n height_width_order: bool = True,\n default_to_square: bool = True,\n param_name=\"size\",\n) -> dict:\n \"\"\"\n Converts the old size parameter in the config into the new dict expected in the config. This is to ensure backwards\n compatibility with the old image processor configs and removes ambiguity over whether the tuple is in (height,\n width) or (width, height) format.\n\n - If `size` is tuple, it is converted to `{\"height\": size[0], \"width\": size[1]}` or `{\"height\": size[1], \"width\":\n size[0]}` if `height_width_order` is `False`.\n - If `size` is an int, and `default_to_square` is `True`, it is converted to `{\"height\": size, \"width\": size}`.\n - If `size` is an int and `default_to_square` is False, it is converted to `{\"shortest_edge\": size}`. If `max_size`\n is set, it is added to the dict as `{\"longest_edge\": max_size}`.\n\n Args:\n size (`Union[int, Iterable[int], Dict[str, int]]`, *optional*):\n The `size` parameter to be cast into a size dictionary.\n max_size (`Optional[int]`, *optional*):\n The `max_size` parameter to be cast into a size dictionary.\n height_width_order (`bool`, *optional*, defaults to `True`):\n If `size` is a tuple, whether it's in (height, width) or (width, height) order.\n default_to_square (`bool`, *optional*, defaults to `True`):\n If `size` is an int, whether to default to a square image or not.\n \"\"\"\n if not isinstance(size, dict):\n size_dict = convert_to_size_dict(size, max_size, default_to_square, height_width_order)\n logger.info(\n f\"{param_name} should be a dictionary on of the following set of keys: {VALID_SIZE_DICT_KEYS}, got {size}.\"\n f\" Converted to {size_dict}.\",\n )\n else:\n size_dict = size\n\n if not is_valid_size_dict(size_dict):\n raise ValueError(\n f\"{param_name} must have one of the following set of keys: {VALID_SIZE_DICT_KEYS}, got {size_dict.keys()}\"\n )\n return size_dict"}, {"class_start_lineno": 1, "class_end_lineno": 811, "func_start_lineno": 281, "func_end_lineno": 302, "func_code": "def get_image_size(image: np.ndarray, channel_dim: ChannelDimension = None) -> Tuple[int, int]:\n \"\"\"\n Returns the (height, width) dimensions of the image.\n\n Args:\n image (`np.ndarray`):\n The image to get the dimensions of.\n channel_dim (`ChannelDimension`, *optional*):\n Which dimension the channel dimension is in. If `None`, will infer the channel dimension from the image.\n\n Returns:\n A tuple of the image's height and width.\n \"\"\"\n if channel_dim is None:\n channel_dim = infer_channel_dimension_format(image)\n\n if channel_dim == ChannelDimension.FIRST:\n return image.shape[-2], image.shape[-1]\n elif channel_dim == ChannelDimension.LAST:\n return image.shape[-3], image.shape[-2]\n else:\n raise ValueError(f\"Unsupported data format: {channel_dim}\")"}, {"class_start_lineno": 1, "class_end_lineno": 854, "func_start_lineno": 214, "func_end_lineno": 278, "func_code": "def get_resize_output_image_size(\n input_image: np.ndarray,\n size: Union[int, Tuple[int, int], List[int], Tuple[int]],\n default_to_square: bool = True,\n max_size: Optional[int] = None,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n) -> tuple:\n \"\"\"\n Find the target (height, width) dimension of the output image after resizing given the input image and the desired\n size.\n\n Args:\n input_image (`np.ndarray`):\n The image to resize.\n size (`int` or `Tuple[int, int]` or List[int] or `Tuple[int]`):\n The size to use for resizing the image. If `size` is a sequence like (h, w), output size will be matched to\n this.\n\n If `size` is an int and `default_to_square` is `True`, then image will be resized to (size, size). If\n `size` is an int and `default_to_square` is `False`, then smaller edge of the image will be matched to this\n number. i.e, if height > width, then image will be rescaled to (size * height / width, size).\n default_to_square (`bool`, *optional*, defaults to `True`):\n How to convert `size` when it is a single int. If set to `True`, the `size` will be converted to a square\n (`size`,`size`). If set to `False`, will replicate\n [`torchvision.transforms.Resize`](https://pytorch.org/vision/stable/transforms.html#torchvision.transforms.Resize)\n with support for resizing only the smallest edge and providing an optional `max_size`.\n max_size (`int`, *optional*):\n The maximum allowed for the longer edge of the resized image: if the longer edge of the image is greater\n than `max_size` after being resized according to `size`, then the image is resized again so that the longer\n edge is equal to `max_size`. As a result, `size` might be overruled, i.e the smaller edge may be shorter\n than `size`. Only used if `default_to_square` is `False`.\n input_data_format (`ChannelDimension`, *optional*):\n The channel dimension format of the input image. If unset, will use the inferred format from the input.\n\n Returns:\n `tuple`: The target (height, width) dimension of the output image after resizing.\n \"\"\"\n if isinstance(size, (tuple, list)):\n if len(size) == 2:\n return tuple(size)\n elif len(size) == 1:\n # Perform same logic as if size was an int\n size = size[0]\n else:\n raise ValueError(\"size must have 1 or 2 elements if it is a list or tuple\")\n\n if default_to_square:\n return (size, size)\n\n height, width = get_image_size(input_image, input_data_format)\n short, long = (width, height) if width <= height else (height, width)\n requested_new_short = size\n\n new_short, new_long = requested_new_short, int(requested_new_short * long / short)\n\n if max_size is not None:\n if max_size <= requested_new_short:\n raise ValueError(\n f\"max_size = {max_size} must be strictly greater than the requested \"\n f\"size for the smaller edge size = {size}\"\n )\n if new_long > max_size:\n new_short, new_long = int(max_size * new_short / new_long), max_size\n\n return (new_long, new_short) if width <= height else (new_short, new_long)"}, {"class_start_lineno": 1, "class_end_lineno": 854, "func_start_lineno": 281, "func_end_lineno": 349, "func_code": "def resize(\n image: np.ndarray,\n size: Tuple[int, int],\n resample: \"PILImageResampling\" = None,\n reducing_gap: Optional[int] = None,\n data_format: Optional[ChannelDimension] = None,\n return_numpy: bool = True,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n) -> np.ndarray:\n \"\"\"\n Resizes `image` to `(height, width)` specified by `size` using the PIL library.\n\n Args:\n image (`np.ndarray`):\n The image to resize.\n size (`Tuple[int, int]`):\n The size to use for resizing the image.\n resample (`int`, *optional*, defaults to `PILImageResampling.BILINEAR`):\n The filter to user for resampling.\n reducing_gap (`int`, *optional*):\n Apply optimization by resizing the image in two steps. The bigger `reducing_gap`, the closer the result to\n the fair resampling. See corresponding Pillow documentation for more details.\n data_format (`ChannelDimension`, *optional*):\n The channel dimension format of the output image. If unset, will use the inferred format from the input.\n return_numpy (`bool`, *optional*, defaults to `True`):\n Whether or not to return the resized image as a numpy array. If False a `PIL.Image.Image` object is\n returned.\n input_data_format (`ChannelDimension`, *optional*):\n The channel dimension format of the input image. If unset, will use the inferred format from the input.\n\n Returns:\n `np.ndarray`: The resized image.\n \"\"\"\n requires_backends(resize, [\"vision\"])\n\n resample = resample if resample is not None else PILImageResampling.BILINEAR\n\n if not len(size) == 2:\n raise ValueError(\"size must have 2 elements\")\n\n # For all transformations, we want to keep the same data format as the input image unless otherwise specified.\n # The resized image from PIL will always have channels last, so find the input format first.\n if input_data_format is None:\n input_data_format = infer_channel_dimension_format(image)\n data_format = input_data_format if data_format is None else data_format\n\n # To maintain backwards compatibility with the resizing done in previous image feature extractors, we use\n # the pillow library to resize the image and then convert back to numpy\n do_rescale = False\n if not isinstance(image, PIL.Image.Image):\n do_rescale = _rescale_for_pil_conversion(image)\n image = to_pil_image(image, do_rescale=do_rescale, input_data_format=input_data_format)\n height, width = size\n # PIL images are in the format (width, height)\n resized_image = image.resize((width, height), resample=resample, reducing_gap=reducing_gap)\n\n if return_numpy:\n resized_image = np.array(resized_image)\n # If the input image channel dimension was of size 1, then it is dropped when converting to a PIL image\n # so we need to add it back if necessary.\n resized_image = np.expand_dims(resized_image, axis=-1) if resized_image.ndim == 2 else resized_image\n # The image is always in channels last format after converting from a PIL image\n resized_image = to_channel_dimension_format(\n resized_image, data_format, input_channel_dim=ChannelDimension.LAST\n )\n # If an image was rescaled to be in the range [0, 255] before converting to a PIL image, then we need to\n # rescale it back to the original range.\n resized_image = rescale(resized_image, 1 / 255) if do_rescale else resized_image\n return resized_image"}, {"class_start_lineno": 66, "class_end_lineno": 404, "func_start_lineno": 142, "func_end_lineno": 184, "func_code": " def resize(\n self,\n image: np.ndarray,\n size: Dict[str, int],\n resample: PILImageResampling = PILImageResampling.BILINEAR,\n data_format: Optional[Union[str, ChannelDimension]] = None,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n **kwargs,\n ) -> np.ndarray:\n \"\"\"\n Resize an image.\n\n Args:\n image (`np.ndarray`):\n Image to resize.\n size (`Dict[str, int]`):\n Size of the output image. If `size` is of the form `{\"height\": h, \"width\": w}`, the output image will\n have the size `(h, w)`. If `size` is of the form `{\"shortest_edge\": s}`, the output image will have its\n shortest edge of length `s` while keeping the aspect ratio of the original image.\n resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):\n Resampling filter to use when resiizing the image.\n data_format (`str` or `ChannelDimension`, *optional*):\n The channel dimension format of the image. If not provided, it will be the same as the input image.\n input_data_format (`str` or `ChannelDimension`, *optional*):\n The channel dimension format of the input image. If not provided, it will be inferred.\n \"\"\"\n size = get_size_dict(size, default_to_square=False)\n if \"shortest_edge\" in size:\n output_size = get_resize_output_image_size(\n image, size[\"shortest_edge\"], default_to_square=False, input_data_format=input_data_format\n )\n elif \"height\" in size and \"width\" in size:\n output_size = (size[\"height\"], size[\"width\"])\n else:\n raise ValueError(f\"Size must have 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}\")\n return resize(\n image,\n size=output_size,\n resample=resample,\n data_format=data_format,\n input_data_format=input_data_format,\n **kwargs,\n )"}], "type": ["function_empty", "Development"], "node": ["transformers.image_processing_utils.get_size_dict", "transformers.image_utils.get_image_size", "transformers.image_transforms.get_resize_output_image_size", "transformers.image_transforms.resize", "transformers.models.vivit.image_processing_vivit.VivitImageProcessor.resize"], "language": "Python", "toolfunc_count": 4, "func_count": 5, "pytest_info": {"total_num": 14, "base_passed_num": 7}} {"id": ["transformers.src.transformers.utils.generic._get_frameworks_and_test_func", "transformers.src.transformers.models.wav2vec2.tokenization_wav2vec2.Wav2Vec2CTCTokenizer::decode", "transformers.src.transformers.models.wav2vec2.tokenization_wav2vec2.Wav2Vec2CTCTokenizer::convert_tokens_to_string", "transformers.src.transformers.models.wav2vec2.tokenization_wav2vec2.Wav2Vec2CTCTokenizer::_decode"], "project": "transformers", "origin_file": ["transformers/utils/generic.py", "transformers/models/wav2vec2/tokenization_wav2vec2.py", "transformers/models/wav2vec2/tokenization_wav2vec2.py", "transformers/models/wav2vec2/tokenization_wav2vec2.py"], "test_list": ["tests/models/wav2vec2/test_tokenization_wav2vec2.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 856, "func_start_lineno": 98, "func_end_lineno": 116, "func_code": "def _get_frameworks_and_test_func(x):\n \"\"\"\n Returns an (ordered since we are in Python 3.7+) dictionary framework to test function, which places the framework\n we can guess from the repr first, then Numpy, then the others.\n \"\"\"\n framework_to_test = {\n \"pt\": is_torch_tensor,\n \"tf\": is_tf_tensor,\n \"jax\": is_jax_tensor,\n \"np\": is_numpy_array,\n \"mlx\": is_mlx_array,\n }\n preferred_framework = infer_framework_from_repr(x)\n # We will test this one first, then numpy, then the others.\n frameworks = [] if preferred_framework is None else [preferred_framework]\n if preferred_framework != \"np\":\n frameworks.append(\"np\")\n frameworks.extend([f for f in framework_to_test if f not in [preferred_framework, \"np\"]])\n return {f: framework_to_test[f] for f in frameworks}"}, {"class_start_lineno": 115, "class_end_lineno": 644, "func_start_lineno": 528, "func_end_lineno": 631, "func_code": " def decode(\n self,\n token_ids: Union[int, List[int], \"np.ndarray\", \"torch.Tensor\", \"tf.Tensor\"],\n skip_special_tokens: bool = False,\n clean_up_tokenization_spaces: bool = None,\n output_char_offsets: bool = False,\n output_word_offsets: bool = False,\n **kwargs,\n ) -> str:\n \"\"\"\n Converts a sequence of ids in a string, using the tokenizer and vocabulary with options to remove special\n tokens and clean up tokenization spaces.\n\n Similar to doing `self.convert_tokens_to_string(self.convert_ids_to_tokens(token_ids))`.\n\n Args:\n token_ids (`Union[int, List[int], np.ndarray, torch.Tensor, tf.Tensor]`):\n List of tokenized input ids. Can be obtained using the `__call__` method.\n skip_special_tokens (`bool`, *optional*, defaults to `False`):\n Whether or not to remove special tokens in the decoding.\n clean_up_tokenization_spaces (`bool`, *optional*):\n Whether or not to clean up the tokenization spaces.\n output_char_offsets (`bool`, *optional*, defaults to `False`):\n Whether or not to output character offsets. Character offsets can be used in combination with the\n sampling rate and model downsampling rate to compute the time-stamps of transcribed characters.\n\n \n\n Please take a look at the example below to better understand how to make use of `output_char_offsets`.\n\n \n\n output_word_offsets (`bool`, *optional*, defaults to `False`):\n Whether or not to output word offsets. Word offsets can be used in combination with the sampling rate\n and model downsampling rate to compute the time-stamps of transcribed words.\n\n \n\n Please take a look at the example below to better understand how to make use of `output_word_offsets`.\n\n \n\n kwargs (additional keyword arguments, *optional*):\n Will be passed to the underlying model specific decode method.\n\n Returns:\n `str` or [`~models.wav2vec2.tokenization_wav2vec2.Wav2Vec2CTCTokenizerOutput`]: The list of decoded\n sentences. Will be a [`~models.wav2vec2.tokenization_wav2vec2.Wav2Vec2CTCTokenizerOutput`] when\n `output_char_offsets == True` or `output_word_offsets == True`.\n\n Example:\n\n ```python\n >>> # Let's see how to retrieve time steps for a model\n >>> from transformers import AutoTokenizer, AutoFeatureExtractor, AutoModelForCTC\n >>> from datasets import load_dataset\n >>> import datasets\n >>> import torch\n\n >>> # import model, feature extractor, tokenizer\n >>> model = AutoModelForCTC.from_pretrained(\"facebook/wav2vec2-base-960h\")\n >>> tokenizer = AutoTokenizer.from_pretrained(\"facebook/wav2vec2-base-960h\")\n >>> feature_extractor = AutoFeatureExtractor.from_pretrained(\"facebook/wav2vec2-base-960h\")\n\n >>> # load first sample of English common_voice\n >>> dataset = load_dataset(\"mozilla-foundation/common_voice_11_0\", \"en\", split=\"train\", streaming=True, trust_remote_code=True)\n >>> dataset = dataset.cast_column(\"audio\", datasets.Audio(sampling_rate=16_000))\n >>> dataset_iter = iter(dataset)\n >>> sample = next(dataset_iter)\n\n >>> # forward sample through model to get greedily predicted transcription ids\n >>> input_values = feature_extractor(sample[\"audio\"][\"array\"], return_tensors=\"pt\").input_values\n >>> logits = model(input_values).logits[0]\n >>> pred_ids = torch.argmax(logits, axis=-1)\n\n >>> # retrieve word stamps (analogous commands for `output_char_offsets`)\n >>> outputs = tokenizer.decode(pred_ids, output_word_offsets=True)\n >>> # compute `time_offset` in seconds as product of downsampling ratio and sampling_rate\n >>> time_offset = model.config.inputs_to_logits_ratio / feature_extractor.sampling_rate\n\n >>> word_offsets = [\n ... {\n ... \"word\": d[\"word\"],\n ... \"start_time\": round(d[\"start_offset\"] * time_offset, 2),\n ... \"end_time\": round(d[\"end_offset\"] * time_offset, 2),\n ... }\n ... for d in outputs.word_offsets\n ... ]\n >>> # compare word offsets with audio `en_train_0/common_voice_en_19121553.mp3` online on the dataset viewer:\n >>> # https://huggingface.co/datasets/mozilla-foundation/common_voice_11_0/viewer/en\n >>> word_offsets[:3]\n [{'word': 'THE', 'start_time': 0.7, 'end_time': 0.78}, {'word': 'TRICK', 'start_time': 0.88, 'end_time': 1.08}, {'word': 'APPEARS', 'start_time': 1.2, 'end_time': 1.64}]\n ```\"\"\"\n # Convert inputs to python lists\n token_ids = to_py_obj(token_ids)\n\n return self._decode(\n token_ids=token_ids,\n skip_special_tokens=skip_special_tokens,\n clean_up_tokenization_spaces=clean_up_tokenization_spaces,\n output_char_offsets=output_char_offsets,\n output_word_offsets=output_word_offsets,\n **kwargs,\n )"}, {"class_start_lineno": 115, "class_end_lineno": 644, "func_start_lineno": 285, "func_end_lineno": 346, "func_code": " def convert_tokens_to_string(\n self,\n tokens: List[str],\n group_tokens: bool = True,\n spaces_between_special_tokens: bool = False,\n output_char_offsets: bool = False,\n output_word_offsets: bool = False,\n ) -> Dict[str, Union[str, float]]:\n \"\"\"\n Converts a connectionist-temporal-classification (CTC) output tokens into a single string.\n \"\"\"\n if len(tokens) == 0:\n return {\"text\": \"\", \"char_offsets\": [], \"word_offsets\": []}\n # group same tokens into non-repeating tokens in CTC style decoding\n if group_tokens:\n chars, char_repetitions = zip(*((token, len(list(group_iter))) for token, group_iter in groupby(tokens)))\n else:\n chars = tokens\n char_repetitions = len(tokens) * [1]\n\n # filter self.pad_token which is used as CTC-blank token\n processed_chars = list(filter(lambda char: char != self.pad_token, chars))\n\n # replace delimiter token\n processed_chars = [\n self.replace_word_delimiter_char if char == self.word_delimiter_token else char for char in processed_chars\n ]\n\n # retrieve offsets\n char_offsets = word_offsets = None\n if output_char_offsets or output_word_offsets:\n char_offsets = self._compute_offsets(char_repetitions, chars, self.pad_token)\n\n if len(char_offsets) != len(processed_chars):\n raise ValueError(\n f\"`char_offsets`: {char_offsets} and `processed_tokens`: {processed_chars}\"\n \" have to be of the same length, but are: \"\n f\"`len(offsets)`: {len(char_offsets)} and `len(processed_tokens)`:\"\n f\" {len(processed_chars)}\"\n )\n\n # set tokens to correct processed token\n for i, char in enumerate(processed_chars):\n char_offsets[i][\"char\"] = char\n\n # retrieve word offsets from character offsets\n word_offsets = None\n if output_word_offsets:\n word_offsets = self._get_word_offsets(char_offsets, self.replace_word_delimiter_char)\n\n # don't output chars if not set to True\n if not output_char_offsets:\n char_offsets = None\n\n # join to string\n join_char = \" \" if spaces_between_special_tokens else \"\"\n string = join_char.join(processed_chars).strip()\n\n if self.do_lower_case:\n string = string.lower()\n\n return {\"text\": string, \"char_offsets\": char_offsets, \"word_offsets\": word_offsets}"}, {"class_start_lineno": 115, "class_end_lineno": 644, "func_start_lineno": 403, "func_end_lineno": 453, "func_code": " def _decode(\n self,\n token_ids: List[int],\n skip_special_tokens: bool = False,\n clean_up_tokenization_spaces: bool = None,\n group_tokens: bool = True,\n spaces_between_special_tokens: bool = False,\n output_word_offsets: Optional[bool] = False,\n output_char_offsets: Optional[bool] = False,\n ) -> str:\n \"\"\"\n special _decode function is needed for Wav2Vec2Tokenizer because added tokens should be treated exactly the\n same as tokens of the base vocabulary and therefore the function `convert_tokens_to_string` has to be called on\n the whole token list and not individually on added tokens\n \"\"\"\n filtered_tokens = self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens)\n\n result = []\n for token in filtered_tokens:\n if skip_special_tokens and (\n token in self.all_special_ids or (token != self.pad_token and token in self.all_special_tokens)\n ):\n continue\n result.append(token)\n\n string_output = self.convert_tokens_to_string(\n result,\n group_tokens=group_tokens,\n spaces_between_special_tokens=spaces_between_special_tokens,\n output_word_offsets=output_word_offsets,\n output_char_offsets=output_char_offsets,\n )\n\n text = string_output[\"text\"]\n\n clean_up_tokenization_spaces = (\n clean_up_tokenization_spaces\n if clean_up_tokenization_spaces is not None\n else self.clean_up_tokenization_spaces\n )\n if clean_up_tokenization_spaces:\n text = self.clean_up_tokenization(text)\n\n if output_word_offsets or output_char_offsets:\n return Wav2Vec2CTCTokenizerOutput(\n text=text,\n char_offsets=string_output[\"char_offsets\"],\n word_offsets=string_output[\"word_offsets\"],\n )\n else:\n return text"}], "type": ["function_empty", "Development"], "node": ["transformers.utils.generic._get_frameworks_and_test_func", "transformers.models.wav2vec2.tokenization_wav2vec2.Wav2Vec2CTCTokenizer.decode", "transformers.models.wav2vec2.tokenization_wav2vec2.Wav2Vec2CTCTokenizer.convert_tokens_to_string", "transformers.models.wav2vec2.tokenization_wav2vec2.Wav2Vec2CTCTokenizer._decode"], "language": "Python", "toolfunc_count": 1, "func_count": 4, "pytest_info": {"total_num": 102, "base_passed_num": 79}} {"id": ["transformers.src.transformers.audio_utils.hertz_to_mel", "transformers.src.transformers.audio_utils.mel_filter_bank", "transformers.src.transformers.audio_utils.window_function", "transformers.src.transformers.models.whisper.feature_extraction_whisper.WhisperFeatureExtractor::_np_extract_fbank_features"], "project": "transformers", "origin_file": ["transformers/audio_utils.py", "transformers/audio_utils.py", "transformers/models/whisper/feature_extraction_whisper.py", "transformers/audio_utils.py", "transformers/models/whisper/feature_extraction_whisper.py"], "test_list": ["tests/models/whisper/test_feature_extraction_whisper.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 1127, "func_start_lineno": 26, "func_end_lineno": 59, "func_code": "def hertz_to_mel(freq: Union[float, np.ndarray], mel_scale: str = \"htk\") -> Union[float, np.ndarray]:\n \"\"\"\n Convert frequency from hertz to mels.\n\n Args:\n freq (`float` or `np.ndarray`):\n The frequency, or multiple frequencies, in hertz (Hz).\n mel_scale (`str`, *optional*, defaults to `\"htk\"`):\n The mel frequency scale to use, `\"htk\"`, `\"kaldi\"` or `\"slaney\"`.\n\n Returns:\n `float` or `np.ndarray`: The frequencies on the mel scale.\n \"\"\"\n\n if mel_scale not in [\"slaney\", \"htk\", \"kaldi\"]:\n raise ValueError('mel_scale should be one of \"htk\", \"slaney\" or \"kaldi\".')\n\n if mel_scale == \"htk\":\n return 2595.0 * np.log10(1.0 + (freq / 700.0))\n elif mel_scale == \"kaldi\":\n return 1127.0 * np.log(1.0 + (freq / 700.0))\n\n min_log_hertz = 1000.0\n min_log_mel = 15.0\n logstep = 27.0 / np.log(6.4)\n mels = 3.0 * freq / 200.0\n\n if isinstance(freq, np.ndarray):\n log_region = freq >= min_log_hertz\n mels[log_region] = min_log_mel + np.log(freq[log_region] / min_log_hertz) * logstep\n elif freq >= min_log_hertz:\n mels = min_log_mel + np.log(freq / min_log_hertz) * logstep\n\n return mels"}, {"class_start_lineno": 1, "class_end_lineno": 1127, "func_start_lineno": 218, "func_end_lineno": 303, "func_code": "def mel_filter_bank(\n num_frequency_bins: int,\n num_mel_filters: int,\n min_frequency: float,\n max_frequency: float,\n sampling_rate: int,\n norm: Optional[str] = None,\n mel_scale: str = \"htk\",\n triangularize_in_mel_space: bool = False,\n) -> np.ndarray:\n \"\"\"\n Creates a frequency bin conversion matrix used to obtain a mel spectrogram. This is called a *mel filter bank*, and\n various implementation exist, which differ in the number of filters, the shape of the filters, the way the filters\n are spaced, the bandwidth of the filters, and the manner in which the spectrum is warped. The goal of these\n features is to approximate the non-linear human perception of the variation in pitch with respect to the frequency.\n\n Different banks of mel filters were introduced in the literature. The following variations are supported:\n\n - MFCC FB-20: introduced in 1980 by Davis and Mermelstein, it assumes a sampling frequency of 10 kHz and a speech\n bandwidth of `[0, 4600]` Hz.\n - MFCC FB-24 HTK: from the Cambridge HMM Toolkit (HTK) (1995) uses a filter bank of 24 filters for a speech\n bandwidth of `[0, 8000]` Hz. This assumes sampling rate ≥ 16 kHz.\n - MFCC FB-40: from the Auditory Toolbox for MATLAB written by Slaney in 1998, assumes a sampling rate of 16 kHz and\n speech bandwidth of `[133, 6854]` Hz. This version also includes area normalization.\n - HFCC-E FB-29 (Human Factor Cepstral Coefficients) of Skowronski and Harris (2004), assumes a sampling rate of\n 12.5 kHz and speech bandwidth of `[0, 6250]` Hz.\n\n This code is adapted from *torchaudio* and *librosa*. Note that the default parameters of torchaudio's\n `melscale_fbanks` implement the `\"htk\"` filters while librosa uses the `\"slaney\"` implementation.\n\n Args:\n num_frequency_bins (`int`):\n Number of frequencies used to compute the spectrogram (should be the same as in `stft`).\n num_mel_filters (`int`):\n Number of mel filters to generate.\n min_frequency (`float`):\n Lowest frequency of interest in Hz.\n max_frequency (`float`):\n Highest frequency of interest in Hz. This should not exceed `sampling_rate / 2`.\n sampling_rate (`int`):\n Sample rate of the audio waveform.\n norm (`str`, *optional*):\n If `\"slaney\"`, divide the triangular mel weights by the width of the mel band (area normalization).\n mel_scale (`str`, *optional*, defaults to `\"htk\"`):\n The mel frequency scale to use, `\"htk\"`, `\"kaldi\"` or `\"slaney\"`.\n triangularize_in_mel_space (`bool`, *optional*, defaults to `False`):\n If this option is enabled, the triangular filter is applied in mel space rather than frequency space. This\n should be set to `true` in order to get the same results as `torchaudio` when computing mel filters.\n\n Returns:\n `np.ndarray` of shape (`num_frequency_bins`, `num_mel_filters`): Triangular filter bank matrix. This is a\n projection matrix to go from a spectrogram to a mel spectrogram.\n \"\"\"\n if norm is not None and norm != \"slaney\":\n raise ValueError('norm must be one of None or \"slaney\"')\n\n # center points of the triangular mel filters\n mel_min = hertz_to_mel(min_frequency, mel_scale=mel_scale)\n mel_max = hertz_to_mel(max_frequency, mel_scale=mel_scale)\n mel_freqs = np.linspace(mel_min, mel_max, num_mel_filters + 2)\n filter_freqs = mel_to_hertz(mel_freqs, mel_scale=mel_scale)\n\n if triangularize_in_mel_space:\n # frequencies of FFT bins in Hz, but filters triangularized in mel space\n fft_bin_width = sampling_rate / (num_frequency_bins * 2)\n fft_freqs = hertz_to_mel(fft_bin_width * np.arange(num_frequency_bins), mel_scale=mel_scale)\n filter_freqs = mel_freqs\n else:\n # frequencies of FFT bins in Hz\n fft_freqs = np.linspace(0, sampling_rate // 2, num_frequency_bins)\n\n mel_filters = _create_triangular_filter_bank(fft_freqs, filter_freqs)\n\n if norm is not None and norm == \"slaney\":\n # Slaney-style mel is scaled to be approx constant energy per channel\n enorm = 2.0 / (filter_freqs[2 : num_mel_filters + 2] - filter_freqs[:num_mel_filters])\n mel_filters *= np.expand_dims(enorm, 0)\n\n if (mel_filters.max(axis=0) == 0.0).any():\n warnings.warn(\n \"At least one mel filter has all zero values. \"\n f\"The value for `num_mel_filters` ({num_mel_filters}) may be set too high. \"\n f\"Or, the value for `num_frequency_bins` ({num_frequency_bins}) may be set too low.\"\n )\n\n return mel_filters"}, {"class_start_lineno": 36, "class_end_lineno": 324, "func_start_lineno": 64, "func_end_lineno": 96, "func_code": " def __init__(\n self,\n feature_size=80,\n sampling_rate=16000,\n hop_length=160,\n chunk_length=30,\n n_fft=400,\n padding_value=0.0,\n return_attention_mask=False, # pad inputs to max length with silence token (zero) and no attention mask\n **kwargs,\n ):\n super().__init__(\n feature_size=feature_size,\n sampling_rate=sampling_rate,\n padding_value=padding_value,\n return_attention_mask=return_attention_mask,\n **kwargs,\n )\n self.n_fft = n_fft\n self.hop_length = hop_length\n self.chunk_length = chunk_length\n self.n_samples = chunk_length * sampling_rate\n self.nb_max_frames = self.n_samples // hop_length\n self.sampling_rate = sampling_rate\n self.mel_filters = mel_filter_bank(\n num_frequency_bins=1 + n_fft // 2,\n num_mel_filters=feature_size,\n min_frequency=0.0,\n max_frequency=8000.0,\n sampling_rate=sampling_rate,\n norm=\"slaney\",\n mel_scale=\"slaney\",\n )"}, {"class_start_lineno": 1, "class_end_lineno": 1127, "func_start_lineno": 319, "func_end_lineno": 379, "func_code": "def window_function(\n window_length: int,\n name: str = \"hann\",\n periodic: bool = True,\n frame_length: Optional[int] = None,\n center: bool = True,\n) -> np.ndarray:\n \"\"\"\n Returns an array containing the specified window. This window is intended to be used with `stft`.\n\n The following window types are supported:\n\n - `\"boxcar\"`: a rectangular window\n - `\"hamming\"`: the Hamming window\n - `\"hann\"`: the Hann window\n - `\"povey\"`: the Povey window\n\n Args:\n window_length (`int`):\n The length of the window in samples.\n name (`str`, *optional*, defaults to `\"hann\"`):\n The name of the window function.\n periodic (`bool`, *optional*, defaults to `True`):\n Whether the window is periodic or symmetric.\n frame_length (`int`, *optional*):\n The length of the analysis frames in samples. Provide a value for `frame_length` if the window is smaller\n than the frame length, so that it will be zero-padded.\n center (`bool`, *optional*, defaults to `True`):\n Whether to center the window inside the FFT buffer. Only used when `frame_length` is provided.\n\n Returns:\n `np.ndarray` of shape `(window_length,)` or `(frame_length,)` containing the window.\n \"\"\"\n length = window_length + 1 if periodic else window_length\n\n if name == \"boxcar\":\n window = np.ones(length)\n elif name in [\"hamming\", \"hamming_window\"]:\n window = np.hamming(length)\n elif name in [\"hann\", \"hann_window\"]:\n window = np.hanning(length)\n elif name in [\"povey\"]:\n window = np.power(np.hanning(length), 0.85)\n else:\n raise ValueError(f\"Unknown window function '{name}'\")\n\n if periodic:\n window = window[:-1]\n\n if frame_length is None:\n return window\n\n if window_length > frame_length:\n raise ValueError(\n f\"Length of the window ({window_length}) may not be larger than frame_length ({frame_length})\"\n )\n\n padded_window = np.zeros(frame_length)\n offset = (frame_length - window_length) // 2 if center else 0\n padded_window[offset : offset + window_length] = window\n return padded_window"}, {"class_start_lineno": 36, "class_end_lineno": 324, "func_start_lineno": 98, "func_end_lineno": 125, "func_code": " def _np_extract_fbank_features(self, waveform_batch: np.array, device: str) -> np.ndarray:\n \"\"\"\n Compute the log-mel spectrogram of the provided audio, gives similar results to Whisper's original torch\n implementation with 1e-5 tolerance.\n \"\"\"\n if device != \"cpu\":\n raise ValueError(\n f\"Got device `{device}` for feature extraction, but feature extraction on CUDA accelerator \"\n \"devices requires torch, which is not installed. Either set `device='cpu'`, or \"\n \"install torch according to the official instructions: https://pytorch.org/get-started/locally/\"\n )\n log_spec_batch = []\n for waveform in waveform_batch:\n log_spec = spectrogram(\n waveform,\n window_function(self.n_fft, \"hann\"),\n frame_length=self.n_fft,\n hop_length=self.hop_length,\n power=2.0,\n mel_filters=self.mel_filters,\n log_mel=\"log10\",\n )\n log_spec = log_spec[:, :-1]\n log_spec = np.maximum(log_spec, log_spec.max() - 8.0)\n log_spec = (log_spec + 4.0) / 4.0\n log_spec_batch.append(log_spec)\n log_spec_batch = np.array(log_spec_batch)\n return log_spec_batch"}], "type": ["function_empty", "Development"], "node": ["transformers.audio_utils.hertz_to_mel", "transformers.audio_utils.mel_filter_bank", "transformers.models.whisper.feature_extraction_whisper.WhisperFeatureExtractor.__init__", "transformers.audio_utils.window_function", "transformers.models.whisper.feature_extraction_whisper.WhisperFeatureExtractor._np_extract_fbank_features"], "language": "Python", "toolfunc_count": 3, "func_count": 4, "pytest_info": {"total_num": 19, "base_passed_num": 8}} {"id": ["transformers.src.transformers.utils.import_utils.create_import_structure_from_path", "transformers.src.transformers.utils.import_utils.define_import_structure"], "project": "transformers", "origin_file": ["transformers/utils/import_utils.py", "transformers/utils/import_utils.py"], "test_list": ["tests/utils/test_dynamic_module_utils.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 2158, "func_start_lineno": 1846, "func_end_lineno": 2037, "func_code": "def create_import_structure_from_path(module_path):\n \"\"\"\n This method takes the path to a file/a folder and returns the import structure.\n If a file is given, it will return the import structure of the parent folder.\n\n Import structures are designed to be digestible by `_LazyModule` objects. They are\n created from the __all__ definitions in each files as well as the `@export` decorators\n above methods and objects.\n\n The import structure allows explicit display of the required backends for a given object.\n These backends are specified in two ways:\n\n 1. Through their `@export`, if they are exported with that decorator. This `@export` decorator\n accepts a `backend` tuple kwarg mentioning which backends are required to run this object.\n\n 2. If an object is defined in a file with \"default\" backends, it will have, at a minimum, this\n backend specified. The default backends are defined according to the filename:\n\n - If a file is named like `modeling_*.py`, it will have a `torch` backend\n - If a file is named like `modeling_tf_*.py`, it will have a `tf` backend\n - If a file is named like `modeling_flax_*.py`, it will have a `flax` backend\n - If a file is named like `tokenization_*_fast.py`, it will have a `tokenizers` backend\n\n Backends serve the purpose of displaying a clear error message to the user in case the backends are not installed.\n Should an object be imported without its required backends being in the environment, any attempt to use the\n object will raise an error mentioning which backend(s) should be added to the environment in order to use\n that object.\n\n Here's an example of an input import structure at the src.transformers.models level:\n\n {\n 'albert': {\n frozenset(): {\n 'configuration_albert': {'AlbertConfig', 'AlbertOnnxConfig'}\n },\n frozenset({'tokenizers'}): {\n 'tokenization_albert_fast': {'AlbertTokenizerFast'}\n },\n },\n 'align': {\n frozenset(): {\n 'configuration_align': {'AlignConfig', 'AlignTextConfig', 'AlignVisionConfig'},\n 'processing_align': {'AlignProcessor'}\n },\n },\n 'altclip': {\n frozenset(): {\n 'configuration_altclip': {'AltCLIPConfig', 'AltCLIPTextConfig', 'AltCLIPVisionConfig'},\n 'processing_altclip': {'AltCLIPProcessor'},\n }\n }\n }\n \"\"\"\n import_structure = {}\n if os.path.isdir(module_path):\n directory = module_path\n adjacent_modules = []\n\n for f in os.listdir(module_path):\n if f != \"__pycache__\" and os.path.isdir(os.path.join(module_path, f)):\n import_structure[f] = create_import_structure_from_path(os.path.join(module_path, f))\n\n elif not os.path.isdir(os.path.join(directory, f)):\n adjacent_modules.append(f)\n\n else:\n directory = os.path.dirname(module_path)\n adjacent_modules = [f for f in os.listdir(directory) if not os.path.isdir(os.path.join(directory, f))]\n\n # We're only taking a look at files different from __init__.py\n # We could theoretically export things directly from the __init__.py\n # files, but this is not supported at this time.\n if \"__init__.py\" in adjacent_modules:\n adjacent_modules.remove(\"__init__.py\")\n\n module_requirements = {}\n for module_name in adjacent_modules:\n # Only modules ending in `.py` are accepted here.\n if not module_name.endswith(\".py\"):\n continue\n\n with open(os.path.join(directory, module_name)) as f:\n file_content = f.read()\n\n # Remove the .py suffix\n module_name = module_name[:-3]\n\n previous_line = \"\"\n previous_index = 0\n\n # Some files have some requirements by default.\n # For example, any file named `modeling_tf_xxx.py`\n # should have TensorFlow as a required backend.\n base_requirements = ()\n for string_check, requirements in BASE_FILE_REQUIREMENTS.items():\n if string_check(module_name):\n base_requirements = requirements\n break\n\n # Objects that have a `@export` assigned to them will get exported\n # with the backends specified in the decorator as well as the file backends.\n exported_objects = set()\n if \"@export\" in file_content:\n lines = file_content.split(\"\\n\")\n for index, line in enumerate(lines):\n # This allows exporting items with other decorators. We'll take a look\n # at the line that follows at the same indentation level.\n if line.startswith((\" \", \"\\t\", \"@\", \")\")) and not line.startswith(\"@export\"):\n continue\n\n # Skipping line enables putting whatever we want between the\n # export() call and the actual class/method definition.\n # This is what enables having # Copied from statements, docs, etc.\n skip_line = False\n\n if \"@export\" in previous_line:\n skip_line = False\n\n # Backends are defined on the same line as export\n if \"backends\" in previous_line:\n backends_string = previous_line.split(\"backends=\")[1].split(\"(\")[1].split(\")\")[0]\n backends = tuple(sorted([b.strip(\"'\\\",\") for b in backends_string.split(\", \") if b]))\n\n # Backends are defined in the lines following export, for example such as:\n # @export(\n # backends=(\n # \"sentencepiece\",\n # \"torch\",\n # \"tf\",\n # )\n # )\n #\n # or\n #\n # @export(\n # backends=(\n # \"sentencepiece\", \"tf\"\n # )\n # )\n elif \"backends\" in lines[previous_index + 1]:\n backends = []\n for backend_line in lines[previous_index:index]:\n if \"backends\" in backend_line:\n backend_line = backend_line.split(\"=\")[1]\n if '\"' in backend_line or \"'\" in backend_line:\n if \", \" in backend_line:\n backends.extend(backend.strip(\"()\\\"', \") for backend in backend_line.split(\", \"))\n else:\n backends.append(backend_line.strip(\"()\\\"', \"))\n\n # If the line is only a ')', then we reached the end of the backends and we break.\n if backend_line.strip() == \")\":\n break\n backends = tuple(backends)\n\n # No backends are registered for export\n else:\n backends = ()\n\n backends = frozenset(backends + base_requirements)\n if backends not in module_requirements:\n module_requirements[backends] = {}\n if module_name not in module_requirements[backends]:\n module_requirements[backends][module_name] = set()\n\n if not line.startswith(\"class\") and not line.startswith(\"def\"):\n skip_line = True\n else:\n start_index = 6 if line.startswith(\"class\") else 4\n object_name = line[start_index:].split(\"(\")[0].strip(\":\")\n module_requirements[backends][module_name].add(object_name)\n exported_objects.add(object_name)\n\n if not skip_line:\n previous_line = line\n previous_index = index\n\n # All objects that are in __all__ should be exported by default.\n # These objects are exported with the file backends.\n if \"__all__\" in file_content:\n for _all_object in fetch__all__(file_content):\n if _all_object not in exported_objects:\n backends = frozenset(base_requirements)\n if backends not in module_requirements:\n module_requirements[backends] = {}\n if module_name not in module_requirements[backends]:\n module_requirements[backends][module_name] = set()\n\n module_requirements[backends][module_name].add(_all_object)\n\n import_structure = {**module_requirements, **import_structure}\n return import_structure"}, {"class_start_lineno": 1, "class_end_lineno": 2158, "func_start_lineno": 2136, "func_end_lineno": 2158, "func_code": "def define_import_structure(module_path: str) -> IMPORT_STRUCTURE_T:\n \"\"\"\n This method takes a module_path as input and creates an import structure digestible by a _LazyModule.\n\n Here's an example of an output import structure at the src.transformers.models level:\n\n {\n frozenset({'tokenizers'}): {\n 'albert.tokenization_albert_fast': {'AlbertTokenizerFast'}\n },\n frozenset(): {\n 'albert.configuration_albert': {'AlbertConfig', 'AlbertOnnxConfig'},\n 'align.processing_align': {'AlignProcessor'},\n 'align.configuration_align': {'AlignConfig', 'AlignTextConfig', 'AlignVisionConfig'},\n 'altclip.configuration_altclip': {'AltCLIPConfig', 'AltCLIPTextConfig', 'AltCLIPVisionConfig'},\n 'altclip.processing_altclip': {'AltCLIPProcessor'}\n }\n }\n\n The import structure is a dict defined with frozensets as keys, and dicts of strings to sets of objects.\n \"\"\"\n import_structure = create_import_structure_from_path(module_path)\n return spread_import_structure(import_structure)"}], "type": ["function_empty"], "node": ["transformers.utils.import_utils.create_import_structure_from_path", "transformers.utils.import_utils.define_import_structure"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 10, "base_passed_num": 0}} {"id": ["transformers.src.transformers.modeling_rope_utils._compute_default_rope_parameters", "transformers.src.transformers.modeling_rope_utils._compute_linear_scaling_rope_parameters", "transformers.src.transformers.modeling_rope_utils._compute_llama3_parameters"], "project": "transformers", "origin_file": ["transformers/modeling_rope_utils.py", "transformers/modeling_rope_utils.py", "transformers/modeling_rope_utils.py"], "test_list": ["tests/utils/test_modeling_rope_utils.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 560, "func_start_lineno": 29, "func_end_lineno": 68, "func_code": "def _compute_default_rope_parameters(\n config: Optional[PretrainedConfig] = None,\n device: Optional[\"torch.device\"] = None,\n seq_len: Optional[int] = None,\n **rope_kwargs,\n) -> Tuple[\"torch.Tensor\", float]:\n \"\"\"\n Computes the inverse frequencies according to the original RoPE implementation\n Args:\n config ([`~transformers.PretrainedConfig`]):\n The model configuration.\n device (`torch.device`):\n The device to use for initialization of the inverse frequencies.\n seq_len (`int`, *optional*):\n The current sequence length. Unused for this type of RoPE.\n rope_kwargs (`Dict`, *optional*):\n BC compatibility with the previous RoPE class instantiation, will be removed in v4.45.\n Returns:\n Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the\n post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).\n \"\"\"\n if config is not None and len(rope_kwargs) > 0:\n raise ValueError(\n \"Unexpected arguments: `**rope_kwargs` and `config` are mutually exclusive in \"\n f\"`_compute_default_rope_parameters`, got `rope_kwargs`={rope_kwargs} and `config`={config}\"\n )\n if len(rope_kwargs) > 0:\n base = rope_kwargs[\"base\"]\n dim = rope_kwargs[\"dim\"]\n elif config is not None:\n base = config.rope_theta\n partial_rotary_factor = config.partial_rotary_factor if hasattr(config, \"partial_rotary_factor\") else 1.0\n head_dim = getattr(config, \"head_dim\", config.hidden_size // config.num_attention_heads)\n dim = int(head_dim * partial_rotary_factor)\n\n attention_factor = 1.0 # Unused in this type of RoPE\n\n # Compute the inverse frequencies\n inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.int64).float().to(device) / dim))\n return inv_freq, attention_factor"}, {"class_start_lineno": 1, "class_end_lineno": 560, "func_start_lineno": 71, "func_end_lineno": 109, "func_code": "def _compute_linear_scaling_rope_parameters(\n config: Optional[PretrainedConfig] = None,\n device: Optional[\"torch.device\"] = None,\n seq_len: Optional[int] = None,\n **rope_kwargs,\n) -> Tuple[\"torch.Tensor\", float]:\n \"\"\"\n Computes the inverse frequencies with linear scaling. Credits to the Reddit user /u/kaiokendev\n Args:\n config ([`~transformers.PretrainedConfig`]):\n The model configuration.\n device (`torch.device`):\n The device to use for initialization of the inverse frequencies.\n seq_len (`int`, *optional*):\n The current sequence length. Unused for this type of RoPE.\n rope_kwargs (`Dict`, *optional*):\n BC compatibility with the previous RoPE class instantiation, will be removed in v4.45.\n Returns:\n Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the\n post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).\n \"\"\"\n if config is not None and len(rope_kwargs) > 0:\n raise ValueError(\n \"Unexpected arguments: `**rope_kwargs` and `config` are mutually exclusive in \"\n f\"`_compute_linear_scaling_rope_parameters`, got `rope_kwargs`={rope_kwargs} and `config`={config}\"\n )\n if len(rope_kwargs) > 0:\n factor = rope_kwargs[\"factor\"]\n elif config is not None:\n factor = config.rope_scaling[\"factor\"]\n\n # Gets the default RoPE parameters\n inv_freq, attention_factor = _compute_default_rope_parameters(config, device, seq_len, **rope_kwargs)\n\n # Then applies linear scaling to the frequencies.\n # NOTE: originally, scaling was applied to the position_ids. However, we get `embs = inv_freq @ position_ids`, so\n # applying scaling to the inverse frequencies is equivalent.\n inv_freq /= factor\n return inv_freq, attention_factor"}, {"class_start_lineno": 1, "class_end_lineno": 560, "func_start_lineno": 307, "func_end_lineno": 347, "func_code": "def _compute_llama3_parameters(\n config: PretrainedConfig, device: \"torch.device\", seq_len: Optional[int] = None, **rope_kwargs\n) -> Tuple[\"torch.Tensor\", float]:\n \"\"\"\n Computes the inverse frequencies for llama 3.1.\n\n Args:\n config ([`~transformers.PretrainedConfig`]):\n The model configuration.\n device (`torch.device`):\n The device to use for initialization of the inverse frequencies.\n seq_len (`int`, *optional*):\n The current sequence length. Unused for this type of RoPE.\n rope_kwargs (`Dict`, *optional*):\n BC compatibility with the previous RoPE class instantiation, will be removed in v4.45.\n Returns:\n Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the\n post-processing scaling factor applied to the computed cos/sin.\n \"\"\"\n # Gets the default RoPE parameters\n inv_freq, attention_factor = _compute_default_rope_parameters(config, device, seq_len, **rope_kwargs)\n\n factor = config.rope_scaling[\"factor\"] # `8` in the original implementation\n low_freq_factor = config.rope_scaling[\"low_freq_factor\"] # `1` in the original implementation\n high_freq_factor = config.rope_scaling[\"high_freq_factor\"] # `4` in the original implementation\n old_context_len = config.rope_scaling[\"original_max_position_embeddings\"] # `8192` in the original implementation\n\n low_freq_wavelen = old_context_len / low_freq_factor\n high_freq_wavelen = old_context_len / high_freq_factor\n\n wavelen = 2 * math.pi / inv_freq\n # wavelen < high_freq_wavelen: do nothing\n # wavelen > low_freq_wavelen: divide by factor\n inv_freq_llama = torch.where(wavelen > low_freq_wavelen, inv_freq / factor, inv_freq)\n # otherwise: interpolate between the two, using a smooth factor\n smooth_factor = (old_context_len / wavelen - low_freq_factor) / (high_freq_factor - low_freq_factor)\n smoothed_inv_freq = (1 - smooth_factor) * inv_freq_llama / factor + smooth_factor * inv_freq_llama\n is_medium_freq = ~(wavelen < high_freq_wavelen) * ~(wavelen > low_freq_wavelen)\n inv_freq_llama = torch.where(is_medium_freq, smoothed_inv_freq, inv_freq_llama)\n\n return inv_freq_llama, attention_factor"}], "type": ["function_empty"], "node": ["transformers.modeling_rope_utils._compute_default_rope_parameters", "transformers.modeling_rope_utils._compute_linear_scaling_rope_parameters", "transformers.modeling_rope_utils._compute_llama3_parameters"], "language": "Python", "toolfunc_count": 3, "func_count": 3, "pytest_info": {"total_num": 10, "base_passed_num": 2}} {"id": ["UniRef.detectron2.structures.boxes.Boxes::__getitem__", "UniRef.detectron2.structures.instances.Instances::set", "UniRef.detectron2.structures.instances.Instances::__getitem__"], "project": "UniRef", "origin_file": ["detectron2/structures/boxes.py", "detectron2/structures/instances.py", "detectron2/structures/instances.py"], "test_list": ["tests/structures/test_instances.py"], "prob_info": [{"class_start_lineno": 130, "class_end_lineno": 307, "func_start_lineno": 213, "func_end_lineno": 235, "func_code": " def __getitem__(self, item) -> \"Boxes\":\n \"\"\"\n Args:\n item: int, slice, or a BoolTensor\n\n Returns:\n Boxes: Create a new :class:`Boxes` by indexing.\n\n The following usage are allowed:\n\n 1. `new_boxes = boxes[3]`: return a `Boxes` which contains only one box.\n 2. `new_boxes = boxes[2:10]`: return a slice of boxes.\n 3. `new_boxes = boxes[vector]`, where vector is a torch.BoolTensor\n with `length = len(boxes)`. Nonzero elements in the vector will be selected.\n\n Note that the returned Boxes might share storage with this Boxes,\n subject to Pytorch's indexing semantics.\n \"\"\"\n if isinstance(item, int):\n return Boxes(self.tensor[item].view(1, -1))\n b = self.tensor[item]\n assert b.dim() == 2, \"Indexing on Boxes with {} failed to return a matrix!\".format(item)\n return Boxes(b)"}, {"class_start_lineno": 7, "class_end_lineno": 192, "func_start_lineno": 68, "func_end_lineno": 79, "func_code": " def set(self, name: str, value: Any) -> None:\n \"\"\"\n Set the field named `name` to `value`.\n The length of `value` must be the number of instances,\n and must agree with other existing fields in this object.\n \"\"\"\n data_len = len(value)\n if len(self._fields):\n assert (\n len(self) == data_len\n ), \"Adding a field of length {} to a Instances of length {}\".format(data_len, len(self))\n self._fields[name] = value"}, {"class_start_lineno": 7, "class_end_lineno": 192, "func_start_lineno": 122, "func_end_lineno": 140, "func_code": " def __getitem__(self, item: Union[int, slice, torch.BoolTensor]) -> \"Instances\":\n \"\"\"\n Args:\n item: an index-like object and will be used to index all the fields.\n\n Returns:\n If `item` is a string, return the data in the corresponding field.\n Otherwise, returns an `Instances` where all fields are indexed by `item`.\n \"\"\"\n if type(item) == int:\n if item >= len(self) or item < -len(self):\n raise IndexError(\"Instances index out of range!\")\n else:\n item = slice(item, None, len(self))\n\n ret = Instances(self._image_size)\n for k, v in self._fields.items():\n ret.set(k, v[item])\n return ret"}], "type": ["function_empty"], "node": ["detectron2.structures.boxes.Boxes.__getitem__", "detectron2.structures.instances.Instances.set", "detectron2.structures.instances.Instances.__getitem__"], "language": "Python", "toolfunc_count": 3, "func_count": 3, "pytest_info": {"total_num": 10, "base_passed_num": 0}} {"id": ["UniRef.detectron2.modeling.roi_heads.fast_rcnn._log_classification_stats", "UniRef.detectron2.modeling.box_regression.Box2BoxTransform::get_deltas", "UniRef.detectron2.modeling.box_regression.Box2BoxTransformRotated::get_deltas", "UniRef.detectron2.modeling.box_regression._dense_box_regression_loss", "UniRef.detectron2.modeling.roi_heads.fast_rcnn.FastRCNNOutputLayers::losses"], "project": "UniRef", "origin_file": ["detectron2/modeling/roi_heads/fast_rcnn.py", "detectron2/modeling/box_regression.py", "detectron2/modeling/box_regression.py", "detectron2/modeling/box_regression.py", "detectron2/modeling/roi_heads/fast_rcnn.py"], "test_list": ["tests/modeling/test_fast_rcnn.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 462, "func_start_lineno": 87, "func_end_lineno": 114, "func_code": "def _log_classification_stats(pred_logits, gt_classes, prefix=\"fast_rcnn\"):\n \"\"\"\n Log the classification metrics to EventStorage.\n\n Args:\n pred_logits: Rx(K+1) logits. The last column is for background class.\n gt_classes: R labels\n \"\"\"\n num_instances = gt_classes.numel()\n if num_instances == 0:\n return\n pred_classes = pred_logits.argmax(dim=1)\n bg_class_ind = pred_logits.shape[1] - 1\n\n fg_inds = (gt_classes >= 0) & (gt_classes < bg_class_ind)\n num_fg = fg_inds.nonzero().numel()\n fg_gt_classes = gt_classes[fg_inds]\n fg_pred_classes = pred_classes[fg_inds]\n\n num_false_negative = (fg_pred_classes == bg_class_ind).nonzero().numel()\n num_accurate = (pred_classes == gt_classes).nonzero().numel()\n fg_num_accurate = (fg_pred_classes == fg_gt_classes).nonzero().numel()\n\n storage = get_event_storage()\n storage.put_scalar(f\"{prefix}/cls_accuracy\", num_accurate / num_instances)\n if num_fg > 0:\n storage.put_scalar(f\"{prefix}/fg_cls_accuracy\", fg_num_accurate / num_fg)\n storage.put_scalar(f\"{prefix}/false_negative\", num_false_negative / num_fg)"}, {"class_start_lineno": 21, "class_end_lineno": 116, "func_start_lineno": 43, "func_end_lineno": 76, "func_code": " def get_deltas(self, src_boxes, target_boxes):\n \"\"\"\n Get box regression transformation deltas (dx, dy, dw, dh) that can be used\n to transform the `src_boxes` into the `target_boxes`. That is, the relation\n ``target_boxes == self.apply_deltas(deltas, src_boxes)`` is true (unless\n any delta is too large and is clamped).\n\n Args:\n src_boxes (Tensor): source boxes, e.g., object proposals\n target_boxes (Tensor): target of the transformation, e.g., ground-truth\n boxes.\n \"\"\"\n assert isinstance(src_boxes, torch.Tensor), type(src_boxes)\n assert isinstance(target_boxes, torch.Tensor), type(target_boxes)\n\n src_widths = src_boxes[:, 2] - src_boxes[:, 0]\n src_heights = src_boxes[:, 3] - src_boxes[:, 1]\n src_ctr_x = src_boxes[:, 0] + 0.5 * src_widths\n src_ctr_y = src_boxes[:, 1] + 0.5 * src_heights\n\n target_widths = target_boxes[:, 2] - target_boxes[:, 0]\n target_heights = target_boxes[:, 3] - target_boxes[:, 1]\n target_ctr_x = target_boxes[:, 0] + 0.5 * target_widths\n target_ctr_y = target_boxes[:, 1] + 0.5 * target_heights\n\n wx, wy, ww, wh = self.weights\n dx = wx * (target_ctr_x - src_ctr_x) / src_widths\n dy = wy * (target_ctr_y - src_ctr_y) / src_heights\n dw = ww * torch.log(target_widths / src_widths)\n dh = wh * torch.log(target_heights / src_heights)\n\n deltas = torch.stack((dx, dy, dw, dh), dim=1)\n assert (src_widths > 0).all().item(), \"Input boxes to Box2BoxTransform are not valid!\"\n return deltas"}, {"class_start_lineno": 120, "class_end_lineno": 227, "func_start_lineno": 145, "func_end_lineno": 181, "func_code": " def get_deltas(self, src_boxes, target_boxes):\n \"\"\"\n Get box regression transformation deltas (dx, dy, dw, dh, da) that can be used\n to transform the `src_boxes` into the `target_boxes`. That is, the relation\n ``target_boxes == self.apply_deltas(deltas, src_boxes)`` is true (unless\n any delta is too large and is clamped).\n\n Args:\n src_boxes (Tensor): Nx5 source boxes, e.g., object proposals\n target_boxes (Tensor): Nx5 target of the transformation, e.g., ground-truth\n boxes.\n \"\"\"\n assert isinstance(src_boxes, torch.Tensor), type(src_boxes)\n assert isinstance(target_boxes, torch.Tensor), type(target_boxes)\n\n src_ctr_x, src_ctr_y, src_widths, src_heights, src_angles = torch.unbind(src_boxes, dim=1)\n\n target_ctr_x, target_ctr_y, target_widths, target_heights, target_angles = torch.unbind(\n target_boxes, dim=1\n )\n\n wx, wy, ww, wh, wa = self.weights\n dx = wx * (target_ctr_x - src_ctr_x) / src_widths\n dy = wy * (target_ctr_y - src_ctr_y) / src_heights\n dw = ww * torch.log(target_widths / src_widths)\n dh = wh * torch.log(target_heights / src_heights)\n # Angles of deltas are in radians while angles of boxes are in degrees.\n # the conversion to radians serve as a way to normalize the values\n da = target_angles - src_angles\n da = (da + 180.0) % 360.0 - 180.0 # make it in [-180, 180)\n da *= wa * math.pi / 180.0\n\n deltas = torch.stack((dx, dy, dw, dh, da), dim=1)\n assert (\n (src_widths > 0).all().item()\n ), \"Input boxes to Box2BoxTransformRotated are not valid!\"\n return deltas"}, {"class_start_lineno": 1, "class_end_lineno": 369, "func_start_lineno": 310, "func_end_lineno": 369, "func_code": "def _dense_box_regression_loss(\n anchors: List[Union[Boxes, torch.Tensor]],\n box2box_transform: Box2BoxTransform,\n pred_anchor_deltas: List[torch.Tensor],\n gt_boxes: List[torch.Tensor],\n fg_mask: torch.Tensor,\n box_reg_loss_type=\"smooth_l1\",\n smooth_l1_beta=0.0,\n):\n \"\"\"\n Compute loss for dense multi-level box regression.\n Loss is accumulated over ``fg_mask``.\n\n Args:\n anchors: #lvl anchor boxes, each is (HixWixA, 4)\n pred_anchor_deltas: #lvl predictions, each is (N, HixWixA, 4)\n gt_boxes: N ground truth boxes, each has shape (R, 4) (R = sum(Hi * Wi * A))\n fg_mask: the foreground boolean mask of shape (N, R) to compute loss on\n box_reg_loss_type (str): Loss type to use. Supported losses: \"smooth_l1\", \"giou\",\n \"diou\", \"ciou\".\n smooth_l1_beta (float): beta parameter for the smooth L1 regression loss. Default to\n use L1 loss. Only used when `box_reg_loss_type` is \"smooth_l1\"\n \"\"\"\n if isinstance(anchors[0], Boxes):\n anchors = type(anchors[0]).cat(anchors).tensor # (R, 4)\n else:\n anchors = cat(anchors)\n if box_reg_loss_type == \"smooth_l1\":\n gt_anchor_deltas = [box2box_transform.get_deltas(anchors, k) for k in gt_boxes]\n gt_anchor_deltas = torch.stack(gt_anchor_deltas) # (N, R, 4)\n loss_box_reg = smooth_l1_loss(\n cat(pred_anchor_deltas, dim=1)[fg_mask],\n gt_anchor_deltas[fg_mask],\n beta=smooth_l1_beta,\n reduction=\"sum\",\n )\n elif box_reg_loss_type == \"giou\":\n pred_boxes = [\n box2box_transform.apply_deltas(k, anchors) for k in cat(pred_anchor_deltas, dim=1)\n ]\n loss_box_reg = giou_loss(\n torch.stack(pred_boxes)[fg_mask], torch.stack(gt_boxes)[fg_mask], reduction=\"sum\"\n )\n elif box_reg_loss_type == \"diou\":\n pred_boxes = [\n box2box_transform.apply_deltas(k, anchors) for k in cat(pred_anchor_deltas, dim=1)\n ]\n loss_box_reg = diou_loss(\n torch.stack(pred_boxes)[fg_mask], torch.stack(gt_boxes)[fg_mask], reduction=\"sum\"\n )\n elif box_reg_loss_type == \"ciou\":\n pred_boxes = [\n box2box_transform.apply_deltas(k, anchors) for k in cat(pred_anchor_deltas, dim=1)\n ]\n loss_box_reg = ciou_loss(\n torch.stack(pred_boxes)[fg_mask], torch.stack(gt_boxes)[fg_mask], reduction=\"sum\"\n )\n else:\n raise ValueError(f\"Invalid dense box regression loss type '{box_reg_loss_type}'\")\n return loss_box_reg"}, {"class_start_lineno": 173, "class_end_lineno": 462, "func_start_lineno": 278, "func_end_lineno": 318, "func_code": " def losses(self, predictions, proposals):\n \"\"\"\n Args:\n predictions: return values of :meth:`forward()`.\n proposals (list[Instances]): proposals that match the features that were used\n to compute predictions. The fields ``proposal_boxes``, ``gt_boxes``,\n ``gt_classes`` are expected.\n\n Returns:\n Dict[str, Tensor]: dict of losses\n \"\"\"\n scores, proposal_deltas = predictions\n\n # parse classification outputs\n gt_classes = (\n cat([p.gt_classes for p in proposals], dim=0) if len(proposals) else torch.empty(0)\n )\n _log_classification_stats(scores, gt_classes)\n\n # parse box regression outputs\n if len(proposals):\n proposal_boxes = cat([p.proposal_boxes.tensor for p in proposals], dim=0) # Nx4\n assert not proposal_boxes.requires_grad, \"Proposals should not require gradients!\"\n # If \"gt_boxes\" does not exist, the proposals must be all negative and\n # should not be included in regression loss computation.\n # Here we just use proposal_boxes as an arbitrary placeholder because its\n # value won't be used in self.box_reg_loss().\n gt_boxes = cat(\n [(p.gt_boxes if p.has(\"gt_boxes\") else p.proposal_boxes).tensor for p in proposals],\n dim=0,\n )\n else:\n proposal_boxes = gt_boxes = torch.empty((0, 4), device=proposal_deltas.device)\n\n losses = {\n \"loss_cls\": cross_entropy(scores, gt_classes, reduction=\"mean\"),\n \"loss_box_reg\": self.box_reg_loss(\n proposal_boxes, gt_boxes, proposal_deltas, gt_classes\n ),\n }\n return {k: v * self.loss_weight.get(k, 1.0) for k, v in losses.items()}"}], "type": ["function_empty"], "node": ["detectron2.modeling.roi_heads.fast_rcnn._log_classification_stats", "detectron2.modeling.box_regression.Box2BoxTransform.get_deltas", "detectron2.modeling.box_regression.Box2BoxTransformRotated.get_deltas", "detectron2.modeling.box_regression._dense_box_regression_loss", "detectron2.modeling.roi_heads.fast_rcnn.FastRCNNOutputLayers.losses"], "language": "Python", "toolfunc_count": 5, "func_count": 5, "pytest_info": {"total_num": 5, "base_passed_num": 2}} {"id": ["UniRef.detectron2.data.detection_utils.check_metadata_consistency", "UniRef.detectron2.data.detection_utils.create_keypoint_hflip_indices", "UniRef.detectron2.structures.instances.Instances::set", "UniRef.detectron2.data.detection_utils.annotations_to_instances"], "project": "UniRef", "origin_file": ["detectron2/data/detection_utils.py", "detectron2/data/detection_utils.py", "detectron2/structures/instances.py", "detectron2/structures/instances.py", "detectron2/data/detection_utils.py"], "test_list": ["tests/data/test_detection_utils.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 623, "func_start_lineno": 564, "func_end_lineno": 590, "func_code": "def check_metadata_consistency(key, dataset_names):\n \"\"\"\n Check that the datasets have consistent metadata.\n\n Args:\n key (str): a metadata key\n dataset_names (list[str]): a list of dataset names\n\n Raises:\n AttributeError: if the key does not exist in the metadata\n ValueError: if the given datasets do not have the same metadata values defined by key\n \"\"\"\n if len(dataset_names) == 0:\n return\n logger = logging.getLogger(__name__)\n entries_per_dataset = [getattr(MetadataCatalog.get(d), key) for d in dataset_names]\n for idx, entry in enumerate(entries_per_dataset):\n if entry != entries_per_dataset[0]:\n logger.error(\n \"Metadata '{}' for dataset '{}' is '{}'\".format(key, dataset_names[idx], str(entry))\n )\n logger.error(\n \"Metadata '{}' for dataset '{}' is '{}'\".format(\n key, dataset_names[0], str(entries_per_dataset[0])\n )\n )\n raise ValueError(\"Datasets have different metadata '{}'!\".format(key))"}, {"class_start_lineno": 1, "class_end_lineno": 623, "func_start_lineno": 509, "func_end_lineno": 531, "func_code": "def create_keypoint_hflip_indices(dataset_names: Union[str, List[str]]) -> List[int]:\n \"\"\"\n Args:\n dataset_names: list of dataset names\n\n Returns:\n list[int]: a list of size=#keypoints, storing the\n horizontally-flipped keypoint indices.\n \"\"\"\n if isinstance(dataset_names, str):\n dataset_names = [dataset_names]\n\n check_metadata_consistency(\"keypoint_names\", dataset_names)\n check_metadata_consistency(\"keypoint_flip_map\", dataset_names)\n\n meta = MetadataCatalog.get(dataset_names[0])\n names = meta.keypoint_names\n # TODO flip -> hflip\n flip_map = dict(meta.keypoint_flip_map)\n flip_map.update({v: k for k, v in flip_map.items()})\n flipped_names = [i if i not in flip_map else flip_map[i] for i in names]\n flip_indices = [names.index(i) for i in flipped_names]\n return flip_indices"}, {"class_start_lineno": 7, "class_end_lineno": 192, "func_start_lineno": 68, "func_end_lineno": 79, "func_code": " def set(self, name: str, value: Any) -> None:\n \"\"\"\n Set the field named `name` to `value`.\n The length of `value` must be the number of instances,\n and must agree with other existing fields in this object.\n \"\"\"\n data_len = len(value)\n if len(self._fields):\n assert (\n len(self) == data_len\n ), \"Adding a field of length {} to a Instances of length {}\".format(data_len, len(self))\n self._fields[name] = value"}, {"class_start_lineno": 7, "class_end_lineno": 192, "func_start_lineno": 57, "func_end_lineno": 61, "func_code": " def __setattr__(self, name: str, val: Any) -> None:\n if name.startswith(\"_\"):\n super().__setattr__(name, val)\n else:\n self.set(name, val)"}, {"class_start_lineno": 1, "class_end_lineno": 623, "func_start_lineno": 369, "func_end_lineno": 441, "func_code": "def annotations_to_instances(annos, image_size, mask_format=\"polygon\"):\n \"\"\"\n Create an :class:`Instances` object used by the models,\n from instance annotations in the dataset dict.\n\n Args:\n annos (list[dict]): a list of instance annotations in one image, each\n element for one instance.\n image_size (tuple): height, width\n\n Returns:\n Instances:\n It will contain fields \"gt_boxes\", \"gt_classes\",\n \"gt_masks\", \"gt_keypoints\", if they can be obtained from `annos`.\n This is the format that builtin models expect.\n \"\"\"\n boxes = (\n np.stack(\n [BoxMode.convert(obj[\"bbox\"], obj[\"bbox_mode\"], BoxMode.XYXY_ABS) for obj in annos]\n )\n if len(annos)\n else np.zeros((0, 4))\n )\n target = Instances(image_size)\n target.gt_boxes = Boxes(boxes)\n\n classes = [int(obj[\"category_id\"]) for obj in annos]\n classes = torch.tensor(classes, dtype=torch.int64)\n target.gt_classes = classes\n\n if len(annos) and \"segmentation\" in annos[0]:\n segms = [obj[\"segmentation\"] for obj in annos]\n if mask_format == \"polygon\":\n try:\n masks = PolygonMasks(segms)\n except ValueError as e:\n raise ValueError(\n \"Failed to use mask_format=='polygon' from the given annotations!\"\n ) from e\n else:\n assert mask_format == \"bitmask\", mask_format\n masks = []\n for segm in segms:\n if isinstance(segm, list):\n # polygon\n masks.append(polygons_to_bitmask(segm, *image_size))\n elif isinstance(segm, dict):\n # COCO RLE\n masks.append(mask_util.decode(segm))\n elif isinstance(segm, np.ndarray):\n assert segm.ndim == 2, \"Expect segmentation of 2 dimensions, got {}.\".format(\n segm.ndim\n )\n # mask array\n masks.append(segm)\n else:\n raise ValueError(\n \"Cannot convert segmentation of type '{}' to BitMasks!\"\n \"Supported types are: polygons as list[list[float] or ndarray],\"\n \" COCO-style RLE as a dict, or a binary segmentation mask \"\n \" in a 2D numpy array of shape HxW.\".format(type(segm))\n )\n # torch.from_numpy does not support array with negative stride.\n masks = BitMasks(\n torch.stack([torch.from_numpy(np.ascontiguousarray(x)) for x in masks])\n )\n target.gt_masks = masks\n\n if len(annos) and \"keypoints\" in annos[0]:\n kpts = [obj.get(\"keypoints\", []) for obj in annos]\n target.gt_keypoints = Keypoints(kpts)\n\n return target"}], "type": ["function_empty"], "node": ["detectron2.data.detection_utils.check_metadata_consistency", "detectron2.data.detection_utils.create_keypoint_hflip_indices", "detectron2.structures.instances.Instances.set", "detectron2.structures.instances.Instances.__setattr__", "detectron2.data.detection_utils.annotations_to_instances"], "language": "Python", "toolfunc_count": 4, "func_count": 4, "pytest_info": {"total_num": 10, "base_passed_num": 7}} {"id": ["UniRef.detectron2.structures.instances.Instances::set", "UniRef.detectron2.tracking.hungarian_tracker.BaseHungarianTracker::_initialize_extra_fields"], "project": "UniRef", "origin_file": ["detectron2/structures/instances.py", "detectron2/structures/instances.py", "detectron2/tracking/hungarian_tracker.py"], "test_list": ["tests/tracking/test_hungarian_tracker.py"], "prob_info": [{"class_start_lineno": 7, "class_end_lineno": 192, "func_start_lineno": 68, "func_end_lineno": 79, "func_code": " def set(self, name: str, value: Any) -> None:\n \"\"\"\n Set the field named `name` to `value`.\n The length of `value` must be the number of instances,\n and must agree with other existing fields in this object.\n \"\"\"\n data_len = len(value)\n if len(self._fields):\n assert (\n len(self) == data_len\n ), \"Adding a field of length {} to a Instances of length {}\".format(data_len, len(self))\n self._fields[name] = value"}, {"class_start_lineno": 7, "class_end_lineno": 192, "func_start_lineno": 57, "func_end_lineno": 61, "func_code": " def __setattr__(self, name: str, val: Any) -> None:\n if name.startswith(\"_\"):\n super().__setattr__(name, val)\n else:\n self.set(name, val)"}, {"class_start_lineno": 16, "class_end_lineno": 176, "func_start_lineno": 74, "func_end_lineno": 95, "func_code": " def _initialize_extra_fields(self, instances: Instances) -> Instances:\n \"\"\"\n If input instances don't have ID, ID_period, lost_frame_count fields,\n this method is used to initialize these fields.\n\n Args:\n instances: D2 Instances, for predictions of the current frame\n Return:\n D2 Instances with extra fields added\n \"\"\"\n if not instances.has(\"ID\"):\n instances.set(\"ID\", [None] * len(instances))\n if not instances.has(\"ID_period\"):\n instances.set(\"ID_period\", [None] * len(instances))\n if not instances.has(\"lost_frame_count\"):\n instances.set(\"lost_frame_count\", [None] * len(instances))\n if self._prev_instances is None:\n instances.ID = list(range(len(instances)))\n self._id_count += len(instances)\n instances.ID_period = [1] * len(instances)\n instances.lost_frame_count = [0] * len(instances)\n return instances"}], "type": ["function_empty"], "node": ["detectron2.structures.instances.Instances.set", "detectron2.structures.instances.Instances.__setattr__", "detectron2.tracking.hungarian_tracker.BaseHungarianTracker._initialize_extra_fields"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 2, "base_passed_num": 1}} {"id": ["UniRef.detectron2.data.catalog._DatasetCatalog::get", "UniRef.detectron2.data.datasets.coco.convert_to_coco_dict"], "project": "UniRef", "origin_file": ["detectron2/data/catalog.py", "detectron2/data/datasets/coco.py"], "test_list": ["tests/data/test_coco.py"], "prob_info": [{"class_start_lineno": 13, "class_end_lineno": 78, "func_start_lineno": 40, "func_end_lineno": 58, "func_code": " def get(self, name):\n \"\"\"\n Call the registered function and return its results.\n\n Args:\n name (str): the name that identifies a dataset, e.g. \"coco_2014_train\".\n\n Returns:\n list[dict]: dataset annotations.\n \"\"\"\n try:\n f = self[name]\n except KeyError as e:\n raise KeyError(\n \"Dataset '{}' is not registered! Available datasets are: {}\".format(\n name, \", \".join(list(self.keys()))\n )\n ) from e\n return f()"}, {"class_start_lineno": 1, "class_end_lineno": 541, "func_start_lineno": 308, "func_end_lineno": 444, "func_code": "def convert_to_coco_dict(dataset_name):\n \"\"\"\n Convert an instance detection/segmentation or keypoint detection dataset\n in detectron2's standard format into COCO json format.\n\n Generic dataset description can be found here:\n https://detectron2.readthedocs.io/tutorials/datasets.html#register-a-dataset\n\n COCO data format description can be found here:\n http://cocodataset.org/#format-data\n\n Args:\n dataset_name (str):\n name of the source dataset\n Must be registered in DatastCatalog and in detectron2's standard format.\n Must have corresponding metadata \"thing_classes\"\n Returns:\n coco_dict: serializable dict in COCO json format\n \"\"\"\n\n dataset_dicts = DatasetCatalog.get(dataset_name)\n metadata = MetadataCatalog.get(dataset_name)\n\n # unmap the category mapping ids for COCO\n if hasattr(metadata, \"thing_dataset_id_to_contiguous_id\"):\n reverse_id_mapping = {v: k for k, v in metadata.thing_dataset_id_to_contiguous_id.items()}\n reverse_id_mapper = lambda contiguous_id: reverse_id_mapping[contiguous_id] # noqa\n else:\n reverse_id_mapper = lambda contiguous_id: contiguous_id # noqa\n\n categories = [\n {\"id\": reverse_id_mapper(id), \"name\": name}\n for id, name in enumerate(metadata.thing_classes)\n ]\n\n logger.info(\"Converting dataset dicts into COCO format\")\n coco_images = []\n coco_annotations = []\n\n for image_id, image_dict in enumerate(dataset_dicts):\n coco_image = {\n \"id\": image_dict.get(\"image_id\", image_id),\n \"width\": int(image_dict[\"width\"]),\n \"height\": int(image_dict[\"height\"]),\n \"file_name\": str(image_dict[\"file_name\"]),\n }\n coco_images.append(coco_image)\n\n anns_per_image = image_dict.get(\"annotations\", [])\n for annotation in anns_per_image:\n # create a new dict with only COCO fields\n coco_annotation = {}\n\n # COCO requirement: XYWH box format for axis-align and XYWHA for rotated\n bbox = annotation[\"bbox\"]\n if isinstance(bbox, np.ndarray):\n if bbox.ndim != 1:\n raise ValueError(f\"bbox has to be 1-dimensional. Got shape={bbox.shape}.\")\n bbox = bbox.tolist()\n if len(bbox) not in [4, 5]:\n raise ValueError(f\"bbox has to has length 4 or 5. Got {bbox}.\")\n from_bbox_mode = annotation[\"bbox_mode\"]\n to_bbox_mode = BoxMode.XYWH_ABS if len(bbox) == 4 else BoxMode.XYWHA_ABS\n bbox = BoxMode.convert(bbox, from_bbox_mode, to_bbox_mode)\n\n # COCO requirement: instance area\n if \"segmentation\" in annotation:\n # Computing areas for instances by counting the pixels\n segmentation = annotation[\"segmentation\"]\n # TODO: check segmentation type: RLE, BinaryMask or Polygon\n if isinstance(segmentation, list):\n polygons = PolygonMasks([segmentation])\n area = polygons.area()[0].item()\n elif isinstance(segmentation, dict): # RLE\n area = mask_util.area(segmentation).item()\n else:\n raise TypeError(f\"Unknown segmentation type {type(segmentation)}!\")\n else:\n # Computing areas using bounding boxes\n if to_bbox_mode == BoxMode.XYWH_ABS:\n bbox_xy = BoxMode.convert(bbox, to_bbox_mode, BoxMode.XYXY_ABS)\n area = Boxes([bbox_xy]).area()[0].item()\n else:\n area = RotatedBoxes([bbox]).area()[0].item()\n\n if \"keypoints\" in annotation:\n keypoints = annotation[\"keypoints\"] # list[int]\n for idx, v in enumerate(keypoints):\n if idx % 3 != 2:\n # COCO's segmentation coordinates are floating points in [0, H or W],\n # but keypoint coordinates are integers in [0, H-1 or W-1]\n # For COCO format consistency we substract 0.5\n # https://github.com/facebookresearch/detectron2/pull/175#issuecomment-551202163\n keypoints[idx] = v - 0.5\n if \"num_keypoints\" in annotation:\n num_keypoints = annotation[\"num_keypoints\"]\n else:\n num_keypoints = sum(kp > 0 for kp in keypoints[2::3])\n\n # COCO requirement:\n # linking annotations to images\n # \"id\" field must start with 1\n coco_annotation[\"id\"] = len(coco_annotations) + 1\n coco_annotation[\"image_id\"] = coco_image[\"id\"]\n coco_annotation[\"bbox\"] = [round(float(x), 3) for x in bbox]\n coco_annotation[\"area\"] = float(area)\n coco_annotation[\"iscrowd\"] = int(annotation.get(\"iscrowd\", 0))\n coco_annotation[\"category_id\"] = int(reverse_id_mapper(annotation[\"category_id\"]))\n\n # Add optional fields\n if \"keypoints\" in annotation:\n coco_annotation[\"keypoints\"] = keypoints\n coco_annotation[\"num_keypoints\"] = num_keypoints\n\n if \"segmentation\" in annotation:\n seg = coco_annotation[\"segmentation\"] = annotation[\"segmentation\"]\n if isinstance(seg, dict): # RLE\n counts = seg[\"counts\"]\n if not isinstance(counts, str):\n # make it json-serializable\n seg[\"counts\"] = counts.decode(\"ascii\")\n\n coco_annotations.append(coco_annotation)\n\n logger.info(\n \"Conversion finished, \"\n f\"#images: {len(coco_images)}, #annotations: {len(coco_annotations)}\"\n )\n\n info = {\n \"date_created\": str(datetime.datetime.now()),\n \"description\": \"Automatically generated COCO json file for Detectron2.\",\n }\n coco_dict = {\"info\": info, \"images\": coco_images, \"categories\": categories, \"licenses\": None}\n if len(coco_annotations) > 0:\n coco_dict[\"annotations\"] = coco_annotations\n return coco_dict"}], "type": ["function_empty", "Development"], "node": ["detectron2.data.catalog._DatasetCatalog.get", "detectron2.data.datasets.coco.convert_to_coco_dict"], "language": "Python", "toolfunc_count": 1, "func_count": 2, "pytest_info": {"total_num": 3, "base_passed_num": 1}} {"id": ["UniRef.detectron2.utils.registry.locate", "UniRef.detectron2.utils.registry._convert_target_to_string"], "project": "UniRef", "origin_file": ["detectron2/utils/registry.py", "detectron2/utils/registry.py"], "test_list": ["tests/test_registry.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 60, "func_start_lineno": 40, "func_end_lineno": 60, "func_code": "def locate(name: str) -> Any:\n \"\"\"\n Locate and return an object ``x`` using an input string ``{x.__module__}.{x.__qualname__}``,\n such as \"module.submodule.class_name\".\n\n Raise Exception if it cannot be found.\n \"\"\"\n obj = pydoc.locate(name)\n\n # Some cases (e.g. torch.optim.sgd.SGD) not handled correctly\n # by pydoc.locate. Try a private function from hydra.\n if obj is None:\n try:\n # from hydra.utils import get_method - will print many errors\n from hydra.utils import _locate\n except ImportError as e:\n raise ImportError(f\"Cannot dynamically locate object {name}!\") from e\n else:\n obj = _locate(name) # it raises if fails\n\n return obj"}, {"class_start_lineno": 1, "class_end_lineno": 60, "func_start_lineno": 15, "func_end_lineno": 37, "func_code": "def _convert_target_to_string(t: Any) -> str:\n \"\"\"\n Inverse of ``locate()``.\n\n Args:\n t: any object with ``__module__`` and ``__qualname__``\n \"\"\"\n module, qualname = t.__module__, t.__qualname__\n\n # Compress the path to this object, e.g. ``module.submodule._impl.class``\n # may become ``module.submodule.class``, if the later also resolves to the same\n # object. This simplifies the string, and also is less affected by moving the\n # class implementation.\n module_parts = module.split(\".\")\n for k in range(1, len(module_parts)):\n prefix = \".\".join(module_parts[:k])\n candidate = f\"{prefix}.{qualname}\"\n try:\n if locate(candidate) is t:\n return candidate\n except ImportError:\n pass\n return f\"{module}.{qualname}\""}], "type": ["Development"], "node": ["detectron2.utils.registry.locate", "detectron2.utils.registry._convert_target_to_string"], "language": "Python", "toolfunc_count": 0, "func_count": 2, "pytest_info": {"total_num": 6, "base_passed_num": 0}} {"id": ["UniRef.detectron2.utils.visualizer._create_text_labels", "UniRef.detectron2.utils.visualizer.Visualizer::draw_instance_predictions", "UniRef.detectron2.utils.visualizer.Visualizer::_convert_masks", "UniRef.detectron2.utils.colormap.random_color", "UniRef.detectron2.utils.visualizer.Visualizer::overlay_instances"], "project": "UniRef", "origin_file": ["detectron2/utils/visualizer.py", "detectron2/utils/visualizer.py", "detectron2/utils/visualizer.py", "detectron2/utils/colormap.py", "detectron2/utils/visualizer.py"], "test_list": ["tests/test_visualizer.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 1274, "func_start_lineno": 237, "func_end_lineno": 261, "func_code": "def _create_text_labels(classes, scores, class_names, is_crowd=None):\n \"\"\"\n Args:\n classes (list[int] or None):\n scores (list[float] or None):\n class_names (list[str] or None):\n is_crowd (list[bool] or None):\n\n Returns:\n list[str] or None\n \"\"\"\n labels = None\n if classes is not None:\n if class_names is not None and len(class_names) > 0:\n labels = [class_names[i] for i in classes]\n else:\n labels = [str(i) for i in classes]\n if scores is not None:\n if labels is None:\n labels = [\"{:.0f}%\".format(s * 100) for s in scores]\n else:\n labels = [\"{} {:.0f}%\".format(l, s * 100) for l, s in zip(labels, scores)]\n if labels is not None and is_crowd is not None:\n labels = [l + (\"|crowd\" if crowd else \"\") for l, crowd in zip(labels, is_crowd)]\n return labels"}, {"class_start_lineno": 338, "class_end_lineno": 1274, "func_start_lineno": 390, "func_end_lineno": 441, "func_code": " def draw_instance_predictions(self, predictions):\n \"\"\"\n Draw instance-level prediction results on an image.\n\n Args:\n predictions (Instances): the output of an instance detection/segmentation\n model. Following fields will be used to draw:\n \"pred_boxes\", \"pred_classes\", \"scores\", \"pred_masks\" (or \"pred_masks_rle\").\n\n Returns:\n output (VisImage): image object with visualizations.\n \"\"\"\n boxes = predictions.pred_boxes if predictions.has(\"pred_boxes\") else None\n scores = predictions.scores if predictions.has(\"scores\") else None\n classes = predictions.pred_classes.tolist() if predictions.has(\"pred_classes\") else None\n labels = _create_text_labels(classes, scores, self.metadata.get(\"thing_classes\", None))\n keypoints = predictions.pred_keypoints if predictions.has(\"pred_keypoints\") else None\n\n if predictions.has(\"pred_masks\"):\n masks = np.asarray(predictions.pred_masks)\n masks = [GenericMask(x, self.output.height, self.output.width) for x in masks]\n else:\n masks = None\n\n if self._instance_mode == ColorMode.SEGMENTATION and self.metadata.get(\"thing_colors\"):\n colors = [\n self._jitter([x / 255 for x in self.metadata.thing_colors[c]]) for c in classes\n ]\n alpha = 0.8\n else:\n colors = None\n alpha = 0.5\n\n if self._instance_mode == ColorMode.IMAGE_BW:\n self.output.reset_image(\n self._create_grayscale_image(\n (predictions.pred_masks.any(dim=0) > 0).numpy()\n if predictions.has(\"pred_masks\")\n else None\n )\n )\n alpha = 0.3\n\n self.overlay_instances(\n masks=masks,\n boxes=boxes,\n labels=labels,\n keypoints=keypoints,\n assigned_colors=colors,\n alpha=alpha,\n )\n return self.output"}, {"class_start_lineno": 338, "class_end_lineno": 1274, "func_start_lineno": 1221, "func_end_lineno": 1242, "func_code": " def _convert_masks(self, masks_or_polygons):\n \"\"\"\n Convert different format of masks or polygons to a tuple of masks and polygons.\n\n Returns:\n list[GenericMask]:\n \"\"\"\n\n m = masks_or_polygons\n if isinstance(m, PolygonMasks):\n m = m.polygons\n if isinstance(m, BitMasks):\n m = m.tensor.numpy()\n if isinstance(m, torch.Tensor):\n m = m.numpy()\n ret = []\n for x in m:\n if isinstance(x, GenericMask):\n ret.append(x)\n else:\n ret.append(GenericMask(x, self.output.height, self.output.width))\n return ret"}, {"class_start_lineno": 1, "class_end_lineno": 158, "func_start_lineno": 112, "func_end_lineno": 125, "func_code": "def random_color(rgb=False, maximum=255):\n \"\"\"\n Args:\n rgb (bool): whether to return RGB colors or BGR colors.\n maximum (int): either 255 or 1\n\n Returns:\n ndarray: a vector of 3 numbers\n \"\"\"\n idx = np.random.randint(0, len(_COLORS))\n ret = _COLORS[idx] * maximum\n if not rgb:\n ret = ret[::-1]\n return ret"}, {"class_start_lineno": 338, "class_end_lineno": 1274, "func_start_lineno": 614, "func_end_lineno": 754, "func_code": " def overlay_instances(\n self,\n *,\n boxes=None,\n labels=None,\n masks=None,\n keypoints=None,\n assigned_colors=None,\n alpha=0.5,\n ):\n \"\"\"\n Args:\n boxes (Boxes, RotatedBoxes or ndarray): either a :class:`Boxes`,\n or an Nx4 numpy array of XYXY_ABS format for the N objects in a single image,\n or a :class:`RotatedBoxes`,\n or an Nx5 numpy array of (x_center, y_center, width, height, angle_degrees) format\n for the N objects in a single image,\n labels (list[str]): the text to be displayed for each instance.\n masks (masks-like object): Supported types are:\n\n * :class:`detectron2.structures.PolygonMasks`,\n :class:`detectron2.structures.BitMasks`.\n * list[list[ndarray]]: contains the segmentation masks for all objects in one image.\n The first level of the list corresponds to individual instances. The second\n level to all the polygon that compose the instance, and the third level\n to the polygon coordinates. The third level should have the format of\n [x0, y0, x1, y1, ..., xn, yn] (n >= 3).\n * list[ndarray]: each ndarray is a binary mask of shape (H, W).\n * list[dict]: each dict is a COCO-style RLE.\n keypoints (Keypoint or array like): an array-like object of shape (N, K, 3),\n where the N is the number of instances and K is the number of keypoints.\n The last dimension corresponds to (x, y, visibility or score).\n assigned_colors (list[matplotlib.colors]): a list of colors, where each color\n corresponds to each mask or box in the image. Refer to 'matplotlib.colors'\n for full list of formats that the colors are accepted in.\n Returns:\n output (VisImage): image object with visualizations.\n \"\"\"\n num_instances = 0\n if boxes is not None:\n boxes = self._convert_boxes(boxes)\n num_instances = len(boxes)\n if masks is not None:\n masks = self._convert_masks(masks)\n if num_instances:\n assert len(masks) == num_instances\n else:\n num_instances = len(masks)\n if keypoints is not None:\n if num_instances:\n assert len(keypoints) == num_instances\n else:\n num_instances = len(keypoints)\n keypoints = self._convert_keypoints(keypoints)\n if labels is not None:\n assert len(labels) == num_instances\n if assigned_colors is None:\n assigned_colors = [random_color(rgb=True, maximum=1) for _ in range(num_instances)]\n if num_instances == 0:\n return self.output\n if boxes is not None and boxes.shape[1] == 5:\n return self.overlay_rotated_instances(\n boxes=boxes, labels=labels, assigned_colors=assigned_colors\n )\n\n # Display in largest to smallest order to reduce occlusion.\n areas = None\n if boxes is not None:\n areas = np.prod(boxes[:, 2:] - boxes[:, :2], axis=1)\n elif masks is not None:\n areas = np.asarray([x.area() for x in masks])\n\n if areas is not None:\n sorted_idxs = np.argsort(-areas).tolist()\n # Re-order overlapped instances in descending order.\n boxes = boxes[sorted_idxs] if boxes is not None else None\n labels = [labels[k] for k in sorted_idxs] if labels is not None else None\n masks = [masks[idx] for idx in sorted_idxs] if masks is not None else None\n assigned_colors = [assigned_colors[idx] for idx in sorted_idxs]\n keypoints = keypoints[sorted_idxs] if keypoints is not None else None\n\n for i in range(num_instances):\n color = assigned_colors[i]\n if boxes is not None:\n self.draw_box(boxes[i], edge_color=color)\n\n if masks is not None:\n for segment in masks[i].polygons:\n self.draw_polygon(segment.reshape(-1, 2), color, alpha=alpha)\n\n if labels is not None:\n # first get a box\n if boxes is not None:\n x0, y0, x1, y1 = boxes[i]\n text_pos = (x0, y0) # if drawing boxes, put text on the box corner.\n horiz_align = \"left\"\n elif masks is not None:\n # skip small mask without polygon\n if len(masks[i].polygons) == 0:\n continue\n\n x0, y0, x1, y1 = masks[i].bbox()\n\n # draw text in the center (defined by median) when box is not drawn\n # median is less sensitive to outliers.\n text_pos = np.median(masks[i].mask.nonzero(), axis=1)[::-1]\n horiz_align = \"center\"\n else:\n continue # drawing the box confidence for keypoints isn't very useful.\n # for small objects, draw text at the side to avoid occlusion\n instance_area = (y1 - y0) * (x1 - x0)\n if (\n instance_area < _SMALL_OBJECT_AREA_THRESH * self.output.scale\n or y1 - y0 < 40 * self.output.scale\n ):\n if y1 >= self.output.height - 5:\n text_pos = (x1, y0)\n else:\n text_pos = (x0, y1)\n\n height_ratio = (y1 - y0) / np.sqrt(self.output.height * self.output.width)\n lighter_color = self._change_color_brightness(color, brightness_factor=0.7)\n font_size = (\n np.clip((height_ratio - 0.02) / 0.08 + 1, 1.2, 2)\n * 0.5\n * self._default_font_size\n )\n self.draw_text(\n labels[i],\n text_pos,\n color=lighter_color,\n horizontal_alignment=horiz_align,\n font_size=font_size,\n )\n\n # draw keypoints\n if keypoints is not None:\n for keypoints_per_instance in keypoints:\n self.draw_and_connect_keypoints(keypoints_per_instance)\n\n return self.output"}], "type": ["function_empty", "Development"], "node": ["detectron2.utils.visualizer._create_text_labels", "detectron2.utils.visualizer.Visualizer.draw_instance_predictions", "detectron2.utils.visualizer.Visualizer._convert_masks", "detectron2.utils.colormap.random_color", "detectron2.utils.visualizer.Visualizer.overlay_instances"], "language": "Python", "toolfunc_count": 4, "func_count": 5, "pytest_info": {"total_num": 14, "base_passed_num": 10}} {"id": ["UniRef.detectron2.structures.instances.Instances::set", "UniRef.detectron2.tracking.bbox_iou_tracker.BBoxIOUTracker::_initialize_extra_fields", "UniRef.detectron2.structures.boxes.pairwise_intersection", "UniRef.detectron2.structures.boxes.pairwise_iou", "UniRef.detectron2.tracking.bbox_iou_tracker.BBoxIOUTracker::update"], "project": "UniRef", "origin_file": ["detectron2/structures/instances.py", "detectron2/structures/instances.py", "detectron2/tracking/bbox_iou_tracker.py", "detectron2/structures/boxes.py", "detectron2/structures/boxes.py", "detectron2/tracking/bbox_iou_tracker.py"], "test_list": ["tests/tracking/test_bbox_iou_tracker.py"], "prob_info": [{"class_start_lineno": 7, "class_end_lineno": 192, "func_start_lineno": 68, "func_end_lineno": 79, "func_code": " def set(self, name: str, value: Any) -> None:\n \"\"\"\n Set the field named `name` to `value`.\n The length of `value` must be the number of instances,\n and must agree with other existing fields in this object.\n \"\"\"\n data_len = len(value)\n if len(self._fields):\n assert (\n len(self) == data_len\n ), \"Adding a field of length {} to a Instances of length {}\".format(data_len, len(self))\n self._fields[name] = value"}, {"class_start_lineno": 7, "class_end_lineno": 192, "func_start_lineno": 57, "func_end_lineno": 61, "func_code": " def __setattr__(self, name: str, val: Any) -> None:\n if name.startswith(\"_\"):\n super().__setattr__(name, val)\n else:\n self.set(name, val)"}, {"class_start_lineno": 17, "class_end_lineno": 260, "func_start_lineno": 152, "func_end_lineno": 173, "func_code": " def _initialize_extra_fields(self, instances: Instances) -> Instances:\n \"\"\"\n If input instances don't have ID, ID_period, lost_frame_count fields,\n this method is used to initialize these fields.\n\n Args:\n instances: D2 Instances, for predictions of the current frame\n Return:\n D2 Instances with extra fields added\n \"\"\"\n if not instances.has(\"ID\"):\n instances.set(\"ID\", [None] * len(instances))\n if not instances.has(\"ID_period\"):\n instances.set(\"ID_period\", [None] * len(instances))\n if not instances.has(\"lost_frame_count\"):\n instances.set(\"lost_frame_count\", [None] * len(instances))\n if self._prev_instances is None:\n instances.ID = list(range(len(instances)))\n self._id_count += len(instances)\n instances.ID_period = [1] * len(instances)\n instances.lost_frame_count = [0] * len(instances)\n return instances"}, {"class_start_lineno": 1, "class_end_lineno": 423, "func_start_lineno": 310, "func_end_lineno": 329, "func_code": "def pairwise_intersection(boxes1: Boxes, boxes2: Boxes) -> torch.Tensor:\n \"\"\"\n Given two lists of boxes of size N and M,\n compute the intersection area between __all__ N x M pairs of boxes.\n The box order must be (xmin, ymin, xmax, ymax)\n\n Args:\n boxes1,boxes2 (Boxes): two `Boxes`. Contains N & M boxes, respectively.\n\n Returns:\n Tensor: intersection, sized [N,M].\n \"\"\"\n boxes1, boxes2 = boxes1.tensor, boxes2.tensor\n width_height = torch.min(boxes1[:, None, 2:], boxes2[:, 2:]) - torch.max(\n boxes1[:, None, :2], boxes2[:, :2]\n ) # [N,M,2]\n\n width_height.clamp_(min=0) # [N,M,2]\n intersection = width_height.prod(dim=2) # [N,M]\n return intersection"}, {"class_start_lineno": 1, "class_end_lineno": 423, "func_start_lineno": 334, "func_end_lineno": 356, "func_code": "def pairwise_iou(boxes1: Boxes, boxes2: Boxes) -> torch.Tensor:\n \"\"\"\n Given two lists of boxes of size N and M, compute the IoU\n (intersection over union) between **all** N x M pairs of boxes.\n The box order must be (xmin, ymin, xmax, ymax).\n\n Args:\n boxes1,boxes2 (Boxes): two `Boxes`. Contains N & M boxes, respectively.\n\n Returns:\n Tensor: IoU, sized [N,M].\n \"\"\"\n area1 = boxes1.area() # [N]\n area2 = boxes2.area() # [M]\n inter = pairwise_intersection(boxes1, boxes2)\n\n # handle empty boxes\n iou = torch.where(\n inter > 0,\n inter / (area1[:, None] + area2 - inter),\n torch.zeros(1, dtype=inter.dtype, device=inter.device),\n )\n return iou"}, {"class_start_lineno": 17, "class_end_lineno": 260, "func_start_lineno": 88, "func_end_lineno": 121, "func_code": " def update(self, instances: Instances) -> Instances:\n \"\"\"\n See BaseTracker description\n \"\"\"\n if instances.has(\"pred_keypoints\"):\n raise NotImplementedError(\"Need to add support for keypoints\")\n instances = self._initialize_extra_fields(instances)\n if self._prev_instances is not None:\n # calculate IoU of all bbox pairs\n iou_all = pairwise_iou(\n boxes1=instances.pred_boxes,\n boxes2=self._prev_instances.pred_boxes,\n )\n # sort IoU in descending order\n bbox_pairs = self._create_prediction_pairs(instances, iou_all)\n # assign previous ID to current bbox if IoU > track_iou_threshold\n self._reset_fields()\n for bbox_pair in bbox_pairs:\n idx = bbox_pair[\"idx\"]\n prev_id = bbox_pair[\"prev_id\"]\n if idx in self._matched_idx \\\n or prev_id in self._matched_ID \\\n or bbox_pair[\"IoU\"] < self._track_iou_threshold:\n continue\n instances.ID[idx] = prev_id\n instances.ID_period[idx] = bbox_pair[\"prev_period\"] + 1\n instances.lost_frame_count[idx] = 0\n self._matched_idx.add(idx)\n self._matched_ID.add(prev_id)\n self._untracked_prev_idx.remove(bbox_pair[\"prev_idx\"])\n instances = self._assign_new_id(instances)\n instances = self._merge_untracked_instances(instances)\n self._prev_instances = copy.deepcopy(instances)\n return instances"}], "type": ["function_empty", "Development"], "node": ["detectron2.structures.instances.Instances.set", "detectron2.structures.instances.Instances.__setattr__", "detectron2.tracking.bbox_iou_tracker.BBoxIOUTracker._initialize_extra_fields", "detectron2.structures.boxes.pairwise_intersection", "detectron2.structures.boxes.pairwise_iou", "detectron2.tracking.bbox_iou_tracker.BBoxIOUTracker.update"], "language": "Python", "toolfunc_count": 4, "func_count": 5, "pytest_info": {"total_num": 5, "base_passed_num": 2}} {"id": ["UniRef.detectron2.structures.boxes.pairwise_intersection", "UniRef.detectron2.structures.boxes.pairwise_ioa", "UniRef.detectron2.structures.boxes.pairwise_iou"], "project": "UniRef", "origin_file": ["detectron2/structures/boxes.py", "detectron2/structures/boxes.py", "detectron2/structures/boxes.py"], "test_list": ["tests/structures/test_boxes.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 423, "func_start_lineno": 310, "func_end_lineno": 329, "func_code": "def pairwise_intersection(boxes1: Boxes, boxes2: Boxes) -> torch.Tensor:\n \"\"\"\n Given two lists of boxes of size N and M,\n compute the intersection area between __all__ N x M pairs of boxes.\n The box order must be (xmin, ymin, xmax, ymax)\n\n Args:\n boxes1,boxes2 (Boxes): two `Boxes`. Contains N & M boxes, respectively.\n\n Returns:\n Tensor: intersection, sized [N,M].\n \"\"\"\n boxes1, boxes2 = boxes1.tensor, boxes2.tensor\n width_height = torch.min(boxes1[:, None, 2:], boxes2[:, 2:]) - torch.max(\n boxes1[:, None, :2], boxes2[:, :2]\n ) # [N,M,2]\n\n width_height.clamp_(min=0) # [N,M,2]\n intersection = width_height.prod(dim=2) # [N,M]\n return intersection"}, {"class_start_lineno": 1, "class_end_lineno": 423, "func_start_lineno": 359, "func_end_lineno": 376, "func_code": "def pairwise_ioa(boxes1: Boxes, boxes2: Boxes) -> torch.Tensor:\n \"\"\"\n Similar to :func:`pariwise_iou` but compute the IoA (intersection over boxes2 area).\n\n Args:\n boxes1,boxes2 (Boxes): two `Boxes`. Contains N & M boxes, respectively.\n\n Returns:\n Tensor: IoA, sized [N,M].\n \"\"\"\n area2 = boxes2.area() # [M]\n inter = pairwise_intersection(boxes1, boxes2)\n\n # handle empty boxes\n ioa = torch.where(\n inter > 0, inter / area2, torch.zeros(1, dtype=inter.dtype, device=inter.device)\n )\n return ioa"}, {"class_start_lineno": 1, "class_end_lineno": 423, "func_start_lineno": 334, "func_end_lineno": 356, "func_code": "def pairwise_iou(boxes1: Boxes, boxes2: Boxes) -> torch.Tensor:\n \"\"\"\n Given two lists of boxes of size N and M, compute the IoU\n (intersection over union) between **all** N x M pairs of boxes.\n The box order must be (xmin, ymin, xmax, ymax).\n\n Args:\n boxes1,boxes2 (Boxes): two `Boxes`. Contains N & M boxes, respectively.\n\n Returns:\n Tensor: IoU, sized [N,M].\n \"\"\"\n area1 = boxes1.area() # [N]\n area2 = boxes2.area() # [M]\n inter = pairwise_intersection(boxes1, boxes2)\n\n # handle empty boxes\n iou = torch.where(\n inter > 0,\n inter / (area1[:, None] + area2 - inter),\n torch.zeros(1, dtype=inter.dtype, device=inter.device),\n )\n return iou"}], "type": ["function_empty"], "node": ["detectron2.structures.boxes.pairwise_intersection", "detectron2.structures.boxes.pairwise_ioa", "detectron2.structures.boxes.pairwise_iou"], "language": "Python", "toolfunc_count": 3, "func_count": 3, "pytest_info": {"total_num": 17, "base_passed_num": 15}} {"id": ["UniRef.detectron2.data.transforms.transform.RotationTransform::create_rotation_matrix", "UniRef.detectron2.data.transforms.transform.RotationTransform::inverse"], "project": "UniRef", "origin_file": ["detectron2/data/transforms/transform.py", "detectron2/data/transforms/transform.py"], "test_list": ["tests/data/test_rotation_transform.py"], "prob_info": [{"class_start_lineno": 162, "class_end_lineno": 247, "func_start_lineno": 223, "func_end_lineno": 233, "func_code": " def create_rotation_matrix(self, offset=0):\n center = (self.center[0] + offset, self.center[1] + offset)\n rm = cv2.getRotationMatrix2D(tuple(center), self.angle, 1)\n if self.expand:\n # Find the coordinates of the center of rotation in the new image\n # The only point for which we know the future coordinates is the center of the image\n rot_im_center = cv2.transform(self.image_center[None, None, :] + offset, rm)[0, 0, :]\n new_center = np.array([self.bound_w / 2, self.bound_h / 2]) + offset - rot_im_center\n # shift the rotation center to the new coordinates\n rm[:, 2] += new_center\n return rm"}, {"class_start_lineno": 162, "class_end_lineno": 247, "func_start_lineno": 235, "func_end_lineno": 247, "func_code": " def inverse(self):\n \"\"\"\n The inverse is to rotate it back with expand, and crop to get the original shape.\n \"\"\"\n if not self.expand: # Not possible to inverse if a part of the image is lost\n raise NotImplementedError()\n rotation = RotationTransform(\n self.bound_h, self.bound_w, -self.angle, True, None, self.interp\n )\n crop = CropTransform(\n (rotation.bound_w - self.w) // 2, (rotation.bound_h - self.h) // 2, self.w, self.h\n )\n return TransformList([rotation, crop])"}], "type": ["Development"], "node": ["detectron2.data.transforms.transform.RotationTransform.create_rotation_matrix", "detectron2.data.transforms.transform.RotationTransform.inverse"], "language": "Python", "toolfunc_count": 0, "func_count": 2, "pytest_info": {"total_num": 6, "base_passed_num": 1}} {"id": ["langchain_core.libs.core.langchain_core.load.dump.dumps", "langchain_core.libs.core.langchain_core.load.dump.default", "langchain_core.libs.core.langchain_core.load.dump.dumpd"], "project": "langchain_core", "origin_file": ["langchain_core/load/dump.py", "langchain_core/load/dump.py", "langchain_core/load/dump.py"], "test_list": ["libs/core/tests/unit_tests/load/test_serializable.py", "libs/core/tests/unit_tests/messages/test_ai.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 70, "func_start_lineno": 23, "func_end_lineno": 53, "func_code": "def dumps(obj: Any, *, pretty: bool = False, **kwargs: Any) -> str:\n \"\"\"Return a json string representation of an object.\n\n Args:\n obj: The object to dump.\n pretty: Whether to pretty print the json. If true, the json will be\n indented with 2 spaces (if no indent is provided as part of kwargs).\n Default is False.\n kwargs: Additional arguments to pass to json.dumps\n\n Returns:\n A json string representation of the object.\n\n Raises:\n ValueError: If `default` is passed as a kwarg.\n \"\"\"\n if \"default\" in kwargs:\n msg = \"`default` should not be passed to dumps\"\n raise ValueError(msg)\n try:\n if pretty:\n indent = kwargs.pop(\"indent\", 2)\n return json.dumps(obj, default=default, indent=indent, **kwargs)\n else:\n return json.dumps(obj, default=default, **kwargs)\n except TypeError:\n if pretty:\n indent = kwargs.pop(\"indent\", 2)\n return json.dumps(to_json_not_implemented(obj), indent=indent, **kwargs)\n else:\n return json.dumps(to_json_not_implemented(obj), **kwargs)"}, {"class_start_lineno": 1, "class_end_lineno": 70, "func_start_lineno": 7, "func_end_lineno": 20, "func_code": "def default(obj: Any) -> Any:\n \"\"\"Return a default value for a Serializable object or\n a SerializedNotImplemented object.\n\n Args:\n obj: The object to serialize to json if it is a Serializable object.\n\n Returns:\n A json serializable object or a SerializedNotImplemented object.\n \"\"\"\n if isinstance(obj, Serializable):\n return obj.to_json()\n else:\n return to_json_not_implemented(obj)"}, {"class_start_lineno": 1, "class_end_lineno": 70, "func_start_lineno": 56, "func_end_lineno": 70, "func_code": "def dumpd(obj: Any) -> Any:\n \"\"\"Return a dict representation of an object.\n\n Note:\n Unfortunately this function is not as efficient as it could be\n because it first dumps the object to a json string and then loads it\n back into a dictionary.\n\n Args:\n obj: The object to dump.\n\n Returns:\n dictionary that can be serialized to json using json.dumps\n \"\"\"\n return json.loads(dumps(obj))"}], "type": ["function_empty"], "node": ["langchain_core.load.dump.dumps", "langchain_core.load.dump.default", "langchain_core.load.dump.dumpd"], "language": "Python", "toolfunc_count": 3, "func_count": 3, "pytest_info": {"total_num": 19, "base_passed_num": 12}} {"id": ["langchain_core.libs.core.langchain_core.runnables.config.ensure_config", "langchain_core.libs.core.langchain_core.runnables.config.patch_config", "langchain_core.libs.core.langchain_core.utils.json.parse_json_markdown", "langchain_core.libs.core.langchain_core.output_parsers.json.JsonOutputParser::parse_result"], "project": "langchain_core", "origin_file": ["langchain_core/runnables/config.py", "langchain_core/runnables/config.py", "langchain_core/utils/json.py", "langchain_core/output_parsers/json.py"], "test_list": ["libs/core/tests/unit_tests/output_parsers/test_json.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 593, "func_start_lineno": 149, "func_end_lineno": 199, "func_code": "def ensure_config(config: Optional[RunnableConfig] = None) -> RunnableConfig:\n \"\"\"Ensure that a config is a dict with all keys present.\n\n Args:\n config (Optional[RunnableConfig], optional): The config to ensure.\n Defaults to None.\n\n Returns:\n RunnableConfig: The ensured config.\n \"\"\"\n empty = RunnableConfig(\n tags=[],\n metadata={},\n callbacks=None,\n recursion_limit=DEFAULT_RECURSION_LIMIT,\n configurable={},\n )\n if var_config := var_child_runnable_config.get():\n empty.update(\n cast(\n RunnableConfig,\n {\n k: v.copy() if k in COPIABLE_KEYS else v # type: ignore[attr-defined]\n for k, v in var_config.items()\n if v is not None\n },\n )\n )\n if config is not None:\n empty.update(\n cast(\n RunnableConfig,\n {\n k: v.copy() if k in COPIABLE_KEYS else v # type: ignore[attr-defined]\n for k, v in config.items()\n if v is not None and k in CONFIG_KEYS\n },\n )\n )\n if config is not None:\n for k, v in config.items():\n if k not in CONFIG_KEYS and v is not None:\n empty[\"configurable\"][k] = v\n for key, value in empty.get(\"configurable\", {}).items():\n if (\n not key.startswith(\"__\")\n and isinstance(value, (str, int, float, bool))\n and key not in empty[\"metadata\"]\n ):\n empty[\"metadata\"][key] = value\n return empty"}, {"class_start_lineno": 1, "class_end_lineno": 593, "func_start_lineno": 249, "func_end_lineno": 292, "func_code": "def patch_config(\n config: Optional[RunnableConfig],\n *,\n callbacks: Optional[BaseCallbackManager] = None,\n recursion_limit: Optional[int] = None,\n max_concurrency: Optional[int] = None,\n run_name: Optional[str] = None,\n configurable: Optional[dict[str, Any]] = None,\n) -> RunnableConfig:\n \"\"\"Patch a config with new values.\n\n Args:\n config (Optional[RunnableConfig]): The config to patch.\n callbacks (Optional[BaseCallbackManager], optional): The callbacks to set.\n Defaults to None.\n recursion_limit (Optional[int], optional): The recursion limit to set.\n Defaults to None.\n max_concurrency (Optional[int], optional): The max concurrency to set.\n Defaults to None.\n run_name (Optional[str], optional): The run name to set. Defaults to None.\n configurable (Optional[Dict[str, Any]], optional): The configurable to set.\n Defaults to None.\n\n Returns:\n RunnableConfig: The patched config.\n \"\"\"\n config = ensure_config(config)\n if callbacks is not None:\n # If we're replacing callbacks, we need to unset run_name\n # As that should apply only to the same run as the original callbacks\n config[\"callbacks\"] = callbacks\n if \"run_name\" in config:\n del config[\"run_name\"]\n if \"run_id\" in config:\n del config[\"run_id\"]\n if recursion_limit is not None:\n config[\"recursion_limit\"] = recursion_limit\n if max_concurrency is not None:\n config[\"max_concurrency\"] = max_concurrency\n if run_name is not None:\n config[\"run_name\"] = run_name\n if configurable is not None:\n config[\"configurable\"] = {**config.get(\"configurable\", {}), **configurable}\n return config"}, {"class_start_lineno": 1, "class_end_lineno": 191, "func_start_lineno": 125, "func_end_lineno": 145, "func_code": "def parse_json_markdown(\n json_string: str, *, parser: Callable[[str], Any] = parse_partial_json\n) -> dict:\n \"\"\"Parse a JSON string from a Markdown string.\n\n Args:\n json_string: The Markdown string.\n\n Returns:\n The parsed JSON object as a Python dictionary.\n \"\"\"\n try:\n return _parse_json(json_string, parser=parser)\n except json.JSONDecodeError:\n # Try to find JSON string within triple backticks\n match = _json_markdown_re.search(json_string)\n\n # If no match found, assume the entire string is a JSON string\n # Else, use the content within the backticks\n json_str = json_string if match is None else match.group(2)\n return _parse_json(json_str, parser=parser)"}, {"class_start_lineno": 34, "class_end_lineno": 123, "func_start_lineno": 57, "func_end_lineno": 86, "func_code": " def parse_result(self, result: list[Generation], *, partial: bool = False) -> Any:\n \"\"\"Parse the result of an LLM call to a JSON object.\n\n Args:\n result: The result of the LLM call.\n partial: Whether to parse partial JSON objects.\n If True, the output will be a JSON object containing\n all the keys that have been returned so far.\n If False, the output will be the full JSON object.\n Default is False.\n\n Returns:\n The parsed JSON object.\n\n Raises:\n OutputParserException: If the output is not valid JSON.\n \"\"\"\n text = result[0].text\n text = text.strip()\n if partial:\n try:\n return parse_json_markdown(text)\n except JSONDecodeError:\n return None\n else:\n try:\n return parse_json_markdown(text)\n except JSONDecodeError as e:\n msg = f\"Invalid json output: {text}\"\n raise OutputParserException(msg, llm_output=text) from e"}], "type": ["function_empty"], "node": ["langchain_core.runnables.config.ensure_config", "langchain_core.runnables.config.patch_config", "langchain_core.utils.json.parse_json_markdown", "langchain_core.output_parsers.json.JsonOutputParser.parse_result"], "language": "Python", "toolfunc_count": 4, "func_count": 4, "pytest_info": {"total_num": 36, "base_passed_num": 11}} {"id": ["langchain_core.libs.core.langchain_core.utils.json.parse_partial_json", "langchain_core.libs.core.langchain_core.messages.ai.AIMessageChunk::init_tool_calls", "langchain_core.libs.core.langchain_core.utils._merge.merge_lists", "langchain_core.libs.core.langchain_core.utils._merge.merge_dicts"], "project": "langchain_core", "origin_file": ["langchain_core/utils/json.py", "langchain_core/messages/ai.py", "langchain_core/utils/_merge.py", "langchain_core/utils/_merge.py", "langchain_core/runnables/base.py"], "test_list": ["libs/core/tests/unit_tests/output_parsers/test_openai_tools.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 191, "func_start_lineno": 43, "func_end_lineno": 119, "func_code": "def parse_partial_json(s: str, *, strict: bool = False) -> Any:\n \"\"\"Parse a JSON string that may be missing closing braces.\n\n Args:\n s: The JSON string to parse.\n strict: Whether to use strict parsing. Defaults to False.\n\n Returns:\n The parsed JSON object as a Python dictionary.\n \"\"\"\n # Attempt to parse the string as-is.\n try:\n return json.loads(s, strict=strict)\n except json.JSONDecodeError:\n pass\n\n # Initialize variables.\n new_chars = []\n stack = []\n is_inside_string = False\n escaped = False\n\n # Process each character in the string one at a time.\n for char in s:\n if is_inside_string:\n if char == '\"' and not escaped:\n is_inside_string = False\n elif char == \"\\n\" and not escaped:\n char = \"\\\\n\" # Replace the newline character with the escape sequence.\n elif char == \"\\\\\":\n escaped = not escaped\n else:\n escaped = False\n else:\n if char == '\"':\n is_inside_string = True\n escaped = False\n elif char == \"{\":\n stack.append(\"}\")\n elif char == \"[\":\n stack.append(\"]\")\n elif char == \"}\" or char == \"]\":\n if stack and stack[-1] == char:\n stack.pop()\n else:\n # Mismatched closing character; the input is malformed.\n return None\n\n # Append the processed character to the new string.\n new_chars.append(char)\n\n # If we're still inside a string at the end of processing,\n # we need to close the string.\n if is_inside_string:\n if escaped: # Remoe unterminated escape character\n new_chars.pop()\n new_chars.append('\"')\n\n # Reverse the stack to get the closing characters.\n stack.reverse()\n\n # Try to parse mods of string until we succeed or run out of characters.\n while new_chars:\n # Close any remaining open structures in the reverse\n # order that they were opened.\n # Attempt to parse the modified string as JSON.\n try:\n return json.loads(\"\".join(new_chars + stack), strict=strict)\n except json.JSONDecodeError:\n # If we still can't parse the string as JSON,\n # try removing the last character\n new_chars.pop()\n\n # If we got here, we ran out of characters to remove\n # and still couldn't parse the string as JSON, so return the parse error\n # for the original string.\n return json.loads(s, strict=strict)"}, {"class_start_lineno": 296, "class_end_lineno": 403, "func_start_lineno": 328, "func_end_lineno": 394, "func_code": " def init_tool_calls(self) -> Self:\n \"\"\"Initialize tool calls from tool call chunks.\n\n Args:\n values: The values to validate.\n\n Returns:\n The values with tool calls initialized.\n\n Raises:\n ValueError: If the tool call chunks are malformed.\n \"\"\"\n if not self.tool_call_chunks:\n if self.tool_calls:\n self.tool_call_chunks = [\n create_tool_call_chunk(\n name=tc[\"name\"],\n args=json.dumps(tc[\"args\"]),\n id=tc[\"id\"],\n index=None,\n )\n for tc in self.tool_calls\n ]\n if self.invalid_tool_calls:\n tool_call_chunks = self.tool_call_chunks\n tool_call_chunks.extend(\n [\n create_tool_call_chunk(\n name=tc[\"name\"], args=tc[\"args\"], id=tc[\"id\"], index=None\n )\n for tc in self.invalid_tool_calls\n ]\n )\n self.tool_call_chunks = tool_call_chunks\n\n return self\n tool_calls = []\n invalid_tool_calls = []\n\n def add_chunk_to_invalid_tool_calls(chunk: ToolCallChunk) -> None:\n invalid_tool_calls.append(\n create_invalid_tool_call(\n name=chunk[\"name\"],\n args=chunk[\"args\"],\n id=chunk[\"id\"],\n error=None,\n )\n )\n\n for chunk in self.tool_call_chunks:\n try:\n args_ = parse_partial_json(chunk[\"args\"]) if chunk[\"args\"] != \"\" else {} # type: ignore[arg-type]\n if isinstance(args_, dict):\n tool_calls.append(\n create_tool_call(\n name=chunk[\"name\"] or \"\",\n args=args_,\n id=chunk[\"id\"],\n )\n )\n else:\n add_chunk_to_invalid_tool_calls(chunk)\n except Exception:\n add_chunk_to_invalid_tool_calls(chunk)\n self.tool_calls = tool_calls\n self.invalid_tool_calls = invalid_tool_calls\n return self"}, {"class_start_lineno": 1, "class_end_lineno": 148, "func_start_lineno": 72, "func_end_lineno": 106, "func_code": "def merge_lists(left: Optional[list], *others: Optional[list]) -> Optional[list]:\n \"\"\"Add many lists, handling None.\n\n Args:\n left: The first list to merge.\n others: The other lists to merge.\n\n Returns:\n The merged list.\n \"\"\"\n merged = left.copy() if left is not None else None\n for other in others:\n if other is None:\n continue\n elif merged is None:\n merged = other.copy()\n else:\n for e in other:\n if isinstance(e, dict) and \"index\" in e and isinstance(e[\"index\"], int):\n to_merge = [\n i\n for i, e_left in enumerate(merged)\n if e_left[\"index\"] == e[\"index\"]\n ]\n if to_merge:\n # TODO: Remove this once merge_dict is updated with special\n # handling for 'type'.\n if \"type\" in e:\n e = {k: v for k, v in e.items() if k != \"type\"}\n merged[to_merge[0]] = merge_dicts(merged[to_merge[0]], e)\n else:\n merged.append(e)\n else:\n merged.append(e)\n return merged"}, {"class_start_lineno": 1, "class_end_lineno": 148, "func_start_lineno": 6, "func_end_lineno": 69, "func_code": "def merge_dicts(left: dict[str, Any], *others: dict[str, Any]) -> dict[str, Any]:\n \"\"\"Merge many dicts, handling specific scenarios where a key exists in both\n dictionaries but has a value of None in 'left'. In such cases, the method uses the\n value from 'right' for that key in the merged dictionary.\n\n Args:\n left: The first dictionary to merge.\n others: The other dictionaries to merge.\n\n Returns:\n The merged dictionary.\n\n Raises:\n TypeError: If the key exists in both dictionaries but has a different type.\n TypeError: If the value has an unsupported type.\n\n Example:\n If left = {\"function_call\": {\"arguments\": None}} and\n right = {\"function_call\": {\"arguments\": \"{\\n\"}}\n then, after merging, for the key \"function_call\",\n the value from 'right' is used,\n resulting in merged = {\"function_call\": {\"arguments\": \"{\\n\"}}.\n \"\"\"\n merged = left.copy()\n for right in others:\n for right_k, right_v in right.items():\n if right_k not in merged or right_v is not None and merged[right_k] is None:\n merged[right_k] = right_v\n elif right_v is None:\n continue\n elif type(merged[right_k]) is not type(right_v):\n msg = (\n f'additional_kwargs[\"{right_k}\"] already exists in this message,'\n \" but with a different type.\"\n )\n raise TypeError(msg)\n elif isinstance(merged[right_k], str):\n # TODO: Add below special handling for 'type' key in 0.3 and remove\n # merge_lists 'type' logic.\n #\n # if right_k == \"type\":\n # if merged[right_k] == right_v:\n # continue\n # else:\n # raise ValueError(\n # \"Unable to merge. Two different values seen for special \"\n # f\"key 'type': {merged[right_k]} and {right_v}. 'type' \"\n # \"should either occur once or have the same value across \"\n # \"all dicts.\"\n # )\n merged[right_k] += right_v\n elif isinstance(merged[right_k], dict):\n merged[right_k] = merge_dicts(merged[right_k], right_v)\n elif isinstance(merged[right_k], list):\n merged[right_k] = merge_lists(merged[right_k], right_v)\n elif merged[right_k] == right_v:\n continue\n else:\n msg = (\n f\"Additional kwargs key {right_k} already exists in left dict and \"\n f\"value has unsupported type {type(merged[right_k])}.\"\n )\n raise TypeError(msg)\n return merged"}, {"class_start_lineno": 2659, "class_end_lineno": 3435, "func_start_lineno": 3403, "func_end_lineno": 3409, "func_code": " def stream(\n self,\n input: Input,\n config: Optional[RunnableConfig] = None,\n **kwargs: Optional[Any],\n ) -> Iterator[Output]:\n yield from self.transform(iter([input]), config, **kwargs)"}], "type": ["function_empty"], "node": ["langchain_core.utils.json.parse_partial_json", "langchain_core.messages.ai.AIMessageChunk.init_tool_calls", "langchain_core.utils._merge.merge_lists", "langchain_core.utils._merge.merge_dicts", "langchain_core.runnables.base.RunnableSequence.stream"], "language": "Python", "toolfunc_count": 4, "func_count": 4, "pytest_info": {"total_num": 11, "base_passed_num": 2}} {"id": ["langchain_core.libs.core.langchain_core.utils.formatting.StrictFormatter::validate_input_variables", "langchain_core.libs.core.langchain_core.prompts.string.check_valid_template"], "project": "langchain_core", "origin_file": ["langchain_core/utils/formatting.py", "langchain_core/prompts/string.py", "langchain_core/prompts/few_shot.py"], "test_list": ["libs/core/tests/unit_tests/prompts/test_few_shot.py"], "prob_info": [{"class_start_lineno": 8, "class_end_lineno": 48, "func_start_lineno": 35, "func_end_lineno": 48, "func_code": " def validate_input_variables(\n self, format_string: str, input_variables: list[str]\n ) -> None:\n \"\"\"Check that all input variables are used in the format string.\n\n Args:\n format_string: The format string.\n input_variables: The input variables.\n\n Raises:\n ValueError: If any input variables are not used in the format string.\n \"\"\"\n dummy_inputs = dict.fromkeys(input_variables, \"foo\")\n super().format(format_string, **dummy_inputs)"}, {"class_start_lineno": 1, "class_end_lineno": 319, "func_start_lineno": 207, "func_end_lineno": 236, "func_code": "def check_valid_template(\n template: str, template_format: str, input_variables: list[str]\n) -> None:\n \"\"\"Check that template string is valid.\n\n Args:\n template: The template string.\n template_format: The template format. Should be one of \"f-string\" or \"jinja2\".\n input_variables: The input variables.\n\n Raises:\n ValueError: If the template format is not supported.\n ValueError: If the prompt schema is invalid.\n \"\"\"\n try:\n validator_func = DEFAULT_VALIDATOR_MAPPING[template_format]\n except KeyError as exc:\n msg = (\n f\"Invalid template format {template_format!r}, should be one of\"\n f\" {list(DEFAULT_FORMATTER_MAPPING)}.\"\n )\n raise ValueError(msg) from exc\n try:\n validator_func(template, input_variables)\n except (KeyError, IndexError) as exc:\n msg = (\n \"Invalid prompt schema; check for mismatched or missing input parameters\"\n f\" from {input_variables}.\"\n )\n raise ValueError(msg) from exc"}, {"class_start_lineno": 115, "class_end_lineno": 244, "func_start_lineno": 148, "func_end_lineno": 164, "func_code": " def template_is_valid(self) -> Self:\n \"\"\"Check that prefix, suffix, and input variables are consistent.\"\"\"\n if self.validate_template:\n check_valid_template(\n self.prefix + self.suffix,\n self.template_format,\n self.input_variables + list(self.partial_variables),\n )\n elif self.template_format or None:\n self.input_variables = [\n var\n for var in get_template_variables(\n self.prefix + self.suffix, self.template_format\n )\n if var not in self.partial_variables\n ]\n return self"}], "type": ["function_empty"], "node": ["langchain_core.utils.formatting.StrictFormatter.validate_input_variables", "langchain_core.prompts.string.check_valid_template", "langchain_core.prompts.few_shot.FewShotPromptTemplate.template_is_valid"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 16, "base_passed_num": 13}} {"id": ["langchain_core.libs.core.langchain_core.prompts.loading.load_prompt_from_config", "langchain_core.libs.core.langchain_core.prompts.loading.load_prompt"], "project": "langchain_core", "origin_file": ["langchain_core/prompts/loading.py", "langchain_core/prompts/loading.py", "langchain_core/prompts/loading.py"], "test_list": ["libs/core/tests/unit_tests/prompts/test_loading.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 203, "func_start_lineno": 20, "func_end_lineno": 41, "func_code": "def load_prompt_from_config(config: dict) -> BasePromptTemplate:\n \"\"\"Load prompt from Config Dict.\n\n Args:\n config: Dict containing the prompt configuration.\n\n Returns:\n A PromptTemplate object.\n\n Raises:\n ValueError: If the prompt type is not supported.\n \"\"\"\n if \"_type\" not in config:\n logger.warning(\"No `_type` key found, defaulting to `prompt`.\")\n config_type = config.pop(\"_type\", \"prompt\")\n\n if config_type not in type_to_loader_dict:\n msg = f\"Loading {config_type} prompt not supported\"\n raise ValueError(msg)\n\n prompt_loader = type_to_loader_dict[config_type]\n return prompt_loader(config)"}, {"class_start_lineno": 1, "class_end_lineno": 203, "func_start_lineno": 141, "func_end_lineno": 163, "func_code": "def load_prompt(\n path: Union[str, Path], encoding: Optional[str] = None\n) -> BasePromptTemplate:\n \"\"\"Unified method for loading a prompt from LangChainHub or local fs.\n\n Args:\n path: Path to the prompt file.\n encoding: Encoding of the file. Defaults to None.\n\n Returns:\n A PromptTemplate object.\n\n Raises:\n RuntimeError: If the path is a Lang Chain Hub path.\n \"\"\"\n if isinstance(path, str) and path.startswith(\"lc://\"):\n msg = (\n \"Loading from the deprecated github-based Hub is no longer supported. \"\n \"Please use the new LangChain Hub at https://smith.langchain.com/hub \"\n \"instead.\"\n )\n raise RuntimeError(msg)\n return _load_prompt_from_file(path, encoding)"}, {"class_start_lineno": 1, "class_end_lineno": 203, "func_start_lineno": 99, "func_end_lineno": 118, "func_code": "def _load_few_shot_prompt(config: dict) -> FewShotPromptTemplate:\n \"\"\"Load the \"few shot\" prompt from the config.\"\"\"\n # Load the suffix and prefix templates.\n config = _load_template(\"suffix\", config)\n config = _load_template(\"prefix\", config)\n # Load the example prompt.\n if \"example_prompt_path\" in config:\n if \"example_prompt\" in config:\n msg = (\n \"Only one of example_prompt and example_prompt_path should \"\n \"be specified.\"\n )\n raise ValueError(msg)\n config[\"example_prompt\"] = load_prompt(config.pop(\"example_prompt_path\"))\n else:\n config[\"example_prompt\"] = load_prompt_from_config(config[\"example_prompt\"])\n # Load the examples.\n config = _load_examples(config)\n config = _load_output_parser(config)\n return FewShotPromptTemplate(**config)"}], "type": ["function_empty"], "node": ["langchain_core.prompts.loading.load_prompt_from_config", "langchain_core.prompts.loading.load_prompt", "langchain_core.prompts.loading._load_few_shot_prompt"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 10, "base_passed_num": 0}} {"id": ["langchain_core.libs.core.langchain_core.runnables.base.RunnableLambda::deps", "langchain_core.libs.core.langchain_core.beta.runnables.context.config_with_context", "langchain_core.libs.core.langchain_core.runnables.config.ensure_config", "langchain_core.libs.core.langchain_core.runnables.config.patch_config"], "project": "langchain_core", "origin_file": ["langchain_core/runnables/base.py", "langchain_core/runnables/base.py", "langchain_core/beta/runnables/context.py", "langchain_core/runnables/config.py", "langchain_core/runnables/config.py"], "test_list": ["libs/core/tests/unit_tests/prompts/test_structured.py"], "prob_info": [{"class_start_lineno": 4230, "class_end_lineno": 4967, "func_start_lineno": 4471, "func_end_lineno": 4491, "func_code": " def deps(self) -> list[Runnable]:\n \"\"\"The dependencies of this Runnable.\n\n Returns:\n The dependencies of this Runnable. If the function has nonlocal\n variables that are Runnables, they are considered dependencies.\n \"\"\"\n if hasattr(self, \"func\"):\n objects = get_function_nonlocals(self.func)\n elif hasattr(self, \"afunc\"):\n objects = get_function_nonlocals(self.afunc)\n else:\n objects = []\n\n deps: list[Runnable] = []\n for obj in objects:\n if isinstance(obj, Runnable):\n deps.append(obj)\n elif isinstance(getattr(obj, \"__self__\", None), Runnable):\n deps.append(obj.__self__)\n return deps"}, {"class_start_lineno": 4230, "class_end_lineno": 4967, "func_start_lineno": 4494, "func_end_lineno": 4497, "func_code": " def config_specs(self) -> list[ConfigurableFieldSpec]:\n return get_unique_config_specs(\n spec for dep in self.deps for spec in dep.config_specs\n )"}, {"class_start_lineno": 1, "class_end_lineno": 401, "func_start_lineno": 140, "func_end_lineno": 153, "func_code": "def config_with_context(\n config: RunnableConfig,\n steps: list[Runnable],\n) -> RunnableConfig:\n \"\"\"Patch a runnable config with context getters and setters.\n\n Args:\n config: The runnable config.\n steps: The runnable steps.\n\n Returns:\n The patched runnable config.\n \"\"\"\n return _config_with_context(config, steps, _setter, _getter, threading.Event)"}, {"class_start_lineno": 1, "class_end_lineno": 593, "func_start_lineno": 149, "func_end_lineno": 199, "func_code": "def ensure_config(config: Optional[RunnableConfig] = None) -> RunnableConfig:\n \"\"\"Ensure that a config is a dict with all keys present.\n\n Args:\n config (Optional[RunnableConfig], optional): The config to ensure.\n Defaults to None.\n\n Returns:\n RunnableConfig: The ensured config.\n \"\"\"\n empty = RunnableConfig(\n tags=[],\n metadata={},\n callbacks=None,\n recursion_limit=DEFAULT_RECURSION_LIMIT,\n configurable={},\n )\n if var_config := var_child_runnable_config.get():\n empty.update(\n cast(\n RunnableConfig,\n {\n k: v.copy() if k in COPIABLE_KEYS else v # type: ignore[attr-defined]\n for k, v in var_config.items()\n if v is not None\n },\n )\n )\n if config is not None:\n empty.update(\n cast(\n RunnableConfig,\n {\n k: v.copy() if k in COPIABLE_KEYS else v # type: ignore[attr-defined]\n for k, v in config.items()\n if v is not None and k in CONFIG_KEYS\n },\n )\n )\n if config is not None:\n for k, v in config.items():\n if k not in CONFIG_KEYS and v is not None:\n empty[\"configurable\"][k] = v\n for key, value in empty.get(\"configurable\", {}).items():\n if (\n not key.startswith(\"__\")\n and isinstance(value, (str, int, float, bool))\n and key not in empty[\"metadata\"]\n ):\n empty[\"metadata\"][key] = value\n return empty"}, {"class_start_lineno": 1, "class_end_lineno": 593, "func_start_lineno": 249, "func_end_lineno": 292, "func_code": "def patch_config(\n config: Optional[RunnableConfig],\n *,\n callbacks: Optional[BaseCallbackManager] = None,\n recursion_limit: Optional[int] = None,\n max_concurrency: Optional[int] = None,\n run_name: Optional[str] = None,\n configurable: Optional[dict[str, Any]] = None,\n) -> RunnableConfig:\n \"\"\"Patch a config with new values.\n\n Args:\n config (Optional[RunnableConfig]): The config to patch.\n callbacks (Optional[BaseCallbackManager], optional): The callbacks to set.\n Defaults to None.\n recursion_limit (Optional[int], optional): The recursion limit to set.\n Defaults to None.\n max_concurrency (Optional[int], optional): The max concurrency to set.\n Defaults to None.\n run_name (Optional[str], optional): The run name to set. Defaults to None.\n configurable (Optional[Dict[str, Any]], optional): The configurable to set.\n Defaults to None.\n\n Returns:\n RunnableConfig: The patched config.\n \"\"\"\n config = ensure_config(config)\n if callbacks is not None:\n # If we're replacing callbacks, we need to unset run_name\n # As that should apply only to the same run as the original callbacks\n config[\"callbacks\"] = callbacks\n if \"run_name\" in config:\n del config[\"run_name\"]\n if \"run_id\" in config:\n del config[\"run_id\"]\n if recursion_limit is not None:\n config[\"recursion_limit\"] = recursion_limit\n if max_concurrency is not None:\n config[\"max_concurrency\"] = max_concurrency\n if run_name is not None:\n config[\"run_name\"] = run_name\n if configurable is not None:\n config[\"configurable\"] = {**config.get(\"configurable\", {}), **configurable}\n return config"}], "type": ["function_empty"], "node": ["langchain_core.runnables.base.RunnableLambda.deps", "langchain_core.runnables.base.RunnableLambda.config_specs", "langchain_core.beta.runnables.context.config_with_context", "langchain_core.runnables.config.ensure_config", "langchain_core.runnables.config.patch_config"], "language": "Python", "toolfunc_count": 4, "func_count": 4, "pytest_info": {"total_num": 4, "base_passed_num": 0}} {"id": ["langchain_core.libs.core.langchain_core.runnables.config.ensure_config", "langchain_core.libs.core.langchain_core.runnables.config.patch_config", "langchain_core.libs.core.langchain_core.callbacks.manager.handle_event", "langchain_core.libs.core.langchain_core.callbacks.manager.CallbackManagerForChainRun::on_chain_end"], "project": "langchain_core", "origin_file": ["langchain_core/runnables/config.py", "langchain_core/runnables/config.py", "langchain_core/callbacks/manager.py", "langchain_core/callbacks/manager.py"], "test_list": ["libs/core/tests/unit_tests/runnables/test_context.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 593, "func_start_lineno": 149, "func_end_lineno": 199, "func_code": "def ensure_config(config: Optional[RunnableConfig] = None) -> RunnableConfig:\n \"\"\"Ensure that a config is a dict with all keys present.\n\n Args:\n config (Optional[RunnableConfig], optional): The config to ensure.\n Defaults to None.\n\n Returns:\n RunnableConfig: The ensured config.\n \"\"\"\n empty = RunnableConfig(\n tags=[],\n metadata={},\n callbacks=None,\n recursion_limit=DEFAULT_RECURSION_LIMIT,\n configurable={},\n )\n if var_config := var_child_runnable_config.get():\n empty.update(\n cast(\n RunnableConfig,\n {\n k: v.copy() if k in COPIABLE_KEYS else v # type: ignore[attr-defined]\n for k, v in var_config.items()\n if v is not None\n },\n )\n )\n if config is not None:\n empty.update(\n cast(\n RunnableConfig,\n {\n k: v.copy() if k in COPIABLE_KEYS else v # type: ignore[attr-defined]\n for k, v in config.items()\n if v is not None and k in CONFIG_KEYS\n },\n )\n )\n if config is not None:\n for k, v in config.items():\n if k not in CONFIG_KEYS and v is not None:\n empty[\"configurable\"][k] = v\n for key, value in empty.get(\"configurable\", {}).items():\n if (\n not key.startswith(\"__\")\n and isinstance(value, (str, int, float, bool))\n and key not in empty[\"metadata\"]\n ):\n empty[\"metadata\"][key] = value\n return empty"}, {"class_start_lineno": 1, "class_end_lineno": 593, "func_start_lineno": 249, "func_end_lineno": 292, "func_code": "def patch_config(\n config: Optional[RunnableConfig],\n *,\n callbacks: Optional[BaseCallbackManager] = None,\n recursion_limit: Optional[int] = None,\n max_concurrency: Optional[int] = None,\n run_name: Optional[str] = None,\n configurable: Optional[dict[str, Any]] = None,\n) -> RunnableConfig:\n \"\"\"Patch a config with new values.\n\n Args:\n config (Optional[RunnableConfig]): The config to patch.\n callbacks (Optional[BaseCallbackManager], optional): The callbacks to set.\n Defaults to None.\n recursion_limit (Optional[int], optional): The recursion limit to set.\n Defaults to None.\n max_concurrency (Optional[int], optional): The max concurrency to set.\n Defaults to None.\n run_name (Optional[str], optional): The run name to set. Defaults to None.\n configurable (Optional[Dict[str, Any]], optional): The configurable to set.\n Defaults to None.\n\n Returns:\n RunnableConfig: The patched config.\n \"\"\"\n config = ensure_config(config)\n if callbacks is not None:\n # If we're replacing callbacks, we need to unset run_name\n # As that should apply only to the same run as the original callbacks\n config[\"callbacks\"] = callbacks\n if \"run_name\" in config:\n del config[\"run_name\"]\n if \"run_id\" in config:\n del config[\"run_id\"]\n if recursion_limit is not None:\n config[\"recursion_limit\"] = recursion_limit\n if max_concurrency is not None:\n config[\"max_concurrency\"] = max_concurrency\n if run_name is not None:\n config[\"run_name\"] = run_name\n if configurable is not None:\n config[\"configurable\"] = {**config.get(\"configurable\", {}), **configurable}\n return config"}, {"class_start_lineno": 1, "class_end_lineno": 2606, "func_start_lineno": 236, "func_end_lineno": 312, "func_code": "def handle_event(\n handlers: list[BaseCallbackHandler],\n event_name: str,\n ignore_condition_name: Optional[str],\n *args: Any,\n **kwargs: Any,\n) -> None:\n \"\"\"Generic event handler for CallbackManager.\n\n Note: This function is used by LangServe to handle events.\n\n Args:\n handlers: The list of handlers that will handle the event.\n event_name: The name of the event (e.g., \"on_llm_start\").\n ignore_condition_name: Name of the attribute defined on handler\n that if True will cause the handler to be skipped for the given event.\n *args: The arguments to pass to the event handler.\n **kwargs: The keyword arguments to pass to the event handler\n \"\"\"\n coros: list[Coroutine[Any, Any, Any]] = []\n\n try:\n message_strings: Optional[list[str]] = None\n for handler in handlers:\n try:\n if ignore_condition_name is None or not getattr(\n handler, ignore_condition_name\n ):\n event = getattr(handler, event_name)(*args, **kwargs)\n if asyncio.iscoroutine(event):\n coros.append(event)\n except NotImplementedError as e:\n if event_name == \"on_chat_model_start\":\n if message_strings is None:\n message_strings = [get_buffer_string(m) for m in args[1]]\n handle_event(\n [handler],\n \"on_llm_start\",\n \"ignore_llm\",\n args[0],\n message_strings,\n *args[2:],\n **kwargs,\n )\n else:\n handler_name = handler.__class__.__name__\n logger.warning(\n f\"NotImplementedError in {handler_name}.{event_name}\"\n f\" callback: {repr(e)}\"\n )\n except Exception as e:\n logger.warning(\n f\"Error in {handler.__class__.__name__}.{event_name} callback:\"\n f\" {repr(e)}\"\n )\n if handler.raise_error:\n raise\n finally:\n if coros:\n try:\n # Raises RuntimeError if there is no current event loop.\n asyncio.get_running_loop()\n loop_running = True\n except RuntimeError:\n loop_running = False\n\n if loop_running:\n # If we try to submit this coroutine to the running loop\n # we end up in a deadlock, as we'd have gotten here from a\n # running coroutine, which we cannot interrupt to run this one.\n # The solution is to create a new loop in a new thread.\n with ThreadPoolExecutor(1) as executor:\n executor.submit(\n cast(Callable, copy_context().run), _run_coros, coros\n ).result()\n else:\n _run_coros(coros)"}, {"class_start_lineno": 817, "class_end_lineno": 900, "func_start_lineno": 820, "func_end_lineno": 836, "func_code": " def on_chain_end(self, outputs: Union[dict[str, Any], Any], **kwargs: Any) -> None:\n \"\"\"Run when chain ends running.\n\n Args:\n outputs (Union[Dict[str, Any], Any]): The outputs of the chain.\n **kwargs (Any): Additional keyword arguments.\n \"\"\"\n handle_event(\n self.handlers,\n \"on_chain_end\",\n \"ignore_chain\",\n outputs,\n run_id=self.run_id,\n parent_run_id=self.parent_run_id,\n tags=self.tags,\n **kwargs,\n )"}], "type": ["function_empty"], "node": ["langchain_core.runnables.config.ensure_config", "langchain_core.runnables.config.patch_config", "langchain_core.callbacks.manager.handle_event", "langchain_core.callbacks.manager.CallbackManagerForChainRun.on_chain_end"], "language": "Python", "toolfunc_count": 4, "func_count": 4, "pytest_info": {"total_num": 27, "base_passed_num": 0}} {"id": ["langchain_core.libs.core.langchain_core.runnables.config.ensure_config", "langchain_core.libs.core.langchain_core.runnables.config.patch_config", "langchain_core.libs.core.langchain_core.globals.get_llm_cache", "langchain_core.libs.core.langchain_core.language_models.llms.get_prompts"], "project": "langchain_core", "origin_file": ["langchain_core/runnables/config.py", "langchain_core/runnables/config.py", "langchain_core/globals.py", "langchain_core/language_models/llms.py"], "test_list": ["libs/core/tests/unit_tests/runnables/test_fallbacks.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 593, "func_start_lineno": 149, "func_end_lineno": 199, "func_code": "def ensure_config(config: Optional[RunnableConfig] = None) -> RunnableConfig:\n \"\"\"Ensure that a config is a dict with all keys present.\n\n Args:\n config (Optional[RunnableConfig], optional): The config to ensure.\n Defaults to None.\n\n Returns:\n RunnableConfig: The ensured config.\n \"\"\"\n empty = RunnableConfig(\n tags=[],\n metadata={},\n callbacks=None,\n recursion_limit=DEFAULT_RECURSION_LIMIT,\n configurable={},\n )\n if var_config := var_child_runnable_config.get():\n empty.update(\n cast(\n RunnableConfig,\n {\n k: v.copy() if k in COPIABLE_KEYS else v # type: ignore[attr-defined]\n for k, v in var_config.items()\n if v is not None\n },\n )\n )\n if config is not None:\n empty.update(\n cast(\n RunnableConfig,\n {\n k: v.copy() if k in COPIABLE_KEYS else v # type: ignore[attr-defined]\n for k, v in config.items()\n if v is not None and k in CONFIG_KEYS\n },\n )\n )\n if config is not None:\n for k, v in config.items():\n if k not in CONFIG_KEYS and v is not None:\n empty[\"configurable\"][k] = v\n for key, value in empty.get(\"configurable\", {}).items():\n if (\n not key.startswith(\"__\")\n and isinstance(value, (str, int, float, bool))\n and key not in empty[\"metadata\"]\n ):\n empty[\"metadata\"][key] = value\n return empty"}, {"class_start_lineno": 1, "class_end_lineno": 593, "func_start_lineno": 249, "func_end_lineno": 292, "func_code": "def patch_config(\n config: Optional[RunnableConfig],\n *,\n callbacks: Optional[BaseCallbackManager] = None,\n recursion_limit: Optional[int] = None,\n max_concurrency: Optional[int] = None,\n run_name: Optional[str] = None,\n configurable: Optional[dict[str, Any]] = None,\n) -> RunnableConfig:\n \"\"\"Patch a config with new values.\n\n Args:\n config (Optional[RunnableConfig]): The config to patch.\n callbacks (Optional[BaseCallbackManager], optional): The callbacks to set.\n Defaults to None.\n recursion_limit (Optional[int], optional): The recursion limit to set.\n Defaults to None.\n max_concurrency (Optional[int], optional): The max concurrency to set.\n Defaults to None.\n run_name (Optional[str], optional): The run name to set. Defaults to None.\n configurable (Optional[Dict[str, Any]], optional): The configurable to set.\n Defaults to None.\n\n Returns:\n RunnableConfig: The patched config.\n \"\"\"\n config = ensure_config(config)\n if callbacks is not None:\n # If we're replacing callbacks, we need to unset run_name\n # As that should apply only to the same run as the original callbacks\n config[\"callbacks\"] = callbacks\n if \"run_name\" in config:\n del config[\"run_name\"]\n if \"run_id\" in config:\n del config[\"run_id\"]\n if recursion_limit is not None:\n config[\"recursion_limit\"] = recursion_limit\n if max_concurrency is not None:\n config[\"max_concurrency\"] = max_concurrency\n if run_name is not None:\n config[\"run_name\"] = run_name\n if configurable is not None:\n config[\"configurable\"] = {**config.get(\"configurable\", {}), **configurable}\n return config"}, {"class_start_lineno": 1, "class_end_lineno": 222, "func_start_lineno": 186, "func_end_lineno": 222, "func_code": "def get_llm_cache() -> \"BaseCache\":\n \"\"\"Get the value of the `llm_cache` global setting.\n\n Returns:\n The value of the `llm_cache` global setting.\n \"\"\"\n try:\n import langchain # type: ignore[import]\n\n # We're about to run some deprecated code, don't report warnings from it.\n # The user called the correct (non-deprecated) code path and shouldn't get warnings.\n with warnings.catch_warnings():\n warnings.filterwarnings(\n \"ignore\",\n message=(\n \"Importing llm_cache from langchain root module is no longer supported\"\n ),\n )\n # N.B.: This is a workaround for an unfortunate quirk of Python's\n # module-level `__getattr__()` implementation:\n # https://github.com/langchain-ai/langchain/pull/11311#issuecomment-1743780004\n #\n # Remove it once `langchain.llm_cache` is no longer supported, and\n # once all users have migrated to using `set_llm_cache()` here.\n #\n # In the meantime, the `llm_cache` setting returns whichever of\n # its two backing sources is truthy (not `None` and non-empty),\n # or the old value if both are falsy. This accommodates users\n # who haven't migrated to using `set_llm_cache()` yet.\n # Those users are getting deprecation warnings directing them\n # to use `set_llm_cache()` when they import `langchain.llm_cache`.\n old_llm_cache = langchain.llm_cache\n except ImportError:\n old_llm_cache = None\n\n global _llm_cache\n return _llm_cache or old_llm_cache"}, {"class_start_lineno": 1, "class_end_lineno": 1547, "func_start_lineno": 151, "func_end_lineno": 184, "func_code": "def get_prompts(\n params: dict[str, Any],\n prompts: list[str],\n cache: Optional[Union[BaseCache, bool, None]] = None,\n) -> tuple[dict[int, list], str, list[int], list[str]]:\n \"\"\"Get prompts that are already cached.\n\n Args:\n params: Dictionary of parameters.\n prompts: List of prompts.\n cache: Cache object. Default is None.\n\n Returns:\n A tuple of existing prompts, llm_string, missing prompt indexes,\n and missing prompts.\n\n Raises:\n ValueError: If the cache is not set and cache is True.\n \"\"\"\n llm_string = str(sorted(params.items()))\n missing_prompts = []\n missing_prompt_idxs = []\n existing_prompts = {}\n\n llm_cache = _resolve_cache(cache)\n for i, prompt in enumerate(prompts):\n if llm_cache:\n cache_val = llm_cache.lookup(prompt, llm_string)\n if isinstance(cache_val, list):\n existing_prompts[i] = cache_val\n else:\n missing_prompts.append(prompt)\n missing_prompt_idxs.append(i)\n return existing_prompts, llm_string, missing_prompt_idxs, missing_prompts"}], "type": ["function_empty"], "node": ["langchain_core.runnables.config.ensure_config", "langchain_core.runnables.config.patch_config", "langchain_core.globals.get_llm_cache", "langchain_core.language_models.llms.get_prompts"], "language": "Python", "toolfunc_count": 4, "func_count": 4, "pytest_info": {"total_num": 16, "base_passed_num": 2}} {"id": ["langchain_core.libs.core.langchain_core.runnables.graph.is_uuid", "langchain_core.libs.core.langchain_core.runnables.graph.node_data_str", "langchain_core.libs.core.langchain_core.runnables.graph.Graph::add_node", "langchain_core.libs.core.langchain_core.runnables.graph_ascii.AsciiCanvas::point", "langchain_core.libs.core.langchain_core.runnables.graph_ascii.AsciiCanvas::line"], "project": "langchain_core", "origin_file": ["langchain_core/runnables/graph.py", "langchain_core/runnables/graph.py", "langchain_core/runnables/graph.py", "langchain_core/runnables/graph_ascii.py", "langchain_core/runnables/graph_ascii.py"], "test_list": ["libs/core/tests/unit_tests/runnables/test_graph.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 664, "func_start_lineno": 42, "func_end_lineno": 55, "func_code": "def is_uuid(value: str) -> bool:\n \"\"\"Check if a string is a valid UUID.\n\n Args:\n value: The string to check.\n\n Returns:\n True if the string is a valid UUID, False otherwise.\n \"\"\"\n try:\n UUID(value)\n except ValueError:\n return False\n return True"}, {"class_start_lineno": 1, "class_end_lineno": 664, "func_start_lineno": 178, "func_end_lineno": 196, "func_code": "def node_data_str(id: str, data: Union[type[BaseModel], RunnableType]) -> str:\n \"\"\"Convert the data of a node to a string.\n\n Args:\n id: The node id.\n data: The node data.\n\n Returns:\n A string representation of the data.\n \"\"\"\n from langchain_core.runnables.base import Runnable\n\n if not is_uuid(id):\n return id\n elif isinstance(data, Runnable):\n data_str = data.get_name()\n else:\n data_str = data.__name__\n return data_str if not data_str.startswith(\"Runnable\") else data_str[8:]"}, {"class_start_lineno": 256, "class_end_lineno": 636, "func_start_lineno": 313, "func_end_lineno": 339, "func_code": " def add_node(\n self,\n data: Union[type[BaseModel], RunnableType],\n id: Optional[str] = None,\n *,\n metadata: Optional[dict[str, Any]] = None,\n ) -> Node:\n \"\"\"Add a node to the graph and return it.\n\n Args:\n data: The data of the node.\n id: The id of the node. Defaults to None.\n metadata: Optional metadata for the node. Defaults to None.\n\n Returns:\n The node that was added to the graph.\n\n Raises:\n ValueError: If a node with the same id already exists.\n \"\"\"\n if id is not None and id in self.nodes:\n msg = f\"Node with id {id} already exists\"\n raise ValueError(msg)\n id = id or self.next_id()\n node = Node(id=id, data=data, metadata=metadata, name=node_data_str(id, data))\n self.nodes[node.id] = node\n return node"}, {"class_start_lineno": 39, "class_end_lineno": 157, "func_start_lineno": 64, "func_end_lineno": 85, "func_code": " def point(self, x: int, y: int, char: str) -> None:\n \"\"\"Create a point on ASCII canvas.\n\n Args:\n x (int): x coordinate. Should be >= 0 and < number of columns in\n the canvas.\n y (int): y coordinate. Should be >= 0 an < number of lines in the\n canvas.\n char (str): character to place in the specified point on the\n canvas.\n \"\"\"\n if len(char) != 1:\n msg = \"char should be a single character\"\n raise ValueError(msg)\n if x >= self.cols or x < 0:\n msg = \"x should be >= 0 and < number of columns\"\n raise ValueError(msg)\n if y >= self.lines or y < 0:\n msg = \"y should be >= 0 and < number of lines\"\n raise ValueError(msg)\n\n self.canvas[y][x] = char"}, {"class_start_lineno": 39, "class_end_lineno": 157, "func_start_lineno": 87, "func_end_lineno": 117, "func_code": " def line(self, x0: int, y0: int, x1: int, y1: int, char: str) -> None:\n \"\"\"Create a line on ASCII canvas.\n\n Args:\n x0 (int): x coordinate where the line should start.\n y0 (int): y coordinate where the line should start.\n x1 (int): x coordinate where the line should end.\n y1 (int): y coordinate where the line should end.\n char (str): character to draw the line with.\n \"\"\"\n if x0 > x1:\n x1, x0 = x0, x1\n y1, y0 = y0, y1\n\n dx = x1 - x0\n dy = y1 - y0\n\n if dx == 0 and dy == 0:\n self.point(x0, y0, char)\n elif abs(dx) >= abs(dy):\n for x in range(x0, x1 + 1):\n y = y0 if dx == 0 else y0 + int(round((x - x0) * dy / float(dx)))\n self.point(x, y, char)\n elif y0 < y1:\n for y in range(y0, y1 + 1):\n x = x0 if dy == 0 else x0 + int(round((y - y0) * dx / float(dy)))\n self.point(x, y, char)\n else:\n for y in range(y1, y0 + 1):\n x = x0 if dy == 0 else x1 + int(round((y - y1) * dx / float(dy)))\n self.point(x, y, char)"}], "type": ["function_empty", "Development"], "node": ["langchain_core.runnables.graph.is_uuid", "langchain_core.runnables.graph.node_data_str", "langchain_core.runnables.graph.Graph.add_node", "langchain_core.runnables.graph_ascii.AsciiCanvas.point", "langchain_core.runnables.graph_ascii.AsciiCanvas.line"], "language": "Python", "toolfunc_count": 4, "func_count": 5, "pytest_info": {"total_num": 11, "base_passed_num": 3}} {"id": ["langchain_core.libs.core.langchain_core.runnables.config.ensure_config", "langchain_core.libs.core.langchain_core.runnables.config.merge_configs", "langchain_core.libs.core.langchain_core.runnables.config.patch_config", "langchain_core.libs.core.langchain_core.runnables.base.RunnableLambda::invoke"], "project": "langchain_core", "origin_file": ["langchain_core/runnables/config.py", "langchain_core/runnables/config.py", "langchain_core/runnables/config.py", "langchain_core/runnables/base.py", "langchain_core/runnables/base.py"], "test_list": ["libs/core/tests/unit_tests/runnables/test_history.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 593, "func_start_lineno": 149, "func_end_lineno": 199, "func_code": "def ensure_config(config: Optional[RunnableConfig] = None) -> RunnableConfig:\n \"\"\"Ensure that a config is a dict with all keys present.\n\n Args:\n config (Optional[RunnableConfig], optional): The config to ensure.\n Defaults to None.\n\n Returns:\n RunnableConfig: The ensured config.\n \"\"\"\n empty = RunnableConfig(\n tags=[],\n metadata={},\n callbacks=None,\n recursion_limit=DEFAULT_RECURSION_LIMIT,\n configurable={},\n )\n if var_config := var_child_runnable_config.get():\n empty.update(\n cast(\n RunnableConfig,\n {\n k: v.copy() if k in COPIABLE_KEYS else v # type: ignore[attr-defined]\n for k, v in var_config.items()\n if v is not None\n },\n )\n )\n if config is not None:\n empty.update(\n cast(\n RunnableConfig,\n {\n k: v.copy() if k in COPIABLE_KEYS else v # type: ignore[attr-defined]\n for k, v in config.items()\n if v is not None and k in CONFIG_KEYS\n },\n )\n )\n if config is not None:\n for k, v in config.items():\n if k not in CONFIG_KEYS and v is not None:\n empty[\"configurable\"][k] = v\n for key, value in empty.get(\"configurable\", {}).items():\n if (\n not key.startswith(\"__\")\n and isinstance(value, (str, int, float, bool))\n and key not in empty[\"metadata\"]\n ):\n empty[\"metadata\"][key] = value\n return empty"}, {"class_start_lineno": 1, "class_end_lineno": 593, "func_start_lineno": 295, "func_end_lineno": 358, "func_code": "def merge_configs(*configs: Optional[RunnableConfig]) -> RunnableConfig:\n \"\"\"Merge multiple configs into one.\n\n Args:\n *configs (Optional[RunnableConfig]): The configs to merge.\n\n Returns:\n RunnableConfig: The merged config.\n \"\"\"\n base: RunnableConfig = {}\n # Even though the keys aren't literals, this is correct\n # because both dicts are the same type\n for config in (ensure_config(c) for c in configs if c is not None):\n for key in config:\n if key == \"metadata\":\n base[key] = { # type: ignore\n **base.get(key, {}), # type: ignore\n **(config.get(key) or {}), # type: ignore\n }\n elif key == \"tags\":\n base[key] = sorted( # type: ignore\n set(base.get(key, []) + (config.get(key) or [])), # type: ignore\n )\n elif key == \"configurable\":\n base[key] = { # type: ignore\n **base.get(key, {}), # type: ignore\n **(config.get(key) or {}), # type: ignore\n }\n elif key == \"callbacks\":\n base_callbacks = base.get(\"callbacks\")\n these_callbacks = config[\"callbacks\"]\n # callbacks can be either None, list[handler] or manager\n # so merging two callbacks values has 6 cases\n if isinstance(these_callbacks, list):\n if base_callbacks is None:\n base[\"callbacks\"] = these_callbacks.copy()\n elif isinstance(base_callbacks, list):\n base[\"callbacks\"] = base_callbacks + these_callbacks\n else:\n # base_callbacks is a manager\n mngr = base_callbacks.copy()\n for callback in these_callbacks:\n mngr.add_handler(callback, inherit=True)\n base[\"callbacks\"] = mngr\n elif these_callbacks is not None:\n # these_callbacks is a manager\n if base_callbacks is None:\n base[\"callbacks\"] = these_callbacks.copy()\n elif isinstance(base_callbacks, list):\n mngr = these_callbacks.copy()\n for callback in base_callbacks:\n mngr.add_handler(callback, inherit=True)\n base[\"callbacks\"] = mngr\n else:\n # base_callbacks is also a manager\n base[\"callbacks\"] = base_callbacks.merge(these_callbacks)\n elif key == \"recursion_limit\":\n if config[\"recursion_limit\"] != DEFAULT_RECURSION_LIMIT:\n base[\"recursion_limit\"] = config[\"recursion_limit\"]\n elif key in COPIABLE_KEYS and config[key] is not None: # type: ignore[literal-required]\n base[key] = config[key].copy() # type: ignore[literal-required]\n else:\n base[key] = config[key] or base.get(key) # type: ignore\n return base"}, {"class_start_lineno": 1, "class_end_lineno": 593, "func_start_lineno": 249, "func_end_lineno": 292, "func_code": "def patch_config(\n config: Optional[RunnableConfig],\n *,\n callbacks: Optional[BaseCallbackManager] = None,\n recursion_limit: Optional[int] = None,\n max_concurrency: Optional[int] = None,\n run_name: Optional[str] = None,\n configurable: Optional[dict[str, Any]] = None,\n) -> RunnableConfig:\n \"\"\"Patch a config with new values.\n\n Args:\n config (Optional[RunnableConfig]): The config to patch.\n callbacks (Optional[BaseCallbackManager], optional): The callbacks to set.\n Defaults to None.\n recursion_limit (Optional[int], optional): The recursion limit to set.\n Defaults to None.\n max_concurrency (Optional[int], optional): The max concurrency to set.\n Defaults to None.\n run_name (Optional[str], optional): The run name to set. Defaults to None.\n configurable (Optional[Dict[str, Any]], optional): The configurable to set.\n Defaults to None.\n\n Returns:\n RunnableConfig: The patched config.\n \"\"\"\n config = ensure_config(config)\n if callbacks is not None:\n # If we're replacing callbacks, we need to unset run_name\n # As that should apply only to the same run as the original callbacks\n config[\"callbacks\"] = callbacks\n if \"run_name\" in config:\n del config[\"run_name\"]\n if \"run_id\" in config:\n del config[\"run_id\"]\n if recursion_limit is not None:\n config[\"recursion_limit\"] = recursion_limit\n if max_concurrency is not None:\n config[\"max_concurrency\"] = max_concurrency\n if run_name is not None:\n config[\"run_name\"] = run_name\n if configurable is not None:\n config[\"configurable\"] = {**config.get(\"configurable\", {}), **configurable}\n return config"}, {"class_start_lineno": 4230, "class_end_lineno": 4967, "func_start_lineno": 4696, "func_end_lineno": 4699, "func_code": " def _config(\n self, config: Optional[RunnableConfig], callable: Callable[..., Any]\n ) -> RunnableConfig:\n return ensure_config(config)"}, {"class_start_lineno": 4230, "class_end_lineno": 4967, "func_start_lineno": 4701, "func_end_lineno": 4732, "func_code": " def invoke(\n self,\n input: Input,\n config: Optional[RunnableConfig] = None,\n **kwargs: Optional[Any],\n ) -> Output:\n \"\"\"Invoke this Runnable synchronously.\n\n Args:\n input: The input to this Runnable.\n config: The config to use. Defaults to None.\n kwargs: Additional keyword arguments.\n\n Returns:\n The output of this Runnable.\n\n Raises:\n TypeError: If the Runnable is a coroutine function.\n \"\"\"\n if hasattr(self, \"func\"):\n return self._call_with_config(\n self._invoke,\n input,\n self._config(config, self.func),\n **kwargs,\n )\n else:\n msg = (\n \"Cannot invoke a coroutine function synchronously.\"\n \"Use `ainvoke` instead.\"\n )\n raise TypeError(msg)"}], "type": ["function_empty"], "node": ["langchain_core.runnables.config.ensure_config", "langchain_core.runnables.config.merge_configs", "langchain_core.runnables.config.patch_config", "langchain_core.runnables.base.RunnableLambda._config", "langchain_core.runnables.base.RunnableLambda.invoke"], "language": "Python", "toolfunc_count": 4, "func_count": 4, "pytest_info": {"total_num": 23, "base_passed_num": 4}} {"id": ["langchain_core.libs.core.langchain_core.utils.env.get_from_env", "langchain_core.libs.core.langchain_core.utils.env.get_from_dict_or_env"], "project": "langchain_core", "origin_file": ["langchain_core/utils/env.py", "langchain_core/utils/env.py"], "test_list": ["libs/core/tests/unit_tests/utils/test_env.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 81, "func_start_lineno": 54, "func_end_lineno": 81, "func_code": "def get_from_env(key: str, env_key: str, default: Optional[str] = None) -> str:\n \"\"\"Get a value from a dictionary or an environment variable.\n\n Args:\n key: The key to look up in the dictionary.\n env_key: The environment variable to look up if the key is not\n in the dictionary.\n default: The default value to return if the key is not in the dictionary\n or the environment. Defaults to None.\n\n Returns:\n str: The value of the key.\n\n Raises:\n ValueError: If the key is not in the dictionary and no default value is\n provided or if the environment variable is not set.\n \"\"\"\n if env_key in os.environ and os.environ[env_key]:\n return os.environ[env_key]\n elif default is not None:\n return default\n else:\n msg = (\n f\"Did not find {key}, please add an environment variable\"\n f\" `{env_key}` which contains it, or pass\"\n f\" `{key}` as a named parameter.\"\n )\n raise ValueError(msg)"}, {"class_start_lineno": 1, "class_end_lineno": 81, "func_start_lineno": 24, "func_end_lineno": 51, "func_code": "def get_from_dict_or_env(\n data: dict[str, Any],\n key: Union[str, list[str]],\n env_key: str,\n default: Optional[str] = None,\n) -> str:\n \"\"\"Get a value from a dictionary or an environment variable.\n\n Args:\n data: The dictionary to look up the key in.\n key: The key to look up in the dictionary. This can be a list of keys to try\n in order.\n env_key: The environment variable to look up if the key is not\n in the dictionary.\n default: The default value to return if the key is not in the dictionary\n or the environment. Defaults to None.\n \"\"\"\n if isinstance(key, (list, tuple)):\n for k in key:\n if k in data and data[k]:\n return data[k]\n\n if isinstance(key, str) and key in data and data[key]:\n return data[key]\n\n key_for_err = key[0] if isinstance(key, (list, tuple)) else key\n\n return get_from_env(key_for_err, env_key, default=default)"}], "type": ["function_empty"], "node": ["langchain_core.utils.env.get_from_env", "langchain_core.utils.env.get_from_dict_or_env"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 1, "base_passed_num": 0}} {"id": ["langchain_core.libs.core.langchain_core.utils._merge.merge_lists", "langchain_core.libs.core.langchain_core.utils._merge.merge_dicts"], "project": "langchain_core", "origin_file": ["langchain_core/utils/_merge.py", "langchain_core/utils/_merge.py"], "test_list": ["libs/core/tests/unit_tests/utils/test_utils.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 148, "func_start_lineno": 72, "func_end_lineno": 106, "func_code": "def merge_lists(left: Optional[list], *others: Optional[list]) -> Optional[list]:\n \"\"\"Add many lists, handling None.\n\n Args:\n left: The first list to merge.\n others: The other lists to merge.\n\n Returns:\n The merged list.\n \"\"\"\n merged = left.copy() if left is not None else None\n for other in others:\n if other is None:\n continue\n elif merged is None:\n merged = other.copy()\n else:\n for e in other:\n if isinstance(e, dict) and \"index\" in e and isinstance(e[\"index\"], int):\n to_merge = [\n i\n for i, e_left in enumerate(merged)\n if e_left[\"index\"] == e[\"index\"]\n ]\n if to_merge:\n # TODO: Remove this once merge_dict is updated with special\n # handling for 'type'.\n if \"type\" in e:\n e = {k: v for k, v in e.items() if k != \"type\"}\n merged[to_merge[0]] = merge_dicts(merged[to_merge[0]], e)\n else:\n merged.append(e)\n else:\n merged.append(e)\n return merged"}, {"class_start_lineno": 1, "class_end_lineno": 148, "func_start_lineno": 6, "func_end_lineno": 69, "func_code": "def merge_dicts(left: dict[str, Any], *others: dict[str, Any]) -> dict[str, Any]:\n \"\"\"Merge many dicts, handling specific scenarios where a key exists in both\n dictionaries but has a value of None in 'left'. In such cases, the method uses the\n value from 'right' for that key in the merged dictionary.\n\n Args:\n left: The first dictionary to merge.\n others: The other dictionaries to merge.\n\n Returns:\n The merged dictionary.\n\n Raises:\n TypeError: If the key exists in both dictionaries but has a different type.\n TypeError: If the value has an unsupported type.\n\n Example:\n If left = {\"function_call\": {\"arguments\": None}} and\n right = {\"function_call\": {\"arguments\": \"{\\n\"}}\n then, after merging, for the key \"function_call\",\n the value from 'right' is used,\n resulting in merged = {\"function_call\": {\"arguments\": \"{\\n\"}}.\n \"\"\"\n merged = left.copy()\n for right in others:\n for right_k, right_v in right.items():\n if right_k not in merged or right_v is not None and merged[right_k] is None:\n merged[right_k] = right_v\n elif right_v is None:\n continue\n elif type(merged[right_k]) is not type(right_v):\n msg = (\n f'additional_kwargs[\"{right_k}\"] already exists in this message,'\n \" but with a different type.\"\n )\n raise TypeError(msg)\n elif isinstance(merged[right_k], str):\n # TODO: Add below special handling for 'type' key in 0.3 and remove\n # merge_lists 'type' logic.\n #\n # if right_k == \"type\":\n # if merged[right_k] == right_v:\n # continue\n # else:\n # raise ValueError(\n # \"Unable to merge. Two different values seen for special \"\n # f\"key 'type': {merged[right_k]} and {right_v}. 'type' \"\n # \"should either occur once or have the same value across \"\n # \"all dicts.\"\n # )\n merged[right_k] += right_v\n elif isinstance(merged[right_k], dict):\n merged[right_k] = merge_dicts(merged[right_k], right_v)\n elif isinstance(merged[right_k], list):\n merged[right_k] = merge_lists(merged[right_k], right_v)\n elif merged[right_k] == right_v:\n continue\n else:\n msg = (\n f\"Additional kwargs key {right_k} already exists in left dict and \"\n f\"value has unsupported type {type(merged[right_k])}.\"\n )\n raise TypeError(msg)\n return merged"}], "type": ["function_empty"], "node": ["langchain_core.utils._merge.merge_lists", "langchain_core.utils._merge.merge_dicts"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 47, "base_passed_num": 26}} {"id": ["finam.src.finam.data.grid_spec.NoGrid::compatible_with", "finam.src.finam.data.tools.mask.mask_specified", "finam.src.finam.data.tools.mask.masks_compatible", "finam.src.finam.data.tools.info.Info::accepts"], "project": "finam", "origin_file": ["finam/data/grid_spec.py", "finam/data/tools/mask.py", "finam/data/tools/info.py", "finam/data/tools/mask.py", "finam/data/tools/info.py"], "test_list": ["tests/adapters/test_probe.py", "tests/adapters/test_time.py", "tests/components/test_debug.py", "tests/core/test_pull_based_component.py"], "prob_info": [{"class_start_lineno": 30, "class_end_lineno": 90, "func_start_lineno": 71, "func_end_lineno": 87, "func_code": " def compatible_with(self, other, check_location=True):\n \"\"\"\n Check for compatibility with other Grid.\n\n Parameters\n ----------\n other : instance of Grid\n Other grid to compatibility with.\n check_location : bool, optional\n Whether to check location for equality, by default True\n\n Returns\n -------\n bool\n compatibility\n \"\"\"\n return isinstance(other, NoGrid) and self.data_shape == other.data_shape"}, {"class_start_lineno": 1, "class_end_lineno": 378, "func_start_lineno": 364, "func_end_lineno": 378, "func_code": "def mask_specified(mask):\n \"\"\"\n Determine whether given mask selection indicates a masked array.\n\n Parameters\n ----------\n mask : :any:`Mask` value or valid boolean mask for :any:`MaskedArray`\n mask to check\n\n Returns\n -------\n bool\n False if mask is Mask.FLEX or Mask.NONE, True otherwise\n \"\"\"\n return not any(mask is val for val in list(Mask))"}, {"class_start_lineno": 22, "class_end_lineno": 248, "func_start_lineno": 87, "func_end_lineno": 89, "func_code": " def mask(self):\n \"\"\"Mask or ndarray: data mask.\"\"\"\n return self._mask"}, {"class_start_lineno": 1, "class_end_lineno": 378, "func_start_lineno": 243, "func_end_lineno": 285, "func_code": "def masks_compatible(\n this, incoming, incoming_donwstream, this_grid=None, incoming_grid=None\n):\n \"\"\"\n Check if an incoming mask is compatible with a given mask.\n\n Parameters\n ----------\n this : :any:`Mask` value or valid boolean mask for :any:`MaskedArray` or None\n mask specification to check against\n incoming : :any:`Mask` value or valid boolean mask for :any:`MaskedArray` or None\n incoming mask to check for compatibility\n incoming_donwstream : bool\n Whether the incoming mask is from downstream data\n this_grid : Grid or NoGrid or None, optional\n grid for first mask (to check shape and value equality)\n incoming_grid : Grid or NoGrid or None, optional\n grid for second mask (to check shape and value equality)\n\n Returns\n -------\n bool\n mask compatibility\n \"\"\"\n if incoming_donwstream:\n upstream, downstream = this, incoming\n up_grid, down_grid = this_grid, incoming_grid\n else:\n upstream, downstream = incoming, this\n up_grid, down_grid = incoming_grid, this_grid\n # None is incompatible\n if upstream is None:\n return False\n # Mask.FLEX accepts anything, Mask.NONE only Mask.NONE\n if not mask_specified(downstream):\n if not mask_specified(upstream):\n return downstream == Mask.FLEX or upstream == Mask.NONE\n return downstream == Mask.FLEX\n # if mask is specified, upstream mask must also be specified\n if not mask_specified(upstream):\n return False\n # if both mask given, compare them\n return masks_equal(downstream, upstream, down_grid, up_grid)"}, {"class_start_lineno": 22, "class_end_lineno": 248, "func_start_lineno": 157, "func_end_lineno": 201, "func_code": " def accepts(self, incoming, fail_info, incoming_donwstream=False):\n \"\"\"\n Tests whether this info can accept/is compatible with an incoming info.\n\n Tested attributes are: \"grid\", \"mask\" and \"units\"\n\n Parameters\n ----------\n incoming : Info\n Incoming/source info to check. This is the info from upstream.\n fail_info : dict\n Dictionary that will be filled with failed properties; name: (source, target).\n incoming_donwstream : bool, optional\n Whether the incoming info is from downstream data. Default: False\n\n Returns\n -------\n bool\n Whether the incoming info is accepted\n \"\"\"\n if not isinstance(incoming, Info):\n fail_info[\"type\"] = (incoming.__class__, self.__class__)\n return False\n\n success = True\n if self.grid is not None and not self.grid.compatible_with(incoming.grid):\n if not (incoming_donwstream and incoming.grid is None):\n fail_info[\"grid\"] = (incoming.grid, self.grid)\n success = False\n\n if self.mask is not None and not masks_compatible(\n self.mask, incoming.mask, incoming_donwstream, self.grid, incoming.grid\n ):\n if not (incoming_donwstream and incoming.mask is None):\n fail_info[\"mask\"] = (incoming.mask, self.mask)\n success = False\n\n u1_none = (u1 := self.units) is None\n u2_none = (u2 := incoming.units) is None\n if not u1_none and (u2_none or not compatible_units(u1, u2)):\n if not (incoming_donwstream and u2_none):\n fail_info[\"units\"] = (u2, u1)\n success = False\n\n return success"}], "type": ["function_empty"], "node": ["finam.data.grid_spec.NoGrid.compatible_with", "finam.data.tools.mask.mask_specified", "finam.data.tools.info.Info.mask", "finam.data.tools.mask.masks_compatible", "finam.data.tools.info.Info.accepts"], "language": "Python", "toolfunc_count": 4, "func_count": 4, "pytest_info": {"total_num": 15, "base_passed_num": 2}} {"id": ["finam.src.finam.data.tools.mask.mask_specified", "finam.src.finam.data.tools.mask.from_compressed", "finam.src.finam.data.tools.mask.masks_compatible", "finam.src.finam.data.tools.info.Info::accepts"], "project": "finam", "origin_file": ["finam/data/tools/mask.py", "finam/data/tools/mask.py", "finam/data/tools/info.py", "finam/data/tools/mask.py", "finam/data/tools/info.py"], "test_list": ["tests/adapters/test_regrid_mask.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 378, "func_start_lineno": 364, "func_end_lineno": 378, "func_code": "def mask_specified(mask):\n \"\"\"\n Determine whether given mask selection indicates a masked array.\n\n Parameters\n ----------\n mask : :any:`Mask` value or valid boolean mask for :any:`MaskedArray`\n mask to check\n\n Returns\n -------\n bool\n False if mask is Mask.FLEX or Mask.NONE, True otherwise\n \"\"\"\n return not any(mask is val for val in list(Mask))"}, {"class_start_lineno": 1, "class_end_lineno": 378, "func_start_lineno": 151, "func_end_lineno": 205, "func_code": "def from_compressed(xdata, shape, order=\"C\", mask=None, **kwargs):\n \"\"\"\n Fill a (masked) array following a given mask or shape with the provided data.\n\n This will only create a masked array if kwargs are given (especially a mask).\n Otherwise this is simply reshaping the given data.\n Filling is performed in the given array order.\n\n Parameters\n ----------\n data : :class:`pint.Quantity` or :class:`numpy.ndarray` or :class:`numpy.ma.MaskedArray`\n The reference object input.\n shape : str\n shape argument for :any:`numpy.reshape`\n order : str\n order argument for :any:`numpy.reshape`\n mask : :any:`Mask` value or valid boolean mask for :any:`MaskedArray`\n mask to use\n **kwargs\n keyword arguments forwarded to :any:`numpy.ma.array`\n\n Returns\n -------\n :class:`pint.Quantity` or :class:`numpy.ndarray` or :class:`numpy.ma.MaskedArray`\n New object with the desired shape and same type as input.\n Units will be taken from the input if present.\n Will only be a masked array if kwargs are given.\n\n See also\n --------\n to_compressed:\n Inverse operation.\n :any:`numpy.ma.array`:\n Routine consuming kwargs to create a masked array.\n :any:`numpy.reshape`:\n Equivalent routine if no mask is provided.\n\n Notes\n -----\n If both `mask` and `shape` are given, they need to match in size.\n \"\"\"\n if mask is None or mask is np.ma.nomask or not mask_specified(mask):\n if kwargs and mask is Mask.NONE:\n msg = \"from_compressed: Can't create masked array with mask=Mask.NONE\"\n raise FinamDataError(msg)\n data = np.reshape(xdata, shape, order=order)\n return to_masked(data, **kwargs) if kwargs or mask is np.ma.nomask else data\n if is_quantified(xdata):\n # pylint: disable-next=unexpected-keyword-arg\n data = quantify(np.empty_like(xdata, shape=np.prod(shape)), xdata.units)\n else:\n # pylint: disable-next=unexpected-keyword-arg\n data = np.empty_like(xdata, shape=np.prod(shape))\n data[np.logical_not(np.ravel(mask, order=order))] = xdata\n return to_masked(np.reshape(data, shape, order=order), mask=mask, **kwargs)"}, {"class_start_lineno": 22, "class_end_lineno": 248, "func_start_lineno": 87, "func_end_lineno": 89, "func_code": " def mask(self):\n \"\"\"Mask or ndarray: data mask.\"\"\"\n return self._mask"}, {"class_start_lineno": 1, "class_end_lineno": 378, "func_start_lineno": 243, "func_end_lineno": 285, "func_code": "def masks_compatible(\n this, incoming, incoming_donwstream, this_grid=None, incoming_grid=None\n):\n \"\"\"\n Check if an incoming mask is compatible with a given mask.\n\n Parameters\n ----------\n this : :any:`Mask` value or valid boolean mask for :any:`MaskedArray` or None\n mask specification to check against\n incoming : :any:`Mask` value or valid boolean mask for :any:`MaskedArray` or None\n incoming mask to check for compatibility\n incoming_donwstream : bool\n Whether the incoming mask is from downstream data\n this_grid : Grid or NoGrid or None, optional\n grid for first mask (to check shape and value equality)\n incoming_grid : Grid or NoGrid or None, optional\n grid for second mask (to check shape and value equality)\n\n Returns\n -------\n bool\n mask compatibility\n \"\"\"\n if incoming_donwstream:\n upstream, downstream = this, incoming\n up_grid, down_grid = this_grid, incoming_grid\n else:\n upstream, downstream = incoming, this\n up_grid, down_grid = incoming_grid, this_grid\n # None is incompatible\n if upstream is None:\n return False\n # Mask.FLEX accepts anything, Mask.NONE only Mask.NONE\n if not mask_specified(downstream):\n if not mask_specified(upstream):\n return downstream == Mask.FLEX or upstream == Mask.NONE\n return downstream == Mask.FLEX\n # if mask is specified, upstream mask must also be specified\n if not mask_specified(upstream):\n return False\n # if both mask given, compare them\n return masks_equal(downstream, upstream, down_grid, up_grid)"}, {"class_start_lineno": 22, "class_end_lineno": 248, "func_start_lineno": 157, "func_end_lineno": 201, "func_code": " def accepts(self, incoming, fail_info, incoming_donwstream=False):\n \"\"\"\n Tests whether this info can accept/is compatible with an incoming info.\n\n Tested attributes are: \"grid\", \"mask\" and \"units\"\n\n Parameters\n ----------\n incoming : Info\n Incoming/source info to check. This is the info from upstream.\n fail_info : dict\n Dictionary that will be filled with failed properties; name: (source, target).\n incoming_donwstream : bool, optional\n Whether the incoming info is from downstream data. Default: False\n\n Returns\n -------\n bool\n Whether the incoming info is accepted\n \"\"\"\n if not isinstance(incoming, Info):\n fail_info[\"type\"] = (incoming.__class__, self.__class__)\n return False\n\n success = True\n if self.grid is not None and not self.grid.compatible_with(incoming.grid):\n if not (incoming_donwstream and incoming.grid is None):\n fail_info[\"grid\"] = (incoming.grid, self.grid)\n success = False\n\n if self.mask is not None and not masks_compatible(\n self.mask, incoming.mask, incoming_donwstream, self.grid, incoming.grid\n ):\n if not (incoming_donwstream and incoming.mask is None):\n fail_info[\"mask\"] = (incoming.mask, self.mask)\n success = False\n\n u1_none = (u1 := self.units) is None\n u2_none = (u2 := incoming.units) is None\n if not u1_none and (u2_none or not compatible_units(u1, u2)):\n if not (incoming_donwstream and u2_none):\n fail_info[\"units\"] = (u2, u1)\n success = False\n\n return success"}], "type": ["function_empty"], "node": ["finam.data.tools.mask.mask_specified", "finam.data.tools.mask.from_compressed", "finam.data.tools.info.Info.mask", "finam.data.tools.mask.masks_compatible", "finam.data.tools.info.Info.accepts"], "language": "Python", "toolfunc_count": 4, "func_count": 4, "pytest_info": {"total_num": 6, "base_passed_num": 0}} {"id": ["finam.src.finam.data.tools.mask.mask_specified", "finam.src.finam.data.tools.mask.masks_compatible", "finam.src.finam.data.tools.info.Info::accepts"], "project": "finam", "origin_file": ["finam/data/tools/mask.py", "finam/data/tools/info.py", "finam/data/tools/mask.py", "finam/data/tools/info.py"], "test_list": ["tests/adapters/test_stats.py", "tests/components/test_simplex_noise.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 378, "func_start_lineno": 364, "func_end_lineno": 378, "func_code": "def mask_specified(mask):\n \"\"\"\n Determine whether given mask selection indicates a masked array.\n\n Parameters\n ----------\n mask : :any:`Mask` value or valid boolean mask for :any:`MaskedArray`\n mask to check\n\n Returns\n -------\n bool\n False if mask is Mask.FLEX or Mask.NONE, True otherwise\n \"\"\"\n return not any(mask is val for val in list(Mask))"}, {"class_start_lineno": 22, "class_end_lineno": 248, "func_start_lineno": 87, "func_end_lineno": 89, "func_code": " def mask(self):\n \"\"\"Mask or ndarray: data mask.\"\"\"\n return self._mask"}, {"class_start_lineno": 1, "class_end_lineno": 378, "func_start_lineno": 243, "func_end_lineno": 285, "func_code": "def masks_compatible(\n this, incoming, incoming_donwstream, this_grid=None, incoming_grid=None\n):\n \"\"\"\n Check if an incoming mask is compatible with a given mask.\n\n Parameters\n ----------\n this : :any:`Mask` value or valid boolean mask for :any:`MaskedArray` or None\n mask specification to check against\n incoming : :any:`Mask` value or valid boolean mask for :any:`MaskedArray` or None\n incoming mask to check for compatibility\n incoming_donwstream : bool\n Whether the incoming mask is from downstream data\n this_grid : Grid or NoGrid or None, optional\n grid for first mask (to check shape and value equality)\n incoming_grid : Grid or NoGrid or None, optional\n grid for second mask (to check shape and value equality)\n\n Returns\n -------\n bool\n mask compatibility\n \"\"\"\n if incoming_donwstream:\n upstream, downstream = this, incoming\n up_grid, down_grid = this_grid, incoming_grid\n else:\n upstream, downstream = incoming, this\n up_grid, down_grid = incoming_grid, this_grid\n # None is incompatible\n if upstream is None:\n return False\n # Mask.FLEX accepts anything, Mask.NONE only Mask.NONE\n if not mask_specified(downstream):\n if not mask_specified(upstream):\n return downstream == Mask.FLEX or upstream == Mask.NONE\n return downstream == Mask.FLEX\n # if mask is specified, upstream mask must also be specified\n if not mask_specified(upstream):\n return False\n # if both mask given, compare them\n return masks_equal(downstream, upstream, down_grid, up_grid)"}, {"class_start_lineno": 22, "class_end_lineno": 248, "func_start_lineno": 157, "func_end_lineno": 201, "func_code": " def accepts(self, incoming, fail_info, incoming_donwstream=False):\n \"\"\"\n Tests whether this info can accept/is compatible with an incoming info.\n\n Tested attributes are: \"grid\", \"mask\" and \"units\"\n\n Parameters\n ----------\n incoming : Info\n Incoming/source info to check. This is the info from upstream.\n fail_info : dict\n Dictionary that will be filled with failed properties; name: (source, target).\n incoming_donwstream : bool, optional\n Whether the incoming info is from downstream data. Default: False\n\n Returns\n -------\n bool\n Whether the incoming info is accepted\n \"\"\"\n if not isinstance(incoming, Info):\n fail_info[\"type\"] = (incoming.__class__, self.__class__)\n return False\n\n success = True\n if self.grid is not None and not self.grid.compatible_with(incoming.grid):\n if not (incoming_donwstream and incoming.grid is None):\n fail_info[\"grid\"] = (incoming.grid, self.grid)\n success = False\n\n if self.mask is not None and not masks_compatible(\n self.mask, incoming.mask, incoming_donwstream, self.grid, incoming.grid\n ):\n if not (incoming_donwstream and incoming.mask is None):\n fail_info[\"mask\"] = (incoming.mask, self.mask)\n success = False\n\n u1_none = (u1 := self.units) is None\n u2_none = (u2 := incoming.units) is None\n if not u1_none and (u2_none or not compatible_units(u1, u2)):\n if not (incoming_donwstream and u2_none):\n fail_info[\"units\"] = (u2, u1)\n success = False\n\n return success"}], "type": ["function_empty"], "node": ["finam.data.tools.mask.mask_specified", "finam.data.tools.info.Info.mask", "finam.data.tools.mask.masks_compatible", "finam.data.tools.info.Info.accepts"], "language": "Python", "toolfunc_count": 3, "func_count": 3, "pytest_info": {"total_num": 3, "base_passed_num": 0}} {"id": ["finam.src.finam.sdk.output.Output::push_info", "finam.src.finam.sdk.component.IOList::add", "finam.src.finam.data.grid_spec.NoGrid::compatible_with", "finam.src.finam.data.tools.mask.mask_specified", "finam.src.finam.data.tools.info.Info::accepts"], "project": "finam", "origin_file": ["finam/sdk/output.py", "finam/sdk/output.py", "finam/sdk/component.py", "finam/data/grid_spec.py", "finam/data/tools/mask.py", "finam/data/tools/info.py", "finam/data/tools/info.py"], "test_list": ["tests/adapters/test_time_integration.py", "tests/components/test_noise.py", "tests/core/test_propagate_info.py", "tests/core/test_schedule.py"], "prob_info": [{"class_start_lineno": 25, "class_end_lineno": 461, "func_start_lineno": 204, "func_end_lineno": 216, "func_code": " def push_info(self, info):\n \"\"\"Push data info into the output.\n\n Parameters\n ----------\n info : :class:`.Info`\n Delivered data info\n \"\"\"\n self.logger.trace(\"push info\")\n if not isinstance(info, Info):\n with ErrorLogger(self.logger):\n raise FinamMetaDataError(\"Metadata must be of type Info\")\n self._output_info = info"}, {"class_start_lineno": 25, "class_end_lineno": 461, "func_start_lineno": 28, "func_end_lineno": 53, "func_code": " def __init__(self, name=None, info=None, static=False, **info_kwargs):\n Loggable.__init__(self)\n self._targets = []\n self.data = []\n self._output_info = None\n self.base_logger_name = None\n if name is None:\n raise ValueError(\"Output: needs a name.\")\n self._name = name\n self._static = static\n\n if info_kwargs:\n if info is not None:\n raise ValueError(\"Output: can't use **kwargs in combination with info\")\n info = Info(**info_kwargs)\n if info is not None:\n self.push_info(info)\n\n self._connected_inputs = {}\n self._out_infos_exchanged = 0\n\n self._time = None\n self._mem_limit = None\n self._mem_location = None\n self._total_mem = 0\n self._mem_counter = 0"}, {"class_start_lineno": 572, "class_end_lineno": 711, "func_start_lineno": 602, "func_end_lineno": 635, "func_code": " def add(self, io=None, *, name=None, info=None, static=False, **info_kwargs):\n \"\"\"\n Add a new IO object either directly ob by attributes.\n\n Parameters\n ----------\n io : :class:`.IInput` or :class:`.IOutput`, optional\n IO object to add, by default None\n name : str, optional\n Name of the new IO object to add, by default None\n info : :class:`.Info`, optional\n Info of the new IO object to add, by default None\n static : bool, optional\n Whether the new IO object in static, by default False\n **info_kwargs\n Optional keyword arguments to instantiate an Info object\n\n Raises\n ------\n ValueError\n If io is not of the correct type.\n \"\"\"\n if self.frozen:\n raise ValueError(\"IO.add: list is frozen.\")\n io = (\n self.cls(name=name, info=info, static=static, **info_kwargs)\n if io is None\n else io\n )\n if not isinstance(io, self.icls):\n raise ValueError(f\"IO.add: {self.name} is not of type {self.iname}\")\n if io.name in self._dict:\n raise ValueError(f\"IO.add: {self.name} '{io.name}' already exists.\")\n self._dict[io.name] = io"}, {"class_start_lineno": 30, "class_end_lineno": 90, "func_start_lineno": 71, "func_end_lineno": 87, "func_code": " def compatible_with(self, other, check_location=True):\n \"\"\"\n Check for compatibility with other Grid.\n\n Parameters\n ----------\n other : instance of Grid\n Other grid to compatibility with.\n check_location : bool, optional\n Whether to check location for equality, by default True\n\n Returns\n -------\n bool\n compatibility\n \"\"\"\n return isinstance(other, NoGrid) and self.data_shape == other.data_shape"}, {"class_start_lineno": 1, "class_end_lineno": 378, "func_start_lineno": 364, "func_end_lineno": 378, "func_code": "def mask_specified(mask):\n \"\"\"\n Determine whether given mask selection indicates a masked array.\n\n Parameters\n ----------\n mask : :any:`Mask` value or valid boolean mask for :any:`MaskedArray`\n mask to check\n\n Returns\n -------\n bool\n False if mask is Mask.FLEX or Mask.NONE, True otherwise\n \"\"\"\n return not any(mask is val for val in list(Mask))"}, {"class_start_lineno": 22, "class_end_lineno": 248, "func_start_lineno": 87, "func_end_lineno": 89, "func_code": " def mask(self):\n \"\"\"Mask or ndarray: data mask.\"\"\"\n return self._mask"}, {"class_start_lineno": 22, "class_end_lineno": 248, "func_start_lineno": 157, "func_end_lineno": 201, "func_code": " def accepts(self, incoming, fail_info, incoming_donwstream=False):\n \"\"\"\n Tests whether this info can accept/is compatible with an incoming info.\n\n Tested attributes are: \"grid\", \"mask\" and \"units\"\n\n Parameters\n ----------\n incoming : Info\n Incoming/source info to check. This is the info from upstream.\n fail_info : dict\n Dictionary that will be filled with failed properties; name: (source, target).\n incoming_donwstream : bool, optional\n Whether the incoming info is from downstream data. Default: False\n\n Returns\n -------\n bool\n Whether the incoming info is accepted\n \"\"\"\n if not isinstance(incoming, Info):\n fail_info[\"type\"] = (incoming.__class__, self.__class__)\n return False\n\n success = True\n if self.grid is not None and not self.grid.compatible_with(incoming.grid):\n if not (incoming_donwstream and incoming.grid is None):\n fail_info[\"grid\"] = (incoming.grid, self.grid)\n success = False\n\n if self.mask is not None and not masks_compatible(\n self.mask, incoming.mask, incoming_donwstream, self.grid, incoming.grid\n ):\n if not (incoming_donwstream and incoming.mask is None):\n fail_info[\"mask\"] = (incoming.mask, self.mask)\n success = False\n\n u1_none = (u1 := self.units) is None\n u2_none = (u2 := incoming.units) is None\n if not u1_none and (u2_none or not compatible_units(u1, u2)):\n if not (incoming_donwstream and u2_none):\n fail_info[\"units\"] = (u2, u1)\n success = False\n\n return success"}], "type": ["function_empty"], "node": ["finam.sdk.output.Output.push_info", "finam.sdk.output.Output.__init__", "finam.sdk.component.IOList.add", "finam.data.grid_spec.NoGrid.compatible_with", "finam.data.tools.mask.mask_specified", "finam.data.tools.info.Info.mask", "finam.data.tools.info.Info.accepts"], "language": "Python", "toolfunc_count": 5, "func_count": 5, "pytest_info": {"total_num": 50, "base_passed_num": 7}} {"id": ["finam.src.finam.sdk.component.IOList::add", "finam.src.finam.components.callback.CallbackComponent::_initialize", "finam.src.finam.sdk.output.Output::push_info", "finam.src.finam.data.grid_spec.NoGrid::compatible_with", "finam.src.finam.data.tools.info.Info::accepts"], "project": "finam", "origin_file": ["finam/sdk/component.py", "finam/components/callback.py", "finam/sdk/output.py", "finam/sdk/output.py", "finam/data/grid_spec.py", "finam/data/tools/info.py"], "test_list": ["tests/components/test_callback.py"], "prob_info": [{"class_start_lineno": 572, "class_end_lineno": 711, "func_start_lineno": 602, "func_end_lineno": 635, "func_code": " def add(self, io=None, *, name=None, info=None, static=False, **info_kwargs):\n \"\"\"\n Add a new IO object either directly ob by attributes.\n\n Parameters\n ----------\n io : :class:`.IInput` or :class:`.IOutput`, optional\n IO object to add, by default None\n name : str, optional\n Name of the new IO object to add, by default None\n info : :class:`.Info`, optional\n Info of the new IO object to add, by default None\n static : bool, optional\n Whether the new IO object in static, by default False\n **info_kwargs\n Optional keyword arguments to instantiate an Info object\n\n Raises\n ------\n ValueError\n If io is not of the correct type.\n \"\"\"\n if self.frozen:\n raise ValueError(\"IO.add: list is frozen.\")\n io = (\n self.cls(name=name, info=info, static=static, **info_kwargs)\n if io is None\n else io\n )\n if not isinstance(io, self.icls):\n raise ValueError(f\"IO.add: {self.name} is not of type {self.iname}\")\n if io.name in self._dict:\n raise ValueError(f\"IO.add: {self.name} '{io.name}' already exists.\")\n self._dict[io.name] = io"}, {"class_start_lineno": 12, "class_end_lineno": 129, "func_start_lineno": 90, "func_end_lineno": 101, "func_code": " def _initialize(self):\n for name, info in self._input_infos.items():\n info.time = self.time\n self.inputs.add(name=name, info=info)\n\n for name, info in self._output_infos.items():\n info.time = self.time\n self.outputs.add(name=name, info=info)\n\n pull_data = list(self._input_infos) if self._initial_pull else {}\n\n self.create_connector(pull_data=pull_data)"}, {"class_start_lineno": 25, "class_end_lineno": 461, "func_start_lineno": 204, "func_end_lineno": 216, "func_code": " def push_info(self, info):\n \"\"\"Push data info into the output.\n\n Parameters\n ----------\n info : :class:`.Info`\n Delivered data info\n \"\"\"\n self.logger.trace(\"push info\")\n if not isinstance(info, Info):\n with ErrorLogger(self.logger):\n raise FinamMetaDataError(\"Metadata must be of type Info\")\n self._output_info = info"}, {"class_start_lineno": 25, "class_end_lineno": 461, "func_start_lineno": 28, "func_end_lineno": 53, "func_code": " def __init__(self, name=None, info=None, static=False, **info_kwargs):\n Loggable.__init__(self)\n self._targets = []\n self.data = []\n self._output_info = None\n self.base_logger_name = None\n if name is None:\n raise ValueError(\"Output: needs a name.\")\n self._name = name\n self._static = static\n\n if info_kwargs:\n if info is not None:\n raise ValueError(\"Output: can't use **kwargs in combination with info\")\n info = Info(**info_kwargs)\n if info is not None:\n self.push_info(info)\n\n self._connected_inputs = {}\n self._out_infos_exchanged = 0\n\n self._time = None\n self._mem_limit = None\n self._mem_location = None\n self._total_mem = 0\n self._mem_counter = 0"}, {"class_start_lineno": 30, "class_end_lineno": 90, "func_start_lineno": 71, "func_end_lineno": 87, "func_code": " def compatible_with(self, other, check_location=True):\n \"\"\"\n Check for compatibility with other Grid.\n\n Parameters\n ----------\n other : instance of Grid\n Other grid to compatibility with.\n check_location : bool, optional\n Whether to check location for equality, by default True\n\n Returns\n -------\n bool\n compatibility\n \"\"\"\n return isinstance(other, NoGrid) and self.data_shape == other.data_shape"}, {"class_start_lineno": 22, "class_end_lineno": 248, "func_start_lineno": 157, "func_end_lineno": 201, "func_code": " def accepts(self, incoming, fail_info, incoming_donwstream=False):\n \"\"\"\n Tests whether this info can accept/is compatible with an incoming info.\n\n Tested attributes are: \"grid\", \"mask\" and \"units\"\n\n Parameters\n ----------\n incoming : Info\n Incoming/source info to check. This is the info from upstream.\n fail_info : dict\n Dictionary that will be filled with failed properties; name: (source, target).\n incoming_donwstream : bool, optional\n Whether the incoming info is from downstream data. Default: False\n\n Returns\n -------\n bool\n Whether the incoming info is accepted\n \"\"\"\n if not isinstance(incoming, Info):\n fail_info[\"type\"] = (incoming.__class__, self.__class__)\n return False\n\n success = True\n if self.grid is not None and not self.grid.compatible_with(incoming.grid):\n if not (incoming_donwstream and incoming.grid is None):\n fail_info[\"grid\"] = (incoming.grid, self.grid)\n success = False\n\n if self.mask is not None and not masks_compatible(\n self.mask, incoming.mask, incoming_donwstream, self.grid, incoming.grid\n ):\n if not (incoming_donwstream and incoming.mask is None):\n fail_info[\"mask\"] = (incoming.mask, self.mask)\n success = False\n\n u1_none = (u1 := self.units) is None\n u2_none = (u2 := incoming.units) is None\n if not u1_none and (u2_none or not compatible_units(u1, u2)):\n if not (incoming_donwstream and u2_none):\n fail_info[\"units\"] = (u2, u1)\n success = False\n\n return success"}], "type": ["function_empty", "Development"], "node": ["finam.sdk.component.IOList.add", "finam.components.callback.CallbackComponent._initialize", "finam.sdk.output.Output.push_info", "finam.sdk.output.Output.__init__", "finam.data.grid_spec.NoGrid.compatible_with", "finam.data.tools.info.Info.accepts"], "language": "Python", "toolfunc_count": 4, "func_count": 5, "pytest_info": {"total_num": 1, "base_passed_num": 0}} {"id": ["finam.src.finam.sdk.output.Output::push_info", "finam.src.finam.sdk.component.IOList::add", "finam.src.finam.data.tools.mask.mask_specified", "finam.src.finam.data.tools.mask.masks_compatible", "finam.src.finam.data.tools.info.Info::accepts"], "project": "finam", "origin_file": ["finam/sdk/output.py", "finam/sdk/output.py", "finam/sdk/component.py", "finam/data/tools/mask.py", "finam/data/tools/info.py", "finam/data/tools/mask.py", "finam/data/tools/info.py"], "test_list": ["tests/components/test_control.py", "tests/components/test_parametric.py", "tests/core/test_units.py"], "prob_info": [{"class_start_lineno": 25, "class_end_lineno": 461, "func_start_lineno": 204, "func_end_lineno": 216, "func_code": " def push_info(self, info):\n \"\"\"Push data info into the output.\n\n Parameters\n ----------\n info : :class:`.Info`\n Delivered data info\n \"\"\"\n self.logger.trace(\"push info\")\n if not isinstance(info, Info):\n with ErrorLogger(self.logger):\n raise FinamMetaDataError(\"Metadata must be of type Info\")\n self._output_info = info"}, {"class_start_lineno": 25, "class_end_lineno": 461, "func_start_lineno": 28, "func_end_lineno": 53, "func_code": " def __init__(self, name=None, info=None, static=False, **info_kwargs):\n Loggable.__init__(self)\n self._targets = []\n self.data = []\n self._output_info = None\n self.base_logger_name = None\n if name is None:\n raise ValueError(\"Output: needs a name.\")\n self._name = name\n self._static = static\n\n if info_kwargs:\n if info is not None:\n raise ValueError(\"Output: can't use **kwargs in combination with info\")\n info = Info(**info_kwargs)\n if info is not None:\n self.push_info(info)\n\n self._connected_inputs = {}\n self._out_infos_exchanged = 0\n\n self._time = None\n self._mem_limit = None\n self._mem_location = None\n self._total_mem = 0\n self._mem_counter = 0"}, {"class_start_lineno": 572, "class_end_lineno": 711, "func_start_lineno": 602, "func_end_lineno": 635, "func_code": " def add(self, io=None, *, name=None, info=None, static=False, **info_kwargs):\n \"\"\"\n Add a new IO object either directly ob by attributes.\n\n Parameters\n ----------\n io : :class:`.IInput` or :class:`.IOutput`, optional\n IO object to add, by default None\n name : str, optional\n Name of the new IO object to add, by default None\n info : :class:`.Info`, optional\n Info of the new IO object to add, by default None\n static : bool, optional\n Whether the new IO object in static, by default False\n **info_kwargs\n Optional keyword arguments to instantiate an Info object\n\n Raises\n ------\n ValueError\n If io is not of the correct type.\n \"\"\"\n if self.frozen:\n raise ValueError(\"IO.add: list is frozen.\")\n io = (\n self.cls(name=name, info=info, static=static, **info_kwargs)\n if io is None\n else io\n )\n if not isinstance(io, self.icls):\n raise ValueError(f\"IO.add: {self.name} is not of type {self.iname}\")\n if io.name in self._dict:\n raise ValueError(f\"IO.add: {self.name} '{io.name}' already exists.\")\n self._dict[io.name] = io"}, {"class_start_lineno": 1, "class_end_lineno": 378, "func_start_lineno": 364, "func_end_lineno": 378, "func_code": "def mask_specified(mask):\n \"\"\"\n Determine whether given mask selection indicates a masked array.\n\n Parameters\n ----------\n mask : :any:`Mask` value or valid boolean mask for :any:`MaskedArray`\n mask to check\n\n Returns\n -------\n bool\n False if mask is Mask.FLEX or Mask.NONE, True otherwise\n \"\"\"\n return not any(mask is val for val in list(Mask))"}, {"class_start_lineno": 22, "class_end_lineno": 248, "func_start_lineno": 87, "func_end_lineno": 89, "func_code": " def mask(self):\n \"\"\"Mask or ndarray: data mask.\"\"\"\n return self._mask"}, {"class_start_lineno": 1, "class_end_lineno": 378, "func_start_lineno": 243, "func_end_lineno": 285, "func_code": "def masks_compatible(\n this, incoming, incoming_donwstream, this_grid=None, incoming_grid=None\n):\n \"\"\"\n Check if an incoming mask is compatible with a given mask.\n\n Parameters\n ----------\n this : :any:`Mask` value or valid boolean mask for :any:`MaskedArray` or None\n mask specification to check against\n incoming : :any:`Mask` value or valid boolean mask for :any:`MaskedArray` or None\n incoming mask to check for compatibility\n incoming_donwstream : bool\n Whether the incoming mask is from downstream data\n this_grid : Grid or NoGrid or None, optional\n grid for first mask (to check shape and value equality)\n incoming_grid : Grid or NoGrid or None, optional\n grid for second mask (to check shape and value equality)\n\n Returns\n -------\n bool\n mask compatibility\n \"\"\"\n if incoming_donwstream:\n upstream, downstream = this, incoming\n up_grid, down_grid = this_grid, incoming_grid\n else:\n upstream, downstream = incoming, this\n up_grid, down_grid = incoming_grid, this_grid\n # None is incompatible\n if upstream is None:\n return False\n # Mask.FLEX accepts anything, Mask.NONE only Mask.NONE\n if not mask_specified(downstream):\n if not mask_specified(upstream):\n return downstream == Mask.FLEX or upstream == Mask.NONE\n return downstream == Mask.FLEX\n # if mask is specified, upstream mask must also be specified\n if not mask_specified(upstream):\n return False\n # if both mask given, compare them\n return masks_equal(downstream, upstream, down_grid, up_grid)"}, {"class_start_lineno": 22, "class_end_lineno": 248, "func_start_lineno": 157, "func_end_lineno": 201, "func_code": " def accepts(self, incoming, fail_info, incoming_donwstream=False):\n \"\"\"\n Tests whether this info can accept/is compatible with an incoming info.\n\n Tested attributes are: \"grid\", \"mask\" and \"units\"\n\n Parameters\n ----------\n incoming : Info\n Incoming/source info to check. This is the info from upstream.\n fail_info : dict\n Dictionary that will be filled with failed properties; name: (source, target).\n incoming_donwstream : bool, optional\n Whether the incoming info is from downstream data. Default: False\n\n Returns\n -------\n bool\n Whether the incoming info is accepted\n \"\"\"\n if not isinstance(incoming, Info):\n fail_info[\"type\"] = (incoming.__class__, self.__class__)\n return False\n\n success = True\n if self.grid is not None and not self.grid.compatible_with(incoming.grid):\n if not (incoming_donwstream and incoming.grid is None):\n fail_info[\"grid\"] = (incoming.grid, self.grid)\n success = False\n\n if self.mask is not None and not masks_compatible(\n self.mask, incoming.mask, incoming_donwstream, self.grid, incoming.grid\n ):\n if not (incoming_donwstream and incoming.mask is None):\n fail_info[\"mask\"] = (incoming.mask, self.mask)\n success = False\n\n u1_none = (u1 := self.units) is None\n u2_none = (u2 := incoming.units) is None\n if not u1_none and (u2_none or not compatible_units(u1, u2)):\n if not (incoming_donwstream and u2_none):\n fail_info[\"units\"] = (u2, u1)\n success = False\n\n return success"}], "type": ["function_empty"], "node": ["finam.sdk.output.Output.push_info", "finam.sdk.output.Output.__init__", "finam.sdk.component.IOList.add", "finam.data.tools.mask.mask_specified", "finam.data.tools.info.Info.mask", "finam.data.tools.mask.masks_compatible", "finam.data.tools.info.Info.accepts"], "language": "Python", "toolfunc_count": 5, "func_count": 5, "pytest_info": {"total_num": 16, "base_passed_num": 1}} {"id": ["skfolio.src.skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.src.skfolio.datasets._base.load_sp500_dataset", "skfolio.src.skfolio.utils.stats.assert_is_square", "skfolio.src.skfolio.utils.stats.assert_is_symmetric", "skfolio.src.skfolio.utils.stats.cov_nearest"], "project": "skfolio", "origin_file": ["skfolio/datasets/_base.py", "skfolio/datasets/_base.py", "skfolio/utils/stats.py", "skfolio/utils/stats.py", "skfolio/utils/stats.py"], "test_list": ["tests/test_distance/test_distance.py", "tests/test_metrics/test_scorer.py", "tests/test_moment/test_expected_returns/test_expected_returns.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 71, "func_end_lineno": 113, "func_code": "def load_gzip_compressed_csv_data(\n data_filename: str,\n data_module: str = DATA_MODULE,\n encoding=\"utf-8\",\n datetime_index: bool = True,\n) -> pd.DataFrame:\n \"\"\"Load gzip-compressed csv files with `importlib.resources`.\n\n 1) Open resource file with `importlib.resources.open_binary`\n 2) Decompress csv file with `gzip.open`\n 3) Load decompressed data with `pd.read_csv`\n\n Parameters\n ----------\n data_filename : str\n Name of gzip-compressed csv file (`'*.csv.gz'`) to be loaded from\n `data_module/data_file_name`. For example `'SPX500.csv.gz'`.\n\n data_module : str or module, default='skfolio.datasets.data'\n Module where data lives. The default is `'skfolio.datasets.data'`.\n\n encoding : str, default=\"utf-8\"\n Name of the encoding that the gzip-decompressed file will be\n decoded with. The default is 'utf-8'.\n\n datetime_index: bool, default=True\n If this is set to True, the DataFrame index is converted to datetime with\n format=\"%Y-%m-%d\".\n The default is `True`.\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n DataFrame with each row representing one observation and each column\n representing the asset price of a given observation.\n \"\"\"\n path = resources.files(data_module).joinpath(data_filename)\n with path.open(\"rb\") as compressed_file:\n compressed_file = gzip.open(compressed_file, mode=\"rt\", encoding=encoding)\n df = pd.read_csv(compressed_file, sep=\",\", index_col=0)\n if datetime_index:\n df.index = pd.to_datetime(df.index, format=\"%Y-%m-%d\")\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 168, "func_end_lineno": 204, "func_code": "def load_sp500_dataset() -> pd.DataFrame:\n \"\"\"Load the prices of 20 assets from the S&P 500 Index composition.\n\n This dataset is composed of the daily prices of 20 assets from the S&P 500\n composition starting from 1990-01-02 up to 2022-12-28.\n\n The data comes from the Yahoo public API.\n The price is the adjusted close which is the closing price after adjustments for\n all applicable splits and dividend distributions.\n The adjustment uses appropriate split and dividend multipliers, adhering to\n the Center for Research in Security Prices (CRSP) standards.\n\n ============== ==================\n Observations 8313\n Assets 20\n ============== ==================\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n Prices DataFrame\n\n Examples\n --------\n >>> from skfolio.datasets import load_sp500_dataset\n >>> prices = load_sp500_dataset()\n >>> prices.head()\n AAPL AMD BAC ... UNH WMT XOM\n 1990-01-02 0.332589 4.1250 11.65625 ... 0.382813 5.890625 12.5000\n 1990-01-03 0.334821 4.0000 11.75000 ... 0.375000 5.890625 12.3750\n 1990-01-04 0.335938 3.9375 11.50000 ... 0.371094 5.859375 12.2500\n 1990-01-05 0.337054 3.8125 11.25000 ... 0.355469 5.796875 12.1875\n 1990-01-08 0.339286 3.8125 11.31250 ... 0.347656 5.875000 12.3750\n \"\"\"\n data_filename = \"sp500_dataset.csv.gz\"\n df = load_gzip_compressed_csv_data(data_filename)\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 577, "func_start_lineno": 208, "func_end_lineno": 221, "func_code": "def assert_is_square(x: np.ndarray) -> None:\n \"\"\"Raises an error if the matrix is not square.\n\n Parameters\n ----------\n x : ndarray of shape (n, n)\n The matrix.\n\n Raises\n ------\n ValueError: if the matrix is not square.\n \"\"\"\n if x.ndim != 2 or x.shape[0] != x.shape[1]:\n raise ValueError(\"The matrix must be square\")"}, {"class_start_lineno": 1, "class_end_lineno": 577, "func_start_lineno": 224, "func_end_lineno": 238, "func_code": "def assert_is_symmetric(x: np.ndarray) -> None:\n \"\"\"Raises an error if the matrix is not symmetric.\n\n Parameters\n ----------\n x : ndarray of shape (n, m)\n The matrix.\n\n Raises\n ------\n ValueError: if the matrix is not symmetric.\n \"\"\"\n assert_is_square(x)\n if not np.allclose(x, x.T):\n raise ValueError(\"The matrix must be symmetric\")"}, {"class_start_lineno": 1, "class_end_lineno": 577, "func_start_lineno": 308, "func_end_lineno": 400, "func_code": "def cov_nearest(\n cov: np.ndarray,\n higham: bool = False,\n higham_max_iteration: int = 100,\n warn: bool = False,\n):\n \"\"\"Compute the nearest covariance matrix that is positive definite and with a\n cholesky decomposition than can be computed. The variance is left unchanged.\n A covariance matrix that is not positive definite often occurs in high\n dimensional problems. It can be due to multicollinearity, floating-point\n inaccuracies, or when the number of observations is smaller than the number of\n assets.\n\n First, it converts the covariance matrix to a correlation matrix.\n Then, it finds the nearest correlation matrix and converts it back to a covariance\n matrix using the initial standard deviation.\n\n Cholesky decomposition can fail for symmetric positive definite (SPD) matrix due\n to floating point error and inversely, Cholesky decomposition can success for\n non-SPD matrix. Therefore, we need to test for both. We always start by testing\n for Cholesky decomposition which is significantly faster than checking for positive\n eigenvalues.\n\n Parameters\n ----------\n cov : ndarray of shape (n, n)\n Covariance matrix.\n\n higham : bool, default=False\n If this is set to True, the Higham & Nick (2002) algorithm [1]_ is used,\n otherwise the eigenvalues are clipped to threshold above zeros (1e-13).\n The default (`False`) is to use the clipping method as the Higham & Nick\n algorithm can be slow for large datasets.\n\n higham_max_iteration : int, default=100\n Maximum number of iteration of the Higham & Nick (2002) algorithm.\n The default value is `100`.\n\n warn : bool, default=False\n If this is set to True, a user warning is emitted when the covariance matrix\n is not positive definite and replaced by the nearest. The default is False.\n\n Returns\n -------\n cov : ndarray\n The nearest covariance matrix.\n\n References\n ----------\n .. [1] \"Computing the nearest correlation matrix - a problem from finance\"\n IMA Journal of Numerical Analysis\n Higham & Nick (2002)\n \"\"\"\n assert_is_square(cov)\n assert_is_symmetric(cov)\n\n # Around 100 times faster than checking eigenvalues with np.linalg.eigh\n if is_cholesky_dec(cov) and is_positive_definite(cov):\n return cov\n\n if warn:\n warnings.warn(\n \"The covariance matrix is not positive definite. \"\n f\"The {'Higham' if higham else 'Clipping'} algorithm will be used to find \"\n \"the nearest positive definite covariance.\",\n stacklevel=2,\n )\n corr, std = cov_to_corr(cov)\n\n if higham:\n eps = np.finfo(np.float64).eps * 5\n diff = np.zeros(corr.shape)\n x = corr.copy()\n for _ in range(higham_max_iteration):\n x_adj = x - diff\n eig_vals, eig_vecs = np.linalg.eigh(x_adj)\n x = eig_vecs * np.maximum(eig_vals, eps) @ eig_vecs.T\n diff = x - x_adj\n np.fill_diagonal(x, 1)\n cov = corr_to_cov(x, std)\n if is_cholesky_dec(cov) and is_positive_definite(cov):\n break\n else:\n raise ValueError(\"Unable to find the nearest positive definite matrix\")\n else:\n eig_vals, eig_vecs = np.linalg.eigh(corr)\n # Clipping the eigenvalues with a value smaller than 1e-13 can cause scipy to\n # consider the matrix non-psd is some corner cases (see test/test_stats.py)\n x = eig_vecs * np.maximum(eig_vals, _CLIPPING_VALUE) @ eig_vecs.T\n x, _ = cov_to_corr(x)\n cov = corr_to_cov(x, std)\n\n return cov"}], "type": ["function_empty", "Development"], "node": ["skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.datasets._base.load_sp500_dataset", "skfolio.utils.stats.assert_is_square", "skfolio.utils.stats.assert_is_symmetric", "skfolio.utils.stats.cov_nearest"], "language": "Python", "toolfunc_count": 4, "func_count": 5, "pytest_info": {"total_num": 26, "base_passed_num": 6}} {"id": ["skfolio.src.skfolio.distribution.copula._clayton._base_sample_scores", "skfolio.src.skfolio.distribution.copula._clayton._neg_log_likelihood", "skfolio.src.skfolio.distribution.copula._utils._apply_copula_rotation", "skfolio.src.skfolio.distribution.copula._utils._apply_rotation_partial_derivatives"], "project": "skfolio", "origin_file": ["skfolio/distribution/copula/_clayton.py", "skfolio/distribution/copula/_clayton.py", "skfolio/distribution/copula/_utils.py", "skfolio/distribution/copula/_utils.py"], "test_list": ["tests/test_distribution/test_copula/test_clayton.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 539, "func_start_lineno": 416, "func_end_lineno": 448, "func_code": "def _base_sample_scores(X: np.ndarray, theta: float) -> np.ndarray:\n r\"\"\"Compute the log-likelihood of each sample (log-pdf) under the bivariate Clayton\n copula.\n\n Parameters\n ----------\n X : array-like of shape (n_observations, 2)\n Bivariate samples `(u, v)`, with each component in [0,1].\n\n theta : float\n The dependence parameter (must be greater than 0).\n\n Returns\n -------\n logpdf : ndarray of shape (n_observations,)\n Log-likelihood values for each observation.\n\n Raises\n ------\n ValueError\n If theta is not greater than 0.\n \"\"\"\n if theta <= 0:\n raise ValueError(\"Theta must be greater than 1 for the Clayton copula.\")\n\n x, y = np.log(X).T\n\n log_density = (\n np.log1p(theta)\n - (2.0 + 1.0 / theta) * np.log1p(np.expm1(-theta * x) + np.expm1(-theta * y))\n - (1.0 + theta) * (x + y)\n )\n return log_density"}, {"class_start_lineno": 1, "class_end_lineno": 539, "func_start_lineno": 395, "func_end_lineno": 413, "func_code": "def _neg_log_likelihood(theta: float, X: np.ndarray) -> float:\n \"\"\"Negative log-likelihood function for the Clayton copula.\n\n Parameters\n ----------\n X : array-like of shape (n_observations, 2)\n An array of bivariate inputs `(u, v)` where each row represents a\n bivariate observation. Both `u` and `v` must be in the interval `[0, 1]`,\n having been transformed to uniform marginals.\n\n theta : float\n The dependence parameter (must be greater than 0).\n\n Returns\n -------\n value : float\n The negative log-likelihood value.\n \"\"\"\n return -np.sum(_base_sample_scores(X=X, theta=theta))"}, {"class_start_lineno": 1, "class_end_lineno": 509, "func_start_lineno": 341, "func_end_lineno": 380, "func_code": "def _apply_copula_rotation(X: npt.ArrayLike, rotation: CopulaRotation) -> np.ndarray:\n r\"\"\"Apply a bivariate copula rotation using the standard (clockwise) convention.\n\n The transformations are defined as follows:\n\n - `CopulaRotation.R0` (0°): :math:`(u, v) \\mapsto (u, v)`\n - `CopulaRotation.R90` (90°): :math:`(u, v) \\mapsto (v,\\, 1 - u)`\n - `CopulaRotation.R180` (180°): :math:`(u, v) \\mapsto (1 - u,\\, 1 - v)`\n - `CopulaRotation.R270` (270°): :math:`(u, v) \\mapsto (1 - v,\\, u)`\n\n Parameters\n ----------\n X : array-like of shape (n_observations, 2)\n An array of bivariate inputs `(u, v)` where each row represents a\n bivariate observation.\n\n rotation : CopulaRotation\n The rotation to apply to the copula (default is no rotation).\n\n Returns\n -------\n rotated_X: ndarray of shape (n_observations, 2)\n The rotated data array.\n \"\"\"\n match rotation:\n case CopulaRotation.R0:\n # No rotation\n pass\n case CopulaRotation.R90:\n # (u, v) -> (v, 1 - u)\n X = np.column_stack([X[:, 1], 1.0 - X[:, 0]])\n case CopulaRotation.R180:\n # (u, v) -> (1 - u, 1 - v)\n X = 1.0 - X\n case CopulaRotation.R270:\n # (u, v) -> (1 - v, u)\n X = np.column_stack([1.0 - X[:, 1], X[:, 0]])\n case _:\n raise ValueError(f\"Unsupported rotation: {rotation}\")\n return X"}, {"class_start_lineno": 1, "class_end_lineno": 509, "func_start_lineno": 452, "func_end_lineno": 509, "func_code": "def _apply_rotation_partial_derivatives(\n func: Callable,\n X: np.ndarray,\n rotation: CopulaRotation,\n first_margin: bool,\n **kwargs,\n) -> np.ndarray:\n \"\"\"\n Apply a copula rotation to X and compute the corresponding partial derivatives.\n\n This function rotates the data X using the specified rotation and then computes\n the partial derivative (h-function) using the provided function. The result is then\n adjusted according to the rotation and the margin of interest.\n\n Parameters\n ----------\n func : Callable\n A function that computes the partial derivative (h-function) given X, the\n margin, and any additional keyword arguments.\n\n X : ndarray of shape (n_observations, 2)\n A 2D array of bivariate inputs.\n\n rotation : CopulaRotation\n The rotation to apply.\n\n first_margin : bool\n If True, compute the partial derivative with respect to the first margin;\n otherwise, compute it with respect to the second margin.\n\n **kwargs\n Additional keyword arguments to pass to the partial derivative function.\n\n Returns\n -------\n z : ndarray of shape (n_observations,)\n The transformed partial derivative values after applying the rotation.\n \"\"\"\n rotated_X = _apply_copula_rotation(X, rotation=rotation)\n\n match rotation:\n case CopulaRotation.R0:\n z = func(X=rotated_X, first_margin=first_margin, **kwargs)\n case CopulaRotation.R90:\n if first_margin:\n z = func(X=rotated_X, first_margin=not first_margin, **kwargs)\n else:\n z = 1 - func(X=rotated_X, first_margin=not first_margin, **kwargs)\n case CopulaRotation.R180:\n z = 1 - func(X=rotated_X, first_margin=first_margin, **kwargs)\n case CopulaRotation.R270:\n if first_margin:\n z = 1 - func(X=rotated_X, first_margin=not first_margin, **kwargs)\n else:\n z = func(X=rotated_X, first_margin=not first_margin, **kwargs)\n case _:\n raise ValueError(f\"Unsupported rotation: {rotation}\")\n return z"}], "type": ["function_empty"], "node": ["skfolio.distribution.copula._clayton._base_sample_scores", "skfolio.distribution.copula._clayton._neg_log_likelihood", "skfolio.distribution.copula._utils._apply_copula_rotation", "skfolio.distribution.copula._utils._apply_rotation_partial_derivatives"], "language": "Python", "toolfunc_count": 4, "func_count": 4, "pytest_info": {"total_num": 69, "base_passed_num": 4}} {"id": ["skfolio.src.skfolio.distribution.copula._gaussian._base_sample_scores", "skfolio.src.skfolio.distribution.copula._gaussian._neg_log_likelihood"], "project": "skfolio", "origin_file": ["skfolio/distribution/copula/_gaussian.py", "skfolio/distribution/copula/_gaussian.py"], "test_list": ["tests/test_distribution/test_copula/test_gaussian.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 407, "func_start_lineno": 373, "func_end_lineno": 407, "func_code": "def _base_sample_scores(X: np.ndarray, rho: float) -> np.ndarray:\n \"\"\"Compute the log-likelihood of each sample (log-pdf) under the bivariate\n Gaussian copula model.\n\n Parameters\n ----------\n X : array-like of shape (n_observations, 2)\n An array of bivariate inputs `(u, v)` where each row represents a\n bivariate observation. Both `u` and `v` must be in the interval `[0, 1]`,\n having been transformed to uniform marginals.\n\n rho : float\n Gaussian copula parameter.\n\n Returns\n -------\n density : ndarray of shape (n_observations,)\n The log-likelihood of each sample under the fitted copula.\n\n Raises\n ------\n ValueError\n If rho is not in (-1, 1)\n \"\"\"\n if not (-1.0 <= rho <= 1.0):\n raise ValueError(\"rho must be between -1 and 1.\")\n\n # Inverse CDF (ppf) using stdtrit for better performance\n u_inv, v_inv = sp.ndtri(X).T\n\n # Using np.log1p to avoid loss of precision\n log_density = -0.5 * np.log1p(-(rho**2)) - rho * (\n 0.5 * rho * (u_inv**2 + v_inv**2) - u_inv * v_inv\n ) / (1 - rho**2)\n return log_density"}, {"class_start_lineno": 1, "class_end_lineno": 407, "func_start_lineno": 352, "func_end_lineno": 370, "func_code": "def _neg_log_likelihood(rho: float, X: np.ndarray) -> float:\n \"\"\"Negative log-likelihood function for optimization.\n\n Parameters\n ----------\n X : array-like of shape (n_observations, 2)\n An array of bivariate inputs `(u, v)` where each row represents a\n bivariate observation. Both `u` and `v` must be in the interval `[0, 1]`,\n having been transformed to uniform marginals.\n\n rho : float\n Correlation copula parameter.\n\n Returns\n -------\n value : float\n The negative log-likelihood value.\n \"\"\"\n return -np.sum(_base_sample_scores(X=X, rho=rho))"}], "type": ["function_empty", "Development"], "node": ["skfolio.distribution.copula._gaussian._base_sample_scores", "skfolio.distribution.copula._gaussian._neg_log_likelihood"], "language": "Python", "toolfunc_count": 1, "func_count": 2, "pytest_info": {"total_num": 38, "base_passed_num": 26}} {"id": ["skfolio.src.skfolio.distribution.copula._gumbel._base_sample_scores", "skfolio.src.skfolio.distribution.copula._gumbel._neg_log_likelihood", "skfolio.src.skfolio.distribution.copula._utils._apply_copula_rotation", "skfolio.src.skfolio.distribution.copula._utils._apply_margin_swap", "skfolio.src.skfolio.distribution.copula._gumbel._base_partial_derivative", "skfolio.src.skfolio.distribution.copula._utils._apply_rotation_partial_derivatives"], "project": "skfolio", "origin_file": ["skfolio/distribution/copula/_gumbel.py", "skfolio/distribution/copula/_gumbel.py", "skfolio/distribution/copula/_utils.py", "skfolio/distribution/copula/_utils.py", "skfolio/distribution/copula/_gumbel.py", "skfolio/distribution/copula/_utils.py"], "test_list": ["tests/test_distribution/test_copula/test_gumbel.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 560, "func_start_lineno": 422, "func_end_lineno": 451, "func_code": "def _base_sample_scores(X: np.ndarray, theta: float) -> np.ndarray:\n r\"\"\"Compute the log-likelihood of each sample (log-pdf) under the bivariate Gumbel\n copula.\n\n Parameters\n ----------\n X : array-like of shape (n_observations, 2)\n Bivariate samples `(u, v)`, with each component in [0,1].\n\n theta : float\n The dependence parameter (must be greater than 1).\n\n Returns\n -------\n logpdf : ndarray of shape (n_observations,)\n Log-likelihood values for each observation.\n \"\"\"\n if theta <= 1:\n raise ValueError(\"Theta must be greater than 1 for the Gumbel copula.\")\n Z = -np.log(X)\n s = np.power(np.power(Z, theta).sum(axis=1), 1 / theta)\n s = np.clip(s, a_min=1e-10, a_max=None)\n log_density = (\n -s\n + np.log(s + theta - 1)\n + (1 - 2 * theta) * np.log(s)\n + (theta - 1) * np.log(Z.prod(axis=1))\n + Z.sum(axis=1)\n )\n return log_density"}, {"class_start_lineno": 1, "class_end_lineno": 560, "func_start_lineno": 401, "func_end_lineno": 419, "func_code": "def _neg_log_likelihood(theta: float, X: np.ndarray) -> float:\n \"\"\"Negative log-likelihood function for the Gumbel copula.\n\n Parameters\n ----------\n X : array-like of shape (n_observations, 2)\n An array of bivariate inputs `(u, v)` where each row represents a\n bivariate observation. Both `u` and `v` must be in the interval [0, 1],\n having been transformed to uniform marginals.\n\n theta : float\n The dependence parameter (must be greater than 1).\n\n Returns\n -------\n value : float\n The negative log-likelihood value.\n \"\"\"\n return -np.sum(_base_sample_scores(X=X, theta=theta))"}, {"class_start_lineno": 1, "class_end_lineno": 509, "func_start_lineno": 341, "func_end_lineno": 380, "func_code": "def _apply_copula_rotation(X: npt.ArrayLike, rotation: CopulaRotation) -> np.ndarray:\n r\"\"\"Apply a bivariate copula rotation using the standard (clockwise) convention.\n\n The transformations are defined as follows:\n\n - `CopulaRotation.R0` (0°): :math:`(u, v) \\mapsto (u, v)`\n - `CopulaRotation.R90` (90°): :math:`(u, v) \\mapsto (v,\\, 1 - u)`\n - `CopulaRotation.R180` (180°): :math:`(u, v) \\mapsto (1 - u,\\, 1 - v)`\n - `CopulaRotation.R270` (270°): :math:`(u, v) \\mapsto (1 - v,\\, u)`\n\n Parameters\n ----------\n X : array-like of shape (n_observations, 2)\n An array of bivariate inputs `(u, v)` where each row represents a\n bivariate observation.\n\n rotation : CopulaRotation\n The rotation to apply to the copula (default is no rotation).\n\n Returns\n -------\n rotated_X: ndarray of shape (n_observations, 2)\n The rotated data array.\n \"\"\"\n match rotation:\n case CopulaRotation.R0:\n # No rotation\n pass\n case CopulaRotation.R90:\n # (u, v) -> (v, 1 - u)\n X = np.column_stack([X[:, 1], 1.0 - X[:, 0]])\n case CopulaRotation.R180:\n # (u, v) -> (1 - u, 1 - v)\n X = 1.0 - X\n case CopulaRotation.R270:\n # (u, v) -> (1 - v, u)\n X = np.column_stack([1.0 - X[:, 1], X[:, 0]])\n case _:\n raise ValueError(f\"Unsupported rotation: {rotation}\")\n return X"}, {"class_start_lineno": 1, "class_end_lineno": 509, "func_start_lineno": 383, "func_end_lineno": 406, "func_code": "def _apply_margin_swap(X: np.ndarray, first_margin: bool) -> np.ndarray:\n \"\"\"\n Swap the columns of X if first_margin is False.\n\n If first_margin is True, X is returned unchanged; otherwise, the columns\n of X are swapped.\n\n Parameters\n ----------\n X : ndarray of shape (n_observations, 2)\n A 2D array of bivariate inputs (u, v).\n first_margin : bool\n If True, no swap is performed; if False, the columns of X are swapped.\n\n Returns\n -------\n X_swapped : ndarray of shape (n_observations, 2)\n The data array with columns swapped if first_margin is False.\n \"\"\"\n assert X.ndim == 2\n assert X.shape[1] == 2\n if first_margin:\n return X[:, [1, 0]]\n return X"}, {"class_start_lineno": 1, "class_end_lineno": 560, "func_start_lineno": 464, "func_end_lineno": 507, "func_code": "def _base_partial_derivative(\n X: np.ndarray, first_margin: bool, theta: float\n) -> np.ndarray:\n r\"\"\"\n Compute the partial derivative (h-function) for the unrotated Gumbel copula.\n\n For Gumbel, the copula is defined as:\n\n .. math::\n C(u,v)=\\exp\\Bigl(-\\Bigl[(-\\ln u)^{\\theta}+(-\\ln v)^{\\theta}\\Bigr]^{1/\\theta}\\Bigr).\n\n The partial derivative with respect to v is:\n\n .. math::\n \\frac{\\partial C(u,v)}{\\partial v}\n = C(u,v)\\,\\Bigl[(-\\ln u)^{\\theta}+(-\\ln v)^{\\theta}\\Bigr]^{\\frac{1}{\\theta}-1}\n \\,(-\\ln v)^{\\theta-1}\\,\\frac{1}{v}.\n\n Parameters\n ----------\n X : array-like of shape (n_observations, 2)\n An array of bivariate inputs `(u, v)` with values in [0, 1].\n\n first_margin : bool, default=False\n If True, compute with respect to u (by swapping margins); otherwise,\n compute with respect to v.\n\n theta : float\n The dependence parameter (must be > 1).\n\n Returns\n -------\n p : ndarray of shape (n_observations,)\n The computed h-function values.\n \"\"\"\n X = _apply_margin_swap(X, first_margin=first_margin)\n _, v = X.T\n x, y = -np.log(X).T\n p = (\n np.exp(-np.power(np.power(x, theta) + np.power(y, theta), 1.0 / theta))\n * np.power(np.power(x / y, theta) + 1.0, 1.0 / theta - 1.0)\n / v\n )\n return p"}, {"class_start_lineno": 1, "class_end_lineno": 509, "func_start_lineno": 452, "func_end_lineno": 509, "func_code": "def _apply_rotation_partial_derivatives(\n func: Callable,\n X: np.ndarray,\n rotation: CopulaRotation,\n first_margin: bool,\n **kwargs,\n) -> np.ndarray:\n \"\"\"\n Apply a copula rotation to X and compute the corresponding partial derivatives.\n\n This function rotates the data X using the specified rotation and then computes\n the partial derivative (h-function) using the provided function. The result is then\n adjusted according to the rotation and the margin of interest.\n\n Parameters\n ----------\n func : Callable\n A function that computes the partial derivative (h-function) given X, the\n margin, and any additional keyword arguments.\n\n X : ndarray of shape (n_observations, 2)\n A 2D array of bivariate inputs.\n\n rotation : CopulaRotation\n The rotation to apply.\n\n first_margin : bool\n If True, compute the partial derivative with respect to the first margin;\n otherwise, compute it with respect to the second margin.\n\n **kwargs\n Additional keyword arguments to pass to the partial derivative function.\n\n Returns\n -------\n z : ndarray of shape (n_observations,)\n The transformed partial derivative values after applying the rotation.\n \"\"\"\n rotated_X = _apply_copula_rotation(X, rotation=rotation)\n\n match rotation:\n case CopulaRotation.R0:\n z = func(X=rotated_X, first_margin=first_margin, **kwargs)\n case CopulaRotation.R90:\n if first_margin:\n z = func(X=rotated_X, first_margin=not first_margin, **kwargs)\n else:\n z = 1 - func(X=rotated_X, first_margin=not first_margin, **kwargs)\n case CopulaRotation.R180:\n z = 1 - func(X=rotated_X, first_margin=first_margin, **kwargs)\n case CopulaRotation.R270:\n if first_margin:\n z = 1 - func(X=rotated_X, first_margin=not first_margin, **kwargs)\n else:\n z = func(X=rotated_X, first_margin=not first_margin, **kwargs)\n case _:\n raise ValueError(f\"Unsupported rotation: {rotation}\")\n return z"}], "type": ["function_empty", "Development"], "node": ["skfolio.distribution.copula._gumbel._base_sample_scores", "skfolio.distribution.copula._gumbel._neg_log_likelihood", "skfolio.distribution.copula._utils._apply_copula_rotation", "skfolio.distribution.copula._utils._apply_margin_swap", "skfolio.distribution.copula._gumbel._base_partial_derivative", "skfolio.distribution.copula._utils._apply_rotation_partial_derivatives"], "language": "Python", "toolfunc_count": 4, "func_count": 6, "pytest_info": {"total_num": 69, "base_passed_num": 5}} {"id": ["skfolio.src.skfolio.distribution.copula._joe._base_sample_scores", "skfolio.src.skfolio.distribution.copula._joe._neg_log_likelihood", "skfolio.src.skfolio.distribution.copula._utils._apply_copula_rotation", "skfolio.src.skfolio.distribution.copula._utils._apply_margin_swap", "skfolio.src.skfolio.distribution.copula._utils._apply_rotation_partial_derivatives"], "project": "skfolio", "origin_file": ["skfolio/distribution/copula/_joe.py", "skfolio/distribution/copula/_joe.py", "skfolio/distribution/copula/_utils.py", "skfolio/distribution/copula/_utils.py", "skfolio/distribution/copula/_joe.py", "skfolio/distribution/copula/_utils.py"], "test_list": ["tests/test_distribution/test_copula/test_joe.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 609, "func_start_lineno": 439, "func_end_lineno": 473, "func_code": "def _base_sample_scores(X: np.ndarray, theta: float) -> np.ndarray:\n \"\"\"Compute the log-likelihood of each sample (log-pdf) under the bivariate\n Joe copula model.\n\n Parameters\n ----------\n X : array-like of shape (n_observations, 2)\n An array of bivariate inputs `(u, v)` where each row represents a\n bivariate observation. Both `u` and `v` must be in the interval `[0, 1]`,\n having been transformed to uniform marginals.\n\n theta : float\n The dependence parameter (must be greater than 1).\n\n Returns\n -------\n density : ndarray of shape (n_observations,)\n The log-likelihood of each sample under the fitted copula.\n\n Raises\n ------\n ValueError\n If rho is not in (-1, 1) or dof is not positive.\n \"\"\"\n if theta <= 1.0:\n raise ValueError(\"Theta must be greater than 1 for the Joe copula.\")\n\n # log-space transformation to improve stability near 0 or 1\n x, y = np.log1p(-X).T\n x_y = x + y\n d = np.exp(x * theta) + np.exp(y * theta) - np.exp(x_y * theta)\n log_density = (\n (1.0 / theta - 2.0) * np.log(d) + x_y * (theta - 1.0) + np.log(theta - 1.0 + d)\n )\n return log_density"}, {"class_start_lineno": 1, "class_end_lineno": 609, "func_start_lineno": 418, "func_end_lineno": 436, "func_code": "def _neg_log_likelihood(theta: float, X: np.ndarray) -> float:\n \"\"\"Negative log-likelihood function for optimization.\n\n Parameters\n ----------\n X : array-like of shape (n_observations, 2)\n An array of bivariate inputs `(u, v)` where each row represents a\n bivariate observation. Both `u` and `v` must be in the interval `[0, 1]`,\n having been transformed to uniform marginals.\n\n theta : float\n The dependence parameter (must be greater than 1).\n\n Returns\n -------\n value : float\n The negative log-likelihood value.\n \"\"\"\n return -np.sum(_base_sample_scores(X=X, theta=theta))"}, {"class_start_lineno": 1, "class_end_lineno": 509, "func_start_lineno": 341, "func_end_lineno": 380, "func_code": "def _apply_copula_rotation(X: npt.ArrayLike, rotation: CopulaRotation) -> np.ndarray:\n r\"\"\"Apply a bivariate copula rotation using the standard (clockwise) convention.\n\n The transformations are defined as follows:\n\n - `CopulaRotation.R0` (0°): :math:`(u, v) \\mapsto (u, v)`\n - `CopulaRotation.R90` (90°): :math:`(u, v) \\mapsto (v,\\, 1 - u)`\n - `CopulaRotation.R180` (180°): :math:`(u, v) \\mapsto (1 - u,\\, 1 - v)`\n - `CopulaRotation.R270` (270°): :math:`(u, v) \\mapsto (1 - v,\\, u)`\n\n Parameters\n ----------\n X : array-like of shape (n_observations, 2)\n An array of bivariate inputs `(u, v)` where each row represents a\n bivariate observation.\n\n rotation : CopulaRotation\n The rotation to apply to the copula (default is no rotation).\n\n Returns\n -------\n rotated_X: ndarray of shape (n_observations, 2)\n The rotated data array.\n \"\"\"\n match rotation:\n case CopulaRotation.R0:\n # No rotation\n pass\n case CopulaRotation.R90:\n # (u, v) -> (v, 1 - u)\n X = np.column_stack([X[:, 1], 1.0 - X[:, 0]])\n case CopulaRotation.R180:\n # (u, v) -> (1 - u, 1 - v)\n X = 1.0 - X\n case CopulaRotation.R270:\n # (u, v) -> (1 - v, u)\n X = np.column_stack([1.0 - X[:, 1], X[:, 0]])\n case _:\n raise ValueError(f\"Unsupported rotation: {rotation}\")\n return X"}, {"class_start_lineno": 1, "class_end_lineno": 509, "func_start_lineno": 383, "func_end_lineno": 406, "func_code": "def _apply_margin_swap(X: np.ndarray, first_margin: bool) -> np.ndarray:\n \"\"\"\n Swap the columns of X if first_margin is False.\n\n If first_margin is True, X is returned unchanged; otherwise, the columns\n of X are swapped.\n\n Parameters\n ----------\n X : ndarray of shape (n_observations, 2)\n A 2D array of bivariate inputs (u, v).\n first_margin : bool\n If True, no swap is performed; if False, the columns of X are swapped.\n\n Returns\n -------\n X_swapped : ndarray of shape (n_observations, 2)\n The data array with columns swapped if first_margin is False.\n \"\"\"\n assert X.ndim == 2\n assert X.shape[1] == 2\n if first_margin:\n return X[:, [1, 0]]\n return X"}, {"class_start_lineno": 1, "class_end_lineno": 609, "func_start_lineno": 517, "func_end_lineno": 546, "func_code": "def _base_partial_derivative(\n X: np.ndarray, first_margin: bool, theta: float\n) -> np.ndarray:\n r\"\"\"Compute the h-function (partial derivative) for the bivariate unrotated\n Joe copula with respect to a specified margin.\n\n Parameters\n ----------\n X : array-like of shape (n_observations, 2)\n An array of bivariate inputs `(u, v)` where each row represents a\n bivariate observation. Both `u` and `v` must be in the interval `[0, 1]`,\n having been transformed to uniform marginals.\n\n first_margin : bool, default=False\n If True, compute the partial derivative with respect to the first\n margin `u`; otherwise, compute the partial derivative with respect to the\n second margin `v`.\n\n theta : float\n The dependence parameter (must be greater than 1).\n\n Returns\n -------\n : ndarray of shape (n_observations,)\n h-function values :math:`h(u \\mid v) \\;=\\; p` for each observation in X.\n \"\"\"\n X = _apply_margin_swap(X, first_margin=first_margin)\n x, y = np.power(1 - X, theta).T\n p = np.power(1 + x / y - x, 1 / theta - 1) * (1.0 - x)\n return p"}, {"class_start_lineno": 1, "class_end_lineno": 509, "func_start_lineno": 452, "func_end_lineno": 509, "func_code": "def _apply_rotation_partial_derivatives(\n func: Callable,\n X: np.ndarray,\n rotation: CopulaRotation,\n first_margin: bool,\n **kwargs,\n) -> np.ndarray:\n \"\"\"\n Apply a copula rotation to X and compute the corresponding partial derivatives.\n\n This function rotates the data X using the specified rotation and then computes\n the partial derivative (h-function) using the provided function. The result is then\n adjusted according to the rotation and the margin of interest.\n\n Parameters\n ----------\n func : Callable\n A function that computes the partial derivative (h-function) given X, the\n margin, and any additional keyword arguments.\n\n X : ndarray of shape (n_observations, 2)\n A 2D array of bivariate inputs.\n\n rotation : CopulaRotation\n The rotation to apply.\n\n first_margin : bool\n If True, compute the partial derivative with respect to the first margin;\n otherwise, compute it with respect to the second margin.\n\n **kwargs\n Additional keyword arguments to pass to the partial derivative function.\n\n Returns\n -------\n z : ndarray of shape (n_observations,)\n The transformed partial derivative values after applying the rotation.\n \"\"\"\n rotated_X = _apply_copula_rotation(X, rotation=rotation)\n\n match rotation:\n case CopulaRotation.R0:\n z = func(X=rotated_X, first_margin=first_margin, **kwargs)\n case CopulaRotation.R90:\n if first_margin:\n z = func(X=rotated_X, first_margin=not first_margin, **kwargs)\n else:\n z = 1 - func(X=rotated_X, first_margin=not first_margin, **kwargs)\n case CopulaRotation.R180:\n z = 1 - func(X=rotated_X, first_margin=first_margin, **kwargs)\n case CopulaRotation.R270:\n if first_margin:\n z = 1 - func(X=rotated_X, first_margin=not first_margin, **kwargs)\n else:\n z = func(X=rotated_X, first_margin=not first_margin, **kwargs)\n case _:\n raise ValueError(f\"Unsupported rotation: {rotation}\")\n return z"}], "type": ["function_empty"], "node": ["skfolio.distribution.copula._joe._base_sample_scores", "skfolio.distribution.copula._joe._neg_log_likelihood", "skfolio.distribution.copula._utils._apply_copula_rotation", "skfolio.distribution.copula._utils._apply_margin_swap", "skfolio.distribution.copula._joe._base_partial_derivative", "skfolio.distribution.copula._utils._apply_rotation_partial_derivatives"], "language": "Python", "toolfunc_count": 5, "func_count": 5, "pytest_info": {"total_num": 69, "base_passed_num": 4}} {"id": ["skfolio.src.skfolio.distribution.copula._clayton._base_sample_scores", "skfolio.src.skfolio.distribution.copula._clayton._neg_log_likelihood"], "project": "skfolio", "origin_file": ["skfolio/distribution/copula/_clayton.py", "skfolio/distribution/copula/_clayton.py"], "test_list": ["tests/test_distribution/test_copula/test_selection.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 539, "func_start_lineno": 416, "func_end_lineno": 448, "func_code": "def _base_sample_scores(X: np.ndarray, theta: float) -> np.ndarray:\n r\"\"\"Compute the log-likelihood of each sample (log-pdf) under the bivariate Clayton\n copula.\n\n Parameters\n ----------\n X : array-like of shape (n_observations, 2)\n Bivariate samples `(u, v)`, with each component in [0,1].\n\n theta : float\n The dependence parameter (must be greater than 0).\n\n Returns\n -------\n logpdf : ndarray of shape (n_observations,)\n Log-likelihood values for each observation.\n\n Raises\n ------\n ValueError\n If theta is not greater than 0.\n \"\"\"\n if theta <= 0:\n raise ValueError(\"Theta must be greater than 1 for the Clayton copula.\")\n\n x, y = np.log(X).T\n\n log_density = (\n np.log1p(theta)\n - (2.0 + 1.0 / theta) * np.log1p(np.expm1(-theta * x) + np.expm1(-theta * y))\n - (1.0 + theta) * (x + y)\n )\n return log_density"}, {"class_start_lineno": 1, "class_end_lineno": 539, "func_start_lineno": 395, "func_end_lineno": 413, "func_code": "def _neg_log_likelihood(theta: float, X: np.ndarray) -> float:\n \"\"\"Negative log-likelihood function for the Clayton copula.\n\n Parameters\n ----------\n X : array-like of shape (n_observations, 2)\n An array of bivariate inputs `(u, v)` where each row represents a\n bivariate observation. Both `u` and `v` must be in the interval `[0, 1]`,\n having been transformed to uniform marginals.\n\n theta : float\n The dependence parameter (must be greater than 0).\n\n Returns\n -------\n value : float\n The negative log-likelihood value.\n \"\"\"\n return -np.sum(_base_sample_scores(X=X, theta=theta))"}], "type": ["function_empty"], "node": ["skfolio.distribution.copula._clayton._base_sample_scores", "skfolio.distribution.copula._clayton._neg_log_likelihood"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 4, "base_passed_num": 3}} {"id": ["skfolio.src.skfolio.distribution.copula._student_t._sample_scores", "skfolio.src.skfolio.distribution.copula._student_t._neg_log_likelihood"], "project": "skfolio", "origin_file": ["skfolio/distribution/copula/_student_t.py", "skfolio/distribution/copula/_student_t.py"], "test_list": ["tests/test_distribution/test_copula/test_student_t.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 486, "func_start_lineno": 445, "func_end_lineno": 486, "func_code": "def _sample_scores(X: np.ndarray, rho: float, dof: float) -> np.ndarray:\n \"\"\"Compute the log-likelihood of each sample (log-pdf) under the bivariate\n Gaussian copula model.\n\n Parameters\n ----------\n X : array-like of shape (n_observations, 2)\n An array of bivariate inputs `(u, v)` where each row represents a\n bivariate observation. Both `u` and `v` must be in the interval `[0, 1]`,\n having been transformed to uniform marginals.\n\n rho : float\n Gaussian copula parameter.\n\n Returns\n -------\n density : ndarray of shape (n_observations,)\n The log-likelihood of each sample under the fitted copula.\n\n Raises\n ------\n ValueError\n If rho is not in (-1, 1) or dof is not positive.\n \"\"\"\n if not (-1.0 <= rho <= 1.0):\n raise ValueError(\"rho must be between -1 and 1.\")\n if not 1.0 <= dof <= 50:\n raise ValueError(\"Degrees of freedom `dof` must be between 1 and 50.\")\n\n # Inverse CDF (ppf) using stdtrit for better performance\n x, y = sp.stdtrit(dof, X).T\n\n a = 1.0 - rho**2\n log_density = (\n sp.gammaln((dof + 2.0) / 2.0)\n + sp.gammaln(dof / 2.0)\n - 2.0 * sp.gammaln((dof + 1.0) / 2.0)\n - np.log(a) / 2\n + (dof + 1.0) / 2.0 * (np.log1p(x**2 / dof) + np.log1p(y**2 / dof))\n - (dof + 2.0) / 2.0 * np.log1p((x**2 - 2 * rho * x * y + y**2) / a / dof)\n )\n return log_density"}, {"class_start_lineno": 1, "class_end_lineno": 486, "func_start_lineno": 421, "func_end_lineno": 442, "func_code": "def _neg_log_likelihood(dof: float, rho: float, X: np.ndarray) -> float:\n \"\"\"Negative log-likelihood function for optimization.\n\n Parameters\n ----------\n X : array-like of shape (n_observations, 2)\n An array of bivariate inputs `(u, v)` where each row represents a\n bivariate observation. Both `u` and `v` must be in the interval `[0, 1]`,\n having been transformed to uniform marginals.\n\n rho : float\n Correlation copula parameter.\n\n dof : float\n Degree of freedom copula parameter.\n\n Returns\n -------\n value : float\n The negative log-likelihood value.\n \"\"\"\n return -np.sum(_sample_scores(X=X, rho=rho, dof=dof))"}], "type": ["function_empty", "Development"], "node": ["skfolio.distribution.copula._student_t._sample_scores", "skfolio.distribution.copula._student_t._neg_log_likelihood"], "language": "Python", "toolfunc_count": 1, "func_count": 2, "pytest_info": {"total_num": 40, "base_passed_num": 17}} {"id": ["skfolio.src.skfolio.distribution.copula._utils._apply_copula_rotation", "skfolio.src.skfolio.distribution.copula._utils._apply_rotation_cdf", "skfolio.src.skfolio.distribution.copula._utils._apply_rotation_partial_derivatives"], "project": "skfolio", "origin_file": ["skfolio/distribution/copula/_utils.py", "skfolio/distribution/copula/_utils.py", "skfolio/distribution/copula/_utils.py"], "test_list": ["tests/test_distribution/test_copula/test_utils.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 509, "func_start_lineno": 341, "func_end_lineno": 380, "func_code": "def _apply_copula_rotation(X: npt.ArrayLike, rotation: CopulaRotation) -> np.ndarray:\n r\"\"\"Apply a bivariate copula rotation using the standard (clockwise) convention.\n\n The transformations are defined as follows:\n\n - `CopulaRotation.R0` (0°): :math:`(u, v) \\mapsto (u, v)`\n - `CopulaRotation.R90` (90°): :math:`(u, v) \\mapsto (v,\\, 1 - u)`\n - `CopulaRotation.R180` (180°): :math:`(u, v) \\mapsto (1 - u,\\, 1 - v)`\n - `CopulaRotation.R270` (270°): :math:`(u, v) \\mapsto (1 - v,\\, u)`\n\n Parameters\n ----------\n X : array-like of shape (n_observations, 2)\n An array of bivariate inputs `(u, v)` where each row represents a\n bivariate observation.\n\n rotation : CopulaRotation\n The rotation to apply to the copula (default is no rotation).\n\n Returns\n -------\n rotated_X: ndarray of shape (n_observations, 2)\n The rotated data array.\n \"\"\"\n match rotation:\n case CopulaRotation.R0:\n # No rotation\n pass\n case CopulaRotation.R90:\n # (u, v) -> (v, 1 - u)\n X = np.column_stack([X[:, 1], 1.0 - X[:, 0]])\n case CopulaRotation.R180:\n # (u, v) -> (1 - u, 1 - v)\n X = 1.0 - X\n case CopulaRotation.R270:\n # (u, v) -> (1 - v, u)\n X = np.column_stack([1.0 - X[:, 1], X[:, 0]])\n case _:\n raise ValueError(f\"Unsupported rotation: {rotation}\")\n return X"}, {"class_start_lineno": 1, "class_end_lineno": 509, "func_start_lineno": 409, "func_end_lineno": 449, "func_code": "def _apply_rotation_cdf(\n func: Callable, X: np.ndarray, rotation: CopulaRotation, **kwargs\n) -> np.ndarray:\n \"\"\"\n Apply a copula rotation to X and compute the corresponding CDF values.\n\n Parameters\n ----------\n func : Callable\n A function that computes the CDF given data X and additional keyword arguments.\n\n X : ndarray of shape (n_observations, 2)\n A 2D array of bivariate inputs.\n\n rotation : CopulaRotation\n The rotation to apply.\n\n **kwargs\n Additional keyword arguments to pass to the CDF function.\n\n Returns\n -------\n rotated_cdf : ndarray of shape (n_observations,)\n The transformed CDF values after applying the rotation.\n \"\"\"\n rotated_X = _apply_copula_rotation(X, rotation=rotation)\n cdf = func(X=rotated_X, **kwargs)\n\n match rotation:\n case CopulaRotation.R0:\n pass\n case CopulaRotation.R90:\n cdf = X[:, 1] - cdf\n case CopulaRotation.R180:\n cdf = np.sum(X, axis=1) - 1 + cdf\n case CopulaRotation.R270:\n cdf = X[:, 0] - cdf\n case _:\n raise ValueError(f\"Unsupported rotation: {rotation}\")\n\n return cdf"}, {"class_start_lineno": 1, "class_end_lineno": 509, "func_start_lineno": 452, "func_end_lineno": 509, "func_code": "def _apply_rotation_partial_derivatives(\n func: Callable,\n X: np.ndarray,\n rotation: CopulaRotation,\n first_margin: bool,\n **kwargs,\n) -> np.ndarray:\n \"\"\"\n Apply a copula rotation to X and compute the corresponding partial derivatives.\n\n This function rotates the data X using the specified rotation and then computes\n the partial derivative (h-function) using the provided function. The result is then\n adjusted according to the rotation and the margin of interest.\n\n Parameters\n ----------\n func : Callable\n A function that computes the partial derivative (h-function) given X, the\n margin, and any additional keyword arguments.\n\n X : ndarray of shape (n_observations, 2)\n A 2D array of bivariate inputs.\n\n rotation : CopulaRotation\n The rotation to apply.\n\n first_margin : bool\n If True, compute the partial derivative with respect to the first margin;\n otherwise, compute it with respect to the second margin.\n\n **kwargs\n Additional keyword arguments to pass to the partial derivative function.\n\n Returns\n -------\n z : ndarray of shape (n_observations,)\n The transformed partial derivative values after applying the rotation.\n \"\"\"\n rotated_X = _apply_copula_rotation(X, rotation=rotation)\n\n match rotation:\n case CopulaRotation.R0:\n z = func(X=rotated_X, first_margin=first_margin, **kwargs)\n case CopulaRotation.R90:\n if first_margin:\n z = func(X=rotated_X, first_margin=not first_margin, **kwargs)\n else:\n z = 1 - func(X=rotated_X, first_margin=not first_margin, **kwargs)\n case CopulaRotation.R180:\n z = 1 - func(X=rotated_X, first_margin=first_margin, **kwargs)\n case CopulaRotation.R270:\n if first_margin:\n z = 1 - func(X=rotated_X, first_margin=not first_margin, **kwargs)\n else:\n z = func(X=rotated_X, first_margin=not first_margin, **kwargs)\n case _:\n raise ValueError(f\"Unsupported rotation: {rotation}\")\n return z"}], "type": ["function_empty"], "node": ["skfolio.distribution.copula._utils._apply_copula_rotation", "skfolio.distribution.copula._utils._apply_rotation_cdf", "skfolio.distribution.copula._utils._apply_rotation_partial_derivatives"], "language": "Python", "toolfunc_count": 3, "func_count": 3, "pytest_info": {"total_num": 10, "base_passed_num": 6}} {"id": ["skfolio.src.skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.src.skfolio.datasets._base.load_sp500_dataset"], "project": "skfolio", "origin_file": ["skfolio/datasets/_base.py", "skfolio/datasets/_base.py"], "test_list": ["tests/test_distribution/test_multivariate/test_utils.py", "tests/test_model_selection/test_walk_forward.py", "tests/test_utils/test_bootstrap.py", "tests/test_utils/test_validation.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 71, "func_end_lineno": 113, "func_code": "def load_gzip_compressed_csv_data(\n data_filename: str,\n data_module: str = DATA_MODULE,\n encoding=\"utf-8\",\n datetime_index: bool = True,\n) -> pd.DataFrame:\n \"\"\"Load gzip-compressed csv files with `importlib.resources`.\n\n 1) Open resource file with `importlib.resources.open_binary`\n 2) Decompress csv file with `gzip.open`\n 3) Load decompressed data with `pd.read_csv`\n\n Parameters\n ----------\n data_filename : str\n Name of gzip-compressed csv file (`'*.csv.gz'`) to be loaded from\n `data_module/data_file_name`. For example `'SPX500.csv.gz'`.\n\n data_module : str or module, default='skfolio.datasets.data'\n Module where data lives. The default is `'skfolio.datasets.data'`.\n\n encoding : str, default=\"utf-8\"\n Name of the encoding that the gzip-decompressed file will be\n decoded with. The default is 'utf-8'.\n\n datetime_index: bool, default=True\n If this is set to True, the DataFrame index is converted to datetime with\n format=\"%Y-%m-%d\".\n The default is `True`.\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n DataFrame with each row representing one observation and each column\n representing the asset price of a given observation.\n \"\"\"\n path = resources.files(data_module).joinpath(data_filename)\n with path.open(\"rb\") as compressed_file:\n compressed_file = gzip.open(compressed_file, mode=\"rt\", encoding=encoding)\n df = pd.read_csv(compressed_file, sep=\",\", index_col=0)\n if datetime_index:\n df.index = pd.to_datetime(df.index, format=\"%Y-%m-%d\")\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 168, "func_end_lineno": 204, "func_code": "def load_sp500_dataset() -> pd.DataFrame:\n \"\"\"Load the prices of 20 assets from the S&P 500 Index composition.\n\n This dataset is composed of the daily prices of 20 assets from the S&P 500\n composition starting from 1990-01-02 up to 2022-12-28.\n\n The data comes from the Yahoo public API.\n The price is the adjusted close which is the closing price after adjustments for\n all applicable splits and dividend distributions.\n The adjustment uses appropriate split and dividend multipliers, adhering to\n the Center for Research in Security Prices (CRSP) standards.\n\n ============== ==================\n Observations 8313\n Assets 20\n ============== ==================\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n Prices DataFrame\n\n Examples\n --------\n >>> from skfolio.datasets import load_sp500_dataset\n >>> prices = load_sp500_dataset()\n >>> prices.head()\n AAPL AMD BAC ... UNH WMT XOM\n 1990-01-02 0.332589 4.1250 11.65625 ... 0.382813 5.890625 12.5000\n 1990-01-03 0.334821 4.0000 11.75000 ... 0.375000 5.890625 12.3750\n 1990-01-04 0.335938 3.9375 11.50000 ... 0.371094 5.859375 12.2500\n 1990-01-05 0.337054 3.8125 11.25000 ... 0.355469 5.796875 12.1875\n 1990-01-08 0.339286 3.8125 11.31250 ... 0.347656 5.875000 12.3750\n \"\"\"\n data_filename = \"sp500_dataset.csv.gz\"\n df = load_gzip_compressed_csv_data(data_filename)\n return df"}], "type": ["function_empty"], "node": ["skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.datasets._base.load_sp500_dataset"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 24, "base_passed_num": 5}} {"id": ["skfolio.src.skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.src.skfolio.datasets._base.load_sp500_dataset", "skfolio.src.skfolio.measures._measures.get_cumulative_returns", "skfolio.src.skfolio.measures._measures.get_drawdowns"], "project": "skfolio", "origin_file": ["skfolio/datasets/_base.py", "skfolio/datasets/_base.py", "skfolio/measures/_measures.py", "skfolio/measures/_measures.py"], "test_list": ["tests/test_measures/test_measures.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 71, "func_end_lineno": 113, "func_code": "def load_gzip_compressed_csv_data(\n data_filename: str,\n data_module: str = DATA_MODULE,\n encoding=\"utf-8\",\n datetime_index: bool = True,\n) -> pd.DataFrame:\n \"\"\"Load gzip-compressed csv files with `importlib.resources`.\n\n 1) Open resource file with `importlib.resources.open_binary`\n 2) Decompress csv file with `gzip.open`\n 3) Load decompressed data with `pd.read_csv`\n\n Parameters\n ----------\n data_filename : str\n Name of gzip-compressed csv file (`'*.csv.gz'`) to be loaded from\n `data_module/data_file_name`. For example `'SPX500.csv.gz'`.\n\n data_module : str or module, default='skfolio.datasets.data'\n Module where data lives. The default is `'skfolio.datasets.data'`.\n\n encoding : str, default=\"utf-8\"\n Name of the encoding that the gzip-decompressed file will be\n decoded with. The default is 'utf-8'.\n\n datetime_index: bool, default=True\n If this is set to True, the DataFrame index is converted to datetime with\n format=\"%Y-%m-%d\".\n The default is `True`.\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n DataFrame with each row representing one observation and each column\n representing the asset price of a given observation.\n \"\"\"\n path = resources.files(data_module).joinpath(data_filename)\n with path.open(\"rb\") as compressed_file:\n compressed_file = gzip.open(compressed_file, mode=\"rt\", encoding=encoding)\n df = pd.read_csv(compressed_file, sep=\",\", index_col=0)\n if datetime_index:\n df.index = pd.to_datetime(df.index, format=\"%Y-%m-%d\")\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 168, "func_end_lineno": 204, "func_code": "def load_sp500_dataset() -> pd.DataFrame:\n \"\"\"Load the prices of 20 assets from the S&P 500 Index composition.\n\n This dataset is composed of the daily prices of 20 assets from the S&P 500\n composition starting from 1990-01-02 up to 2022-12-28.\n\n The data comes from the Yahoo public API.\n The price is the adjusted close which is the closing price after adjustments for\n all applicable splits and dividend distributions.\n The adjustment uses appropriate split and dividend multipliers, adhering to\n the Center for Research in Security Prices (CRSP) standards.\n\n ============== ==================\n Observations 8313\n Assets 20\n ============== ==================\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n Prices DataFrame\n\n Examples\n --------\n >>> from skfolio.datasets import load_sp500_dataset\n >>> prices = load_sp500_dataset()\n >>> prices.head()\n AAPL AMD BAC ... UNH WMT XOM\n 1990-01-02 0.332589 4.1250 11.65625 ... 0.382813 5.890625 12.5000\n 1990-01-03 0.334821 4.0000 11.75000 ... 0.375000 5.890625 12.3750\n 1990-01-04 0.335938 3.9375 11.50000 ... 0.371094 5.859375 12.2500\n 1990-01-05 0.337054 3.8125 11.25000 ... 0.355469 5.796875 12.1875\n 1990-01-08 0.339286 3.8125 11.31250 ... 0.347656 5.875000 12.3750\n \"\"\"\n data_filename = \"sp500_dataset.csv.gz\"\n df = load_gzip_compressed_csv_data(data_filename)\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 633, "func_start_lineno": 405, "func_end_lineno": 428, "func_code": "def get_cumulative_returns(returns: np.ndarray, compounded: bool = False) -> np.ndarray:\n \"\"\"Compute the cumulative returns from the returns.\n Non-compounded cumulative returns start at 0.\n Compounded cumulative returns are rescaled to start at 1000.\n\n Parameters\n ----------\n returns : ndarray of shape (n_observations,)\n Vector of returns.\n\n compounded : bool, default=False\n If this is set to True, the cumulative returns are compounded otherwise they\n are uncompounded.\n\n Returns\n -------\n values: ndarray of shape (n_observations,)\n Cumulative returns.\n \"\"\"\n if compounded:\n cumulative_returns = 1000 * np.cumprod(1 + returns) # Rescaled to start at 1000\n else:\n cumulative_returns = np.cumsum(returns)\n return cumulative_returns"}, {"class_start_lineno": 1, "class_end_lineno": 633, "func_start_lineno": 431, "func_end_lineno": 453, "func_code": "def get_drawdowns(returns: np.ndarray, compounded: bool = False) -> np.ndarray:\n \"\"\"Compute the drawdowns' series from the returns.\n\n Parameters\n ----------\n returns : ndarray of shape (n_observations,)\n Vector of returns.\n\n compounded : bool, default=False\n If this is set to True, the cumulative returns are compounded otherwise they\n are uncompounded.\n\n Returns\n -------\n values: ndarray of shape (n_observations,)\n Drawdowns.\n \"\"\"\n cumulative_returns = get_cumulative_returns(returns=returns, compounded=compounded)\n if compounded:\n drawdowns = cumulative_returns / np.maximum.accumulate(cumulative_returns) - 1\n else:\n drawdowns = cumulative_returns - np.maximum.accumulate(cumulative_returns)\n return drawdowns"}], "type": ["function_empty"], "node": ["skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.datasets._base.load_sp500_dataset", "skfolio.measures._measures.get_cumulative_returns", "skfolio.measures._measures.get_drawdowns"], "language": "Python", "toolfunc_count": 4, "func_count": 4, "pytest_info": {"total_num": 17, "base_passed_num": 0}} {"id": ["skfolio.src.skfolio.model_selection._combinatorial._n_splits", "skfolio.src.skfolio.model_selection._combinatorial._n_test_paths"], "project": "skfolio", "origin_file": ["skfolio/model_selection/_combinatorial.py", "skfolio/model_selection/_combinatorial.py", "skfolio/model_selection/_combinatorial.py"], "test_list": ["tests/test_model_selection/test_combinatorial.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 564, "func_start_lineno": 415, "func_end_lineno": 431, "func_code": "def _n_splits(n_folds: int, n_test_folds: int) -> int:\n \"\"\"Number of splits.\n\n Parameters\n ----------\n n_folds : int\n Number of folds.\n\n n_test_folds : int\n Number of test folds.\n\n Returns\n -------\n n_splits : int\n Number of splits\n \"\"\"\n return math.comb(n_folds, n_test_folds)"}, {"class_start_lineno": 1, "class_end_lineno": 564, "func_start_lineno": 434, "func_end_lineno": 453, "func_code": "def _n_test_paths(n_folds: int, n_test_folds: int) -> int:\n \"\"\"Number of test paths that can be reconstructed from the train/test\n combinations.\n\n Parameters\n ----------\n n_folds : int\n Number of folds.\n\n n_test_folds : int\n Number of test folds.\n\n Returns\n -------\n n_splits : int\n Number of test paths.\n \"\"\"\n return (\n _n_splits(n_folds=n_folds, n_test_folds=n_test_folds) * n_test_folds // n_folds\n )"}, {"class_start_lineno": 46, "class_end_lineno": 412, "func_start_lineno": 203, "func_end_lineno": 207, "func_code": " def n_test_paths(self) -> int:\n \"\"\"Number of test paths that can be reconstructed from the train/test\n combinations.\n \"\"\"\n return _n_test_paths(n_folds=self.n_folds, n_test_folds=self.n_test_folds)"}], "type": ["function_empty"], "node": ["skfolio.model_selection._combinatorial._n_splits", "skfolio.model_selection._combinatorial._n_test_paths", "skfolio.model_selection._combinatorial.CombinatorialPurgedCV.n_test_paths"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 8, "base_passed_num": 0}} {"id": ["skfolio.src.skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.src.skfolio.datasets._base.load_sp500_dataset", "skfolio.src.skfolio.utils.tools.safe_indexing", "skfolio.src.skfolio.utils.tools.safe_split", "skfolio.src.skfolio.model_selection._validation.cross_val_predict"], "project": "skfolio", "origin_file": ["skfolio/datasets/_base.py", "skfolio/datasets/_base.py", "skfolio/utils/tools.py", "skfolio/utils/tools.py", "skfolio/model_selection/_validation.py"], "test_list": ["tests/test_model_selection/test_validation.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 71, "func_end_lineno": 113, "func_code": "def load_gzip_compressed_csv_data(\n data_filename: str,\n data_module: str = DATA_MODULE,\n encoding=\"utf-8\",\n datetime_index: bool = True,\n) -> pd.DataFrame:\n \"\"\"Load gzip-compressed csv files with `importlib.resources`.\n\n 1) Open resource file with `importlib.resources.open_binary`\n 2) Decompress csv file with `gzip.open`\n 3) Load decompressed data with `pd.read_csv`\n\n Parameters\n ----------\n data_filename : str\n Name of gzip-compressed csv file (`'*.csv.gz'`) to be loaded from\n `data_module/data_file_name`. For example `'SPX500.csv.gz'`.\n\n data_module : str or module, default='skfolio.datasets.data'\n Module where data lives. The default is `'skfolio.datasets.data'`.\n\n encoding : str, default=\"utf-8\"\n Name of the encoding that the gzip-decompressed file will be\n decoded with. The default is 'utf-8'.\n\n datetime_index: bool, default=True\n If this is set to True, the DataFrame index is converted to datetime with\n format=\"%Y-%m-%d\".\n The default is `True`.\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n DataFrame with each row representing one observation and each column\n representing the asset price of a given observation.\n \"\"\"\n path = resources.files(data_module).joinpath(data_filename)\n with path.open(\"rb\") as compressed_file:\n compressed_file = gzip.open(compressed_file, mode=\"rt\", encoding=encoding)\n df = pd.read_csv(compressed_file, sep=\",\", index_col=0)\n if datetime_index:\n df.index = pd.to_datetime(df.index, format=\"%Y-%m-%d\")\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 168, "func_end_lineno": 204, "func_code": "def load_sp500_dataset() -> pd.DataFrame:\n \"\"\"Load the prices of 20 assets from the S&P 500 Index composition.\n\n This dataset is composed of the daily prices of 20 assets from the S&P 500\n composition starting from 1990-01-02 up to 2022-12-28.\n\n The data comes from the Yahoo public API.\n The price is the adjusted close which is the closing price after adjustments for\n all applicable splits and dividend distributions.\n The adjustment uses appropriate split and dividend multipliers, adhering to\n the Center for Research in Security Prices (CRSP) standards.\n\n ============== ==================\n Observations 8313\n Assets 20\n ============== ==================\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n Prices DataFrame\n\n Examples\n --------\n >>> from skfolio.datasets import load_sp500_dataset\n >>> prices = load_sp500_dataset()\n >>> prices.head()\n AAPL AMD BAC ... UNH WMT XOM\n 1990-01-02 0.332589 4.1250 11.65625 ... 0.382813 5.890625 12.5000\n 1990-01-03 0.334821 4.0000 11.75000 ... 0.375000 5.890625 12.3750\n 1990-01-04 0.335938 3.9375 11.50000 ... 0.371094 5.859375 12.2500\n 1990-01-05 0.337054 3.8125 11.25000 ... 0.355469 5.796875 12.1875\n 1990-01-08 0.339286 3.8125 11.31250 ... 0.347656 5.875000 12.3750\n \"\"\"\n data_filename = \"sp500_dataset.csv.gz\"\n df = load_gzip_compressed_csv_data(data_filename)\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 787, "func_start_lineno": 190, "func_end_lineno": 219, "func_code": "def safe_indexing(\n X: npt.ArrayLike | pd.DataFrame, indices: npt.ArrayLike | None, axis: int = 0\n):\n \"\"\"Return rows, items or columns of X using indices.\n\n Parameters\n ----------\n X : array-like\n Data from which to sample rows.\n\n indices : array-like, optional\n Indices of rows or columns.\n The default (`None`) is to select the entire data.\n\n axis : int, default=0\n The axis along which `X` will be sub-sampled. `axis=0` will select\n rows while `axis=1` will select columns.\n\n Returns\n -------\n subset :\n Subset of X on axis 0.\n \"\"\"\n if indices is None:\n return X\n if hasattr(X, \"iloc\"):\n return X.take(indices, axis=axis)\n if axis == 0:\n return X[indices]\n return X[:, indices]"}, {"class_start_lineno": 1, "class_end_lineno": 787, "func_start_lineno": 222, "func_end_lineno": 261, "func_code": "def safe_split(\n X: npt.ArrayLike,\n y: npt.ArrayLike | None = None,\n indices: np.ndarray | None = None,\n axis: int = 0,\n):\n \"\"\"Create subset of dataset.\n\n Slice X, y according to indices for cross-validation.\n\n Parameters\n ----------\n X : array-like\n Data to be indexed.\n\n y : array-like\n Data to be indexed.\n\n indices : ndarray of int, optional\n Rows or columns to select from X and y.\n The default (`None`) is to select the entire data.\n\n axis : int, default=0\n The axis along which `X` will be sub-sampled. `axis=0` will select\n rows while `axis=1` will select columns.\n\n Returns\n -------\n X_subset : array-like\n Indexed data.\n\n y_subset : array-like\n Indexed targets.\n \"\"\"\n X_subset = safe_indexing(X, indices=indices, axis=axis)\n if y is not None:\n y_subset = safe_indexing(y, indices=indices, axis=axis)\n else:\n y_subset = None\n return X_subset, y_subset"}, {"class_start_lineno": 1, "class_end_lineno": 254, "func_start_lineno": 38, "func_end_lineno": 254, "func_code": "def cross_val_predict(\n estimator: skb.BaseEstimator,\n X: npt.ArrayLike,\n y: npt.ArrayLike = None,\n cv: sks.BaseCrossValidator | BaseCombinatorialCV | int | None = None,\n n_jobs: int | None = None,\n method: str = \"predict\",\n verbose: int = 0,\n params: dict | None = None,\n pre_dispatch: str = \"2*n_jobs\",\n column_indices: np.ndarray | None = None,\n portfolio_params: dict | None = None,\n) -> MultiPeriodPortfolio | Population:\n \"\"\"Generate cross-validated `Portfolios` estimates.\n\n The data is split according to the `cv` parameter.\n The optimization estimator is fitted on the training set and portfolios are\n predicted on the corresponding test set.\n\n For non-combinatorial cross-validation like `Kfold`, the output is the predicted\n :class:`~skfolio.portfolio.MultiPeriodPortfolio` where\n each :class:`~skfolio.portfolio.Portfolio` corresponds to the prediction on each\n train/test pair (`k` portfolios for `Kfold`).\n\n For combinatorial cross-validation\n like :class:`~skfolio.model_selection.CombinatorialPurgedCV`, the output is the\n predicted :class:`~skfolio.population.Population` of multiple\n :class:`~skfolio.portfolio.MultiPeriodPortfolio` (each test outputs are a\n collection of multiple paths instead of one single path).\n\n Parameters\n ----------\n estimator : BaseOptimization\n :ref:`Optimization estimators ` use to fit the data.\n\n X : array-like of shape (n_observations, n_assets)\n Price returns of the assets.\n\n y : array-like of shape (n_observations, n_targets), optional\n Target data (optional).\n For example, the price returns of the factors.\n\n cv : int | cross-validation generator, optional\n Determines the cross-validation splitting strategy.\n Possible inputs for cv are:\n\n * None, to use the default 5-fold cross validation,\n * int, to specify the number of folds in a `(Stratified)KFold`,\n * `CV splitter`,\n * An iterable that generates (train, test) splits as arrays of indices.\n\n n_jobs : int, optional\n The number of jobs to run in parallel for `fit` of all `estimators`.\n `None` means 1 unless in a `joblib.parallel_backend` context. -1 means\n using all processors.\n\n method : str\n Invokes the passed method name of the passed estimator.\n\n verbose : int, default=0\n The verbosity level.\n\n params : dict, optional\n Parameters to pass to the underlying estimator's ``fit`` and the CV splitter.\n\n pre_dispatch : int or str, default='2*n_jobs'\n Controls the number of jobs that get dispatched during parallel\n execution. Reducing this number can be useful to avoid an\n explosion of memory consumption when more jobs get dispatched\n than CPUs can process. This parameter can be:\n\n * None, in which case all the jobs are immediately\n created and spawned. Use this for lightweight and\n fast-running jobs, to avoid delays due to on-demand\n spawning of the jobs\n\n * An int, giving the exact number of total jobs that are\n spawned\n\n * A str, giving an expression as a function of n_jobs,\n as in '2*n_jobs'\n\n column_indices : ndarray, optional\n Indices of the `X` columns to cross-validate on.\n\n portfolio_params : dict, optional\n Additional portfolio parameters passed to `MultiPeriodPortfolio`.\n\n Returns\n -------\n predictions : MultiPeriodPortfolio | Population\n This is the result of calling `predict`\n \"\"\"\n params = {} if params is None else params\n\n X, y = safe_split(X, y, indices=column_indices, axis=1)\n X, y = sku.indexable(X, y)\n\n if _routing_enabled():\n # For estimators, a MetadataRouter is created in get_metadata_routing\n # methods. For these router methods, we create the router to use\n # `process_routing` on it.\n # noinspection PyTypeChecker\n router = (\n skm.MetadataRouter(owner=\"cross_validate\")\n .add(\n splitter=cv,\n method_mapping=skm.MethodMapping().add(caller=\"fit\", callee=\"split\"),\n )\n .add(\n estimator=estimator,\n method_mapping=skm.MethodMapping().add(caller=\"fit\", callee=\"fit\"),\n )\n )\n try:\n routed_params = skm.process_routing(router, \"fit\", **params)\n except ske.UnsetMetadataPassedError as e:\n # The default exception would mention `fit` since in the above\n # `process_routing` code, we pass `fit` as the caller. However,\n # the user is not calling `fit` directly, so we change the message\n # to make it more suitable for this case.\n unrequested_params = sorted(e.unrequested_params)\n raise ske.UnsetMetadataPassedError(\n message=(\n f\"{unrequested_params} are passed to `cross_val_predict` but are\"\n \" not explicitly set as requested or not requested for\"\n f\" cross_validate's estimator: {estimator.__class__.__name__} Call\"\n \" `.set_fit_request({{metadata}}=True)` on the estimator for\"\n f\" each metadata in {unrequested_params} that you want to use and\"\n \" `metadata=False` for not using it. See the Metadata Routing User\"\n \" guide \"\n \" for more information.\"\n ),\n unrequested_params=e.unrequested_params,\n routed_params=e.routed_params,\n ) from None\n else:\n routed_params = sku.Bunch()\n routed_params.splitter = sku.Bunch(split={})\n routed_params.estimator = sku.Bunch(fit=params)\n\n cv = sks.check_cv(cv, y)\n splits = list(cv.split(X, y, **routed_params.splitter.split))\n\n portfolio_params = {} if portfolio_params is None else portfolio_params.copy()\n\n # We ensure that the folds are not shuffled\n if not isinstance(cv, BaseCombinatorialCV):\n try:\n if cv.shuffle:\n raise ValueError(\n \"`cross_val_predict` only works with cross-validation setting\"\n \" `shuffle=False`\"\n )\n except AttributeError:\n # If we cannot find the attribute shuffle, we check if the first folds\n # are shuffled\n for fold in splits[0]:\n if not np.all(np.diff(fold) > 0):\n raise ValueError(\n \"`cross_val_predict` only works with un-shuffled folds\"\n ) from None\n\n # We clone the estimator to make sure that all the folds are independent\n # and that it is pickle-able.\n parallel = skp.Parallel(n_jobs=n_jobs, verbose=verbose, pre_dispatch=pre_dispatch)\n # TODO remove when https://github.com/joblib/joblib/issues/1071 is fixed\n # noinspection PyCallingNonCallable\n predictions = parallel(\n skp.delayed(fit_and_predict)(\n sk.clone(estimator),\n X,\n y,\n train=train,\n test=test,\n fit_params=routed_params.estimator.fit,\n method=method,\n )\n for train, test in splits\n )\n\n if isinstance(cv, BaseCombinatorialCV):\n path_ids = cv.get_path_ids()\n path_nb = np.max(path_ids) + 1\n portfolios = [[] for _ in range(path_nb)]\n for i, prediction in enumerate(predictions):\n for j, p in enumerate(prediction):\n path_id = path_ids[i, j]\n portfolios[path_id].append(p)\n name = portfolio_params.pop(\"name\", \"path\")\n pred = Population(\n [\n MultiPeriodPortfolio(\n name=f\"{name}_{i}\", portfolios=portfolios[i], **portfolio_params\n )\n for i in range(path_nb)\n ]\n )\n else:\n # We need to re-order the test folds in case they were un-ordered by the\n # CV generator.\n # Because the tests folds are not shuffled, we use the first index of each\n # fold to order them.\n test_indices = np.concatenate([test for _, test in splits])\n if np.unique(test_indices, axis=0).shape[0] != test_indices.shape[0]:\n raise ValueError(\n \"`cross_val_predict` only works with non-duplicated test indices\"\n )\n test_indices = [test for _, test in splits]\n sorted_fold_id = np.argsort([x[0] for x in test_indices])\n pred = MultiPeriodPortfolio(\n portfolios=[predictions[fold_id] for fold_id in sorted_fold_id],\n check_observations_order=False,\n **portfolio_params,\n )\n\n return pred"}], "type": ["function_empty"], "node": ["skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.datasets._base.load_sp500_dataset", "skfolio.utils.tools.safe_indexing", "skfolio.utils.tools.safe_split", "skfolio.model_selection._validation.cross_val_predict"], "language": "Python", "toolfunc_count": 5, "func_count": 5, "pytest_info": {"total_num": 3, "base_passed_num": 0}} {"id": ["skfolio.src.skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.src.skfolio.datasets._base.load_sp500_dataset", "skfolio.src.skfolio.datasets._base.get_data_home", "skfolio.src.skfolio.datasets._base.download_dataset", "skfolio.src.skfolio.datasets._base.load_sp500_implied_vol_dataset"], "project": "skfolio", "origin_file": ["skfolio/datasets/_base.py", "skfolio/datasets/_base.py", "skfolio/datasets/_base.py", "skfolio/datasets/_base.py", "skfolio/datasets/_base.py"], "test_list": ["tests/test_moment/test_covariance/test_implied_covariance.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 71, "func_end_lineno": 113, "func_code": "def load_gzip_compressed_csv_data(\n data_filename: str,\n data_module: str = DATA_MODULE,\n encoding=\"utf-8\",\n datetime_index: bool = True,\n) -> pd.DataFrame:\n \"\"\"Load gzip-compressed csv files with `importlib.resources`.\n\n 1) Open resource file with `importlib.resources.open_binary`\n 2) Decompress csv file with `gzip.open`\n 3) Load decompressed data with `pd.read_csv`\n\n Parameters\n ----------\n data_filename : str\n Name of gzip-compressed csv file (`'*.csv.gz'`) to be loaded from\n `data_module/data_file_name`. For example `'SPX500.csv.gz'`.\n\n data_module : str or module, default='skfolio.datasets.data'\n Module where data lives. The default is `'skfolio.datasets.data'`.\n\n encoding : str, default=\"utf-8\"\n Name of the encoding that the gzip-decompressed file will be\n decoded with. The default is 'utf-8'.\n\n datetime_index: bool, default=True\n If this is set to True, the DataFrame index is converted to datetime with\n format=\"%Y-%m-%d\".\n The default is `True`.\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n DataFrame with each row representing one observation and each column\n representing the asset price of a given observation.\n \"\"\"\n path = resources.files(data_module).joinpath(data_filename)\n with path.open(\"rb\") as compressed_file:\n compressed_file = gzip.open(compressed_file, mode=\"rt\", encoding=encoding)\n df = pd.read_csv(compressed_file, sep=\",\", index_col=0)\n if datetime_index:\n df.index = pd.to_datetime(df.index, format=\"%Y-%m-%d\")\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 168, "func_end_lineno": 204, "func_code": "def load_sp500_dataset() -> pd.DataFrame:\n \"\"\"Load the prices of 20 assets from the S&P 500 Index composition.\n\n This dataset is composed of the daily prices of 20 assets from the S&P 500\n composition starting from 1990-01-02 up to 2022-12-28.\n\n The data comes from the Yahoo public API.\n The price is the adjusted close which is the closing price after adjustments for\n all applicable splits and dividend distributions.\n The adjustment uses appropriate split and dividend multipliers, adhering to\n the Center for Research in Security Prices (CRSP) standards.\n\n ============== ==================\n Observations 8313\n Assets 20\n ============== ==================\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n Prices DataFrame\n\n Examples\n --------\n >>> from skfolio.datasets import load_sp500_dataset\n >>> prices = load_sp500_dataset()\n >>> prices.head()\n AAPL AMD BAC ... UNH WMT XOM\n 1990-01-02 0.332589 4.1250 11.65625 ... 0.382813 5.890625 12.5000\n 1990-01-03 0.334821 4.0000 11.75000 ... 0.375000 5.890625 12.3750\n 1990-01-04 0.335938 3.9375 11.50000 ... 0.371094 5.859375 12.2500\n 1990-01-05 0.337054 3.8125 11.25000 ... 0.355469 5.796875 12.1875\n 1990-01-08 0.339286 3.8125 11.31250 ... 0.347656 5.875000 12.3750\n \"\"\"\n data_filename = \"sp500_dataset.csv.gz\"\n df = load_gzip_compressed_csv_data(data_filename)\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 25, "func_end_lineno": 55, "func_code": "def get_data_home(data_home: str | Path | None = None) -> str:\n \"\"\"Return the path of the skfolio data directory.\n\n This folder is used by some large dataset loaders to avoid downloading the\n data several times.\n\n By default, the data directory is set to a folder named 'skfolio_data' in the\n user home folder.\n\n Alternatively, it can be set by the 'SKFOLIO_DATA' environment\n variable or programmatically by giving an explicit folder path. The '~'\n symbol is expanded to the user home folder.\n\n If the folder does not already exist, it is automatically created.\n\n Parameters\n ----------\n data_home : str, optional\n The path to skfolio data directory. If `None`, the default path\n is `~/skfolio_data`.\n\n Returns\n -------\n data_home: str or path-like, optional\n The path to skfolio data directory.\n \"\"\"\n if data_home is None:\n data_home = os.environ.get(\"SKFOLIO_DATA\", os.path.join(\"~\", \"skfolio_data\"))\n data_home = os.path.expanduser(data_home)\n os.makedirs(data_home, exist_ok=True)\n return data_home"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 116, "func_end_lineno": 165, "func_code": "def download_dataset(\n data_filename: str,\n data_home: str | Path | None = None,\n download_if_missing: bool = True,\n) -> pd.DataFrame:\n \"\"\"Download and save locally a dataset from the remote GitHub dataset folder.\n\n Parameters\n ----------\n data_filename : str\n Name of gzip-compressed csv file (`'*.csv.gz'`) to be loaded from a remote\n GitHub dataset folder.\n\n data_home : str or path-like, optional\n Specify another download and cache folder for the datasets. By default,\n all skfolio data is stored in `~/skfolio_data` sub-folders.\n\n download_if_missing : bool, default=True\n If False, raise an OSError if the data is not locally available\n instead of trying to download the data from the source site.\n The default is `True`.\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n DataFrame with each row representing one observation and each column\n representing the asset price of a given observation.\n \"\"\"\n # Use a CORS proxy when triggering requests from the browser\n url_prefix = \"https://corsproxy.io/?\" if sys.platform == \"emscripten\" else \"\"\n url = url_prefix + (\n f\"https://github.com/skfolio/skfolio-datasets/raw/main/\"\n f\"datasets/{data_filename}.csv.gz\"\n )\n\n data_home = get_data_home(data_home=data_home)\n filepath = os.path.join(data_home, f\"{data_filename}.pkz\")\n\n if os.path.exists(filepath):\n return joblib.load(filepath)\n\n if not download_if_missing:\n raise OSError(\"Data not found and `download_if_missing` is False\")\n\n archive_path = os.path.join(data_home, os.path.basename(url))\n ur.urlretrieve(url, archive_path)\n df = load_gzip_compressed_csv_data(archive_path)\n joblib.dump(df, filepath, compress=6)\n os.remove(archive_path)\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 400, "func_end_lineno": 448, "func_code": "def load_sp500_implied_vol_dataset(\n data_home=None, download_if_missing=True\n) -> pd.DataFrame:\n \"\"\"Load the 3 months ATM implied volatility of the 20 assets from the\n SP500 dataset.\n\n This dataset is composed of the 3 months ATM implied volatility of 20 assets\n from the S&P 500 composition starting from 2010-01-04 up to 2022-12-28.\n\n The data comes from the Yahoo public API option chains.\n\n ============== ==================\n Observations 3270\n Assets 20\n ============== ==================\n\n Parameters\n ----------\n data_home : str, optional\n Specify another download and cache folder for the datasets.\n By default, all skfolio data is stored in `~/skfolio_data` subfolders.\n\n download_if_missing : bool, default=True\n If False, raise an OSError if the data is not locally available\n instead of trying to download the data from the source site.\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n Implied volatility DataFrame\n\n Examples\n --------\n >>> from skfolio.datasets import load_sp500_implied_vol_dataset\n >>> implied_vol = load_sp500_implied_vol_dataset()\n >>> implied_vol.head()\n AAPL AMD BAC ... UNH WMT XOM\n Date ...\n 2010-01-04 0.364353 0.572056 0.382926 ... 0.362751 0.171737 0.201485\n 2010-01-05 0.371865 0.568791 0.374699 ... 0.368504 0.174764 0.203852\n 2010-01-06 0.356746 0.558054 0.349220 ... 0.368514 0.171892 0.197475\n 2010-01-07 0.361084 0.560475 0.354942 ... 0.355792 0.169083 0.200046\n 2010-01-08 0.348085 0.543932 0.360345 ... 0.351130 0.170897 0.204832\n \"\"\"\n data_filename = \"sp500_implied_vol_dataset\"\n df = download_dataset(\n data_filename, data_home=data_home, download_if_missing=download_if_missing\n )\n return df"}], "type": ["function_empty"], "node": ["skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.datasets._base.load_sp500_dataset", "skfolio.datasets._base.get_data_home", "skfolio.datasets._base.download_dataset", "skfolio.datasets._base.load_sp500_implied_vol_dataset"], "language": "Python", "toolfunc_count": 5, "func_count": 5, "pytest_info": {"total_num": 25, "base_passed_num": 0}} {"id": ["skfolio.src.skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.src.skfolio.datasets._base.load_sp500_dataset", "skfolio.src.skfolio.utils.stats.assert_is_square", "skfolio.src.skfolio.utils.stats.assert_is_symmetric", "skfolio.src.skfolio.utils.stats.assert_is_distance"], "project": "skfolio", "origin_file": ["skfolio/datasets/_base.py", "skfolio/datasets/_base.py", "skfolio/utils/stats.py", "skfolio/utils/stats.py", "skfolio/utils/stats.py"], "test_list": ["tests/test_optimization/test_cluster/test_nco.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 71, "func_end_lineno": 113, "func_code": "def load_gzip_compressed_csv_data(\n data_filename: str,\n data_module: str = DATA_MODULE,\n encoding=\"utf-8\",\n datetime_index: bool = True,\n) -> pd.DataFrame:\n \"\"\"Load gzip-compressed csv files with `importlib.resources`.\n\n 1) Open resource file with `importlib.resources.open_binary`\n 2) Decompress csv file with `gzip.open`\n 3) Load decompressed data with `pd.read_csv`\n\n Parameters\n ----------\n data_filename : str\n Name of gzip-compressed csv file (`'*.csv.gz'`) to be loaded from\n `data_module/data_file_name`. For example `'SPX500.csv.gz'`.\n\n data_module : str or module, default='skfolio.datasets.data'\n Module where data lives. The default is `'skfolio.datasets.data'`.\n\n encoding : str, default=\"utf-8\"\n Name of the encoding that the gzip-decompressed file will be\n decoded with. The default is 'utf-8'.\n\n datetime_index: bool, default=True\n If this is set to True, the DataFrame index is converted to datetime with\n format=\"%Y-%m-%d\".\n The default is `True`.\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n DataFrame with each row representing one observation and each column\n representing the asset price of a given observation.\n \"\"\"\n path = resources.files(data_module).joinpath(data_filename)\n with path.open(\"rb\") as compressed_file:\n compressed_file = gzip.open(compressed_file, mode=\"rt\", encoding=encoding)\n df = pd.read_csv(compressed_file, sep=\",\", index_col=0)\n if datetime_index:\n df.index = pd.to_datetime(df.index, format=\"%Y-%m-%d\")\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 168, "func_end_lineno": 204, "func_code": "def load_sp500_dataset() -> pd.DataFrame:\n \"\"\"Load the prices of 20 assets from the S&P 500 Index composition.\n\n This dataset is composed of the daily prices of 20 assets from the S&P 500\n composition starting from 1990-01-02 up to 2022-12-28.\n\n The data comes from the Yahoo public API.\n The price is the adjusted close which is the closing price after adjustments for\n all applicable splits and dividend distributions.\n The adjustment uses appropriate split and dividend multipliers, adhering to\n the Center for Research in Security Prices (CRSP) standards.\n\n ============== ==================\n Observations 8313\n Assets 20\n ============== ==================\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n Prices DataFrame\n\n Examples\n --------\n >>> from skfolio.datasets import load_sp500_dataset\n >>> prices = load_sp500_dataset()\n >>> prices.head()\n AAPL AMD BAC ... UNH WMT XOM\n 1990-01-02 0.332589 4.1250 11.65625 ... 0.382813 5.890625 12.5000\n 1990-01-03 0.334821 4.0000 11.75000 ... 0.375000 5.890625 12.3750\n 1990-01-04 0.335938 3.9375 11.50000 ... 0.371094 5.859375 12.2500\n 1990-01-05 0.337054 3.8125 11.25000 ... 0.355469 5.796875 12.1875\n 1990-01-08 0.339286 3.8125 11.31250 ... 0.347656 5.875000 12.3750\n \"\"\"\n data_filename = \"sp500_dataset.csv.gz\"\n df = load_gzip_compressed_csv_data(data_filename)\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 577, "func_start_lineno": 208, "func_end_lineno": 221, "func_code": "def assert_is_square(x: np.ndarray) -> None:\n \"\"\"Raises an error if the matrix is not square.\n\n Parameters\n ----------\n x : ndarray of shape (n, n)\n The matrix.\n\n Raises\n ------\n ValueError: if the matrix is not square.\n \"\"\"\n if x.ndim != 2 or x.shape[0] != x.shape[1]:\n raise ValueError(\"The matrix must be square\")"}, {"class_start_lineno": 1, "class_end_lineno": 577, "func_start_lineno": 224, "func_end_lineno": 238, "func_code": "def assert_is_symmetric(x: np.ndarray) -> None:\n \"\"\"Raises an error if the matrix is not symmetric.\n\n Parameters\n ----------\n x : ndarray of shape (n, m)\n The matrix.\n\n Raises\n ------\n ValueError: if the matrix is not symmetric.\n \"\"\"\n assert_is_square(x)\n if not np.allclose(x, x.T):\n raise ValueError(\"The matrix must be symmetric\")"}, {"class_start_lineno": 1, "class_end_lineno": 577, "func_start_lineno": 241, "func_end_lineno": 257, "func_code": "def assert_is_distance(x: np.ndarray) -> None:\n \"\"\"Raises an error if the matrix is not a distance matrix.\n\n Parameters\n ----------\n x : ndarray of shape (n, n)\n The matrix.\n\n Raises\n ------\n ValueError: if the matrix is a distance matrix.\n \"\"\"\n assert_is_symmetric(x)\n if not np.allclose(np.diag(x), np.zeros(x.shape[0]), atol=1e-5):\n raise ValueError(\n \"The distance matrix must have diagonal elements close to zeros\"\n )"}], "type": ["function_empty"], "node": ["skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.datasets._base.load_sp500_dataset", "skfolio.utils.stats.assert_is_square", "skfolio.utils.stats.assert_is_symmetric", "skfolio.utils.stats.assert_is_distance"], "language": "Python", "toolfunc_count": 5, "func_count": 5, "pytest_info": {"total_num": 15, "base_passed_num": 0}} {"id": ["skfolio.src.skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.src.skfolio.datasets._base.load_sp500_dataset", "skfolio.src.skfolio.prior._empirical.EmpiricalPrior::get_metadata_routing", "skfolio.src.skfolio.prior._empirical.EmpiricalPrior::fit"], "project": "skfolio", "origin_file": ["skfolio/datasets/_base.py", "skfolio/datasets/_base.py", "skfolio/prior/_empirical.py", "skfolio/prior/_empirical.py"], "test_list": ["tests/test_optimization/test_cluster/test_hierarchical/test_herc.py", "tests/test_optimization/test_cluster/test_hierarchical/test_hrp.py", "tests/test_optimization/test_convex/test_maximum_diversification.py", "tests/test_optimization/test_convex/test_risk_budgeting.py", "tests/test_prior/test_empirical.py", "tests/test_uncertainty_set/test_bootstrap.py", "tests/test_uncertainty_set/test_empirical.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 71, "func_end_lineno": 113, "func_code": "def load_gzip_compressed_csv_data(\n data_filename: str,\n data_module: str = DATA_MODULE,\n encoding=\"utf-8\",\n datetime_index: bool = True,\n) -> pd.DataFrame:\n \"\"\"Load gzip-compressed csv files with `importlib.resources`.\n\n 1) Open resource file with `importlib.resources.open_binary`\n 2) Decompress csv file with `gzip.open`\n 3) Load decompressed data with `pd.read_csv`\n\n Parameters\n ----------\n data_filename : str\n Name of gzip-compressed csv file (`'*.csv.gz'`) to be loaded from\n `data_module/data_file_name`. For example `'SPX500.csv.gz'`.\n\n data_module : str or module, default='skfolio.datasets.data'\n Module where data lives. The default is `'skfolio.datasets.data'`.\n\n encoding : str, default=\"utf-8\"\n Name of the encoding that the gzip-decompressed file will be\n decoded with. The default is 'utf-8'.\n\n datetime_index: bool, default=True\n If this is set to True, the DataFrame index is converted to datetime with\n format=\"%Y-%m-%d\".\n The default is `True`.\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n DataFrame with each row representing one observation and each column\n representing the asset price of a given observation.\n \"\"\"\n path = resources.files(data_module).joinpath(data_filename)\n with path.open(\"rb\") as compressed_file:\n compressed_file = gzip.open(compressed_file, mode=\"rt\", encoding=encoding)\n df = pd.read_csv(compressed_file, sep=\",\", index_col=0)\n if datetime_index:\n df.index = pd.to_datetime(df.index, format=\"%Y-%m-%d\")\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 168, "func_end_lineno": 204, "func_code": "def load_sp500_dataset() -> pd.DataFrame:\n \"\"\"Load the prices of 20 assets from the S&P 500 Index composition.\n\n This dataset is composed of the daily prices of 20 assets from the S&P 500\n composition starting from 1990-01-02 up to 2022-12-28.\n\n The data comes from the Yahoo public API.\n The price is the adjusted close which is the closing price after adjustments for\n all applicable splits and dividend distributions.\n The adjustment uses appropriate split and dividend multipliers, adhering to\n the Center for Research in Security Prices (CRSP) standards.\n\n ============== ==================\n Observations 8313\n Assets 20\n ============== ==================\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n Prices DataFrame\n\n Examples\n --------\n >>> from skfolio.datasets import load_sp500_dataset\n >>> prices = load_sp500_dataset()\n >>> prices.head()\n AAPL AMD BAC ... UNH WMT XOM\n 1990-01-02 0.332589 4.1250 11.65625 ... 0.382813 5.890625 12.5000\n 1990-01-03 0.334821 4.0000 11.75000 ... 0.375000 5.890625 12.3750\n 1990-01-04 0.335938 3.9375 11.50000 ... 0.371094 5.859375 12.2500\n 1990-01-05 0.337054 3.8125 11.25000 ... 0.355469 5.796875 12.1875\n 1990-01-08 0.339286 3.8125 11.31250 ... 0.347656 5.875000 12.3750\n \"\"\"\n data_filename = \"sp500_dataset.csv.gz\"\n df = load_gzip_compressed_csv_data(data_filename)\n return df"}, {"class_start_lineno": 17, "class_end_lineno": 202, "func_start_lineno": 93, "func_end_lineno": 106, "func_code": " def get_metadata_routing(self):\n # noinspection PyTypeChecker\n router = (\n skm.MetadataRouter(owner=self.__class__.__name__)\n .add(\n mu_estimator=self.mu_estimator,\n method_mapping=skm.MethodMapping().add(caller=\"fit\", callee=\"fit\"),\n )\n .add(\n covariance_estimator=self.covariance_estimator,\n method_mapping=skm.MethodMapping().add(caller=\"fit\", callee=\"fit\"),\n )\n )\n return router"}, {"class_start_lineno": 17, "class_end_lineno": 202, "func_start_lineno": 108, "func_end_lineno": 202, "func_code": " def fit(self, X: npt.ArrayLike, y=None, **fit_params) -> \"EmpiricalPrior\":\n \"\"\"Fit the Empirical Prior estimator.\n\n Parameters\n ----------\n X : array-like of shape (n_observations, n_assets)\n Price returns of the assets.\n\n y : Ignored\n Not used, present for API consistency by convention.\n\n **fit_params : dict\n Parameters to pass to the underlying estimators.\n Only available if `enable_metadata_routing=True`, which can be\n set by using ``sklearn.set_config(enable_metadata_routing=True)``.\n See :ref:`Metadata Routing User Guide ` for\n more details.\n\n Returns\n -------\n self : EmpiricalPrior\n Fitted estimator.\n \"\"\"\n routed_params = skm.process_routing(self, \"fit\", **fit_params)\n\n self.mu_estimator_ = check_estimator(\n self.mu_estimator,\n default=EmpiricalMu(),\n check_type=BaseMu,\n )\n self.covariance_estimator_ = check_estimator(\n self.covariance_estimator,\n default=EmpiricalCovariance(),\n check_type=BaseCovariance,\n )\n # fitting estimators\n if not self.is_log_normal:\n if self.investment_horizon is not None:\n raise ValueError(\n \"`investment_horizon` must be `None` when \"\n \"`is_log_normal` is `False`\"\n )\n # Expected returns\n # noinspection PyArgumentList\n self.mu_estimator_.fit(X, y, **routed_params.mu_estimator.fit)\n mu = self.mu_estimator_.mu_\n\n # Covariance\n # noinspection PyArgumentList\n self.covariance_estimator_.fit(\n X, y, **routed_params.covariance_estimator.fit\n )\n covariance = self.covariance_estimator_.covariance_\n else:\n if self.investment_horizon is None:\n raise ValueError(\n \"`investment_horizon` must be provided when \"\n \"`is_log_normal` is `True`\"\n )\n # Convert linear returns to log returns\n X_log = np.log(1 + X)\n y_log = np.log(1 + y) if y is not None else None\n\n # Estimates the moments on the log returns\n # Expected returns\n # noinspection PyArgumentList\n self.mu_estimator_.fit(X_log, y_log, **routed_params.mu_estimator.fit)\n mu = self.mu_estimator_.mu_\n\n # Covariance\n # noinspection PyArgumentList\n self.covariance_estimator_.fit(\n X_log, y_log, **routed_params.covariance_estimator.fit\n )\n covariance = self.covariance_estimator_.covariance_\n\n # Using the property of aggregation across time we scale this distribution\n # to the investment horizon by the “square-root rule”.\n mu *= self.investment_horizon\n covariance *= self.investment_horizon\n\n # We convert it into a distribution of linear returns over the investment\n # horizon\n mu = np.exp(mu + 0.5 * np.diag(covariance))\n covariance = np.outer(mu, mu) * (np.exp(covariance) - 1)\n\n # we validate and convert to numpy after all models have been fitted to keep\n # features names information.\n X = skv.validate_data(self, X)\n self.prior_model_ = PriorModel(\n mu=mu,\n covariance=covariance,\n returns=X,\n )\n return self"}], "type": ["function_empty", "Development"], "node": ["skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.datasets._base.load_sp500_dataset", "skfolio.prior._empirical.EmpiricalPrior.get_metadata_routing", "skfolio.prior._empirical.EmpiricalPrior.fit"], "language": "Python", "toolfunc_count": 2, "func_count": 4, "pytest_info": {"total_num": 398, "base_passed_num": 0}} {"id": ["skfolio.src.skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.src.skfolio.datasets._base.load_sp500_dataset", "skfolio.src.skfolio.optimization.ensemble._stacking.StackingOptimization::get_metadata_routing", "skfolio.src.skfolio.optimization.ensemble._stacking.StackingOptimization::fit"], "project": "skfolio", "origin_file": ["skfolio/datasets/_base.py", "skfolio/datasets/_base.py", "skfolio/optimization/ensemble/_stacking.py", "skfolio/optimization/ensemble/_stacking.py"], "test_list": ["tests/test_optimization/test_ensemble/test_stacking.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 71, "func_end_lineno": 113, "func_code": "def load_gzip_compressed_csv_data(\n data_filename: str,\n data_module: str = DATA_MODULE,\n encoding=\"utf-8\",\n datetime_index: bool = True,\n) -> pd.DataFrame:\n \"\"\"Load gzip-compressed csv files with `importlib.resources`.\n\n 1) Open resource file with `importlib.resources.open_binary`\n 2) Decompress csv file with `gzip.open`\n 3) Load decompressed data with `pd.read_csv`\n\n Parameters\n ----------\n data_filename : str\n Name of gzip-compressed csv file (`'*.csv.gz'`) to be loaded from\n `data_module/data_file_name`. For example `'SPX500.csv.gz'`.\n\n data_module : str or module, default='skfolio.datasets.data'\n Module where data lives. The default is `'skfolio.datasets.data'`.\n\n encoding : str, default=\"utf-8\"\n Name of the encoding that the gzip-decompressed file will be\n decoded with. The default is 'utf-8'.\n\n datetime_index: bool, default=True\n If this is set to True, the DataFrame index is converted to datetime with\n format=\"%Y-%m-%d\".\n The default is `True`.\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n DataFrame with each row representing one observation and each column\n representing the asset price of a given observation.\n \"\"\"\n path = resources.files(data_module).joinpath(data_filename)\n with path.open(\"rb\") as compressed_file:\n compressed_file = gzip.open(compressed_file, mode=\"rt\", encoding=encoding)\n df = pd.read_csv(compressed_file, sep=\",\", index_col=0)\n if datetime_index:\n df.index = pd.to_datetime(df.index, format=\"%Y-%m-%d\")\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 168, "func_end_lineno": 204, "func_code": "def load_sp500_dataset() -> pd.DataFrame:\n \"\"\"Load the prices of 20 assets from the S&P 500 Index composition.\n\n This dataset is composed of the daily prices of 20 assets from the S&P 500\n composition starting from 1990-01-02 up to 2022-12-28.\n\n The data comes from the Yahoo public API.\n The price is the adjusted close which is the closing price after adjustments for\n all applicable splits and dividend distributions.\n The adjustment uses appropriate split and dividend multipliers, adhering to\n the Center for Research in Security Prices (CRSP) standards.\n\n ============== ==================\n Observations 8313\n Assets 20\n ============== ==================\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n Prices DataFrame\n\n Examples\n --------\n >>> from skfolio.datasets import load_sp500_dataset\n >>> prices = load_sp500_dataset()\n >>> prices.head()\n AAPL AMD BAC ... UNH WMT XOM\n 1990-01-02 0.332589 4.1250 11.65625 ... 0.382813 5.890625 12.5000\n 1990-01-03 0.334821 4.0000 11.75000 ... 0.375000 5.890625 12.3750\n 1990-01-04 0.335938 3.9375 11.50000 ... 0.371094 5.859375 12.2500\n 1990-01-05 0.337054 3.8125 11.25000 ... 0.355469 5.796875 12.1875\n 1990-01-08 0.339286 3.8125 11.31250 ... 0.347656 5.875000 12.3750\n \"\"\"\n data_filename = \"sp500_dataset.csv.gz\"\n df = load_gzip_compressed_csv_data(data_filename)\n return df"}, {"class_start_lineno": 30, "class_end_lineno": 355, "func_start_lineno": 233, "func_end_lineno": 241, "func_code": " def get_metadata_routing(self):\n # noinspection PyTypeChecker\n router = skm.MetadataRouter(owner=self.__class__.__name__)\n for name, estimator in self.estimators:\n router.add(\n **{name: estimator},\n method_mapping=skm.MethodMapping().add(caller=\"fit\", callee=\"fit\"),\n )\n return router"}, {"class_start_lineno": 30, "class_end_lineno": 355, "func_start_lineno": 243, "func_end_lineno": 355, "func_code": " def fit(\n self, X: npt.ArrayLike, y: npt.ArrayLike | None = None, **fit_params\n ) -> \"StackingOptimization\":\n \"\"\"Fit the Stacking Optimization estimator.\n\n Parameters\n ----------\n X : array-like of shape (n_observations, n_assets)\n Price returns of the assets.\n\n y : array-like of shape (n_observations, n_targets), optional\n Price returns of factors or a target benchmark.\n The default is `None`.\n\n **fit_params : dict\n Parameters to pass to the underlying estimators.\n Only available if `enable_metadata_routing=True`, which can be\n set by using ``sklearn.set_config(enable_metadata_routing=True)``.\n See :ref:`Metadata Routing User Guide ` for\n more details.\n\n Returns\n -------\n self : StackingOptimization\n Fitted estimator.\n \"\"\"\n routed_params = skm.process_routing(self, \"fit\", **fit_params)\n\n names, all_estimators = self._validate_estimators()\n self.final_estimator_ = check_estimator(\n self.final_estimator,\n default=MeanRisk(),\n check_type=BaseOptimization,\n )\n\n if self.cv == \"prefit\":\n self.estimators_ = []\n for estimator in all_estimators:\n skv.check_is_fitted(estimator)\n self.estimators_.append(estimator)\n else:\n # Fit the base estimators on the whole training data. Those\n # base estimators will be used to retrieve the inner weights.\n # They are exposed publicly.\n # noinspection PyCallingNonCallable\n self.estimators_ = skp.Parallel(n_jobs=self.n_jobs)(\n skp.delayed(fit_single_estimator)(\n sk.clone(est), X, y, routed_params[name][\"fit\"]\n )\n for name, est in zip(names, all_estimators, strict=True)\n )\n\n self.named_estimators_ = {\n name: estimator\n for name, estimator in zip(names, self.estimators_, strict=True)\n }\n\n inner_weights = np.array([estimator.weights_ for estimator in self.estimators_])\n\n # To train the final-estimator using the most data as possible, we use\n # a cross-validation to obtain the output of the stacked estimators.\n # To ensure that the data provided to each estimator are the same,\n # we need to set the random state of the cv if there is one and we\n # need to take a copy.\n if self.cv in [\"prefit\", \"ignore\"]:\n X_pred = np.array(\n [estimator.predict(X) for estimator in self.estimators_]\n ).T\n else:\n cv = sks.check_cv(self.cv)\n if hasattr(cv, \"random_state\") and cv.random_state is None:\n cv.random_state = np.random.RandomState()\n # noinspection PyCallingNonCallable\n cv_predictions = skp.Parallel(n_jobs=self.n_jobs)(\n skp.delayed(cross_val_predict)(\n sk.clone(est),\n X,\n y,\n cv=deepcopy(cv),\n method=\"predict\",\n n_jobs=self.n_jobs,\n params=routed_params[name][\"fit\"],\n verbose=self.verbose,\n )\n for name, est in zip(names, all_estimators, strict=True)\n )\n\n # We validate and convert to numpy array only after base-estimator fitting\n # to keep the assets names in case they are used in the estimator.\n if y is not None:\n _, y = skv.validate_data(self, X, y, multi_output=True)\n else:\n _ = skv.validate_data(self, X)\n\n if isinstance(self.cv, BaseCombinatorialCV):\n X_pred = np.array(\n [\n pred.quantile(measure=self.quantile_measure, q=self.quantile)\n for pred in cv_predictions\n ]\n ).T\n else:\n X_pred = np.array(cv_predictions).T\n if y is not None:\n test_indices = np.sort(\n np.concatenate([test for _, test in cv.split(X, y)])\n )\n y = y[test_indices]\n\n fit_single_estimator(self.final_estimator_, X_pred, y, {})\n outer_weights = self.final_estimator_.weights_\n self.weights_ = outer_weights @ inner_weights\n return self"}], "type": ["function_empty", "Development"], "node": ["skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.datasets._base.load_sp500_dataset", "skfolio.optimization.ensemble._stacking.StackingOptimization.get_metadata_routing", "skfolio.optimization.ensemble._stacking.StackingOptimization.fit"], "language": "Python", "toolfunc_count": 2, "func_count": 4, "pytest_info": {"total_num": 5, "base_passed_num": 1}} {"id": ["skfolio.src.skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.src.skfolio.datasets._base.load_sp500_dataset", "skfolio.src.skfolio.datasets._base.load_factors_dataset", "skfolio.src.skfolio.prior._empirical.EmpiricalPrior::get_metadata_routing", "skfolio.src.skfolio.prior._empirical.EmpiricalPrior::fit"], "project": "skfolio", "origin_file": ["skfolio/datasets/_base.py", "skfolio/datasets/_base.py", "skfolio/datasets/_base.py", "skfolio/prior/_empirical.py", "skfolio/prior/_empirical.py"], "test_list": ["tests/test_optimization/test_naive/test_naive.py", "tests/test_prior/test_factor_model.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 71, "func_end_lineno": 113, "func_code": "def load_gzip_compressed_csv_data(\n data_filename: str,\n data_module: str = DATA_MODULE,\n encoding=\"utf-8\",\n datetime_index: bool = True,\n) -> pd.DataFrame:\n \"\"\"Load gzip-compressed csv files with `importlib.resources`.\n\n 1) Open resource file with `importlib.resources.open_binary`\n 2) Decompress csv file with `gzip.open`\n 3) Load decompressed data with `pd.read_csv`\n\n Parameters\n ----------\n data_filename : str\n Name of gzip-compressed csv file (`'*.csv.gz'`) to be loaded from\n `data_module/data_file_name`. For example `'SPX500.csv.gz'`.\n\n data_module : str or module, default='skfolio.datasets.data'\n Module where data lives. The default is `'skfolio.datasets.data'`.\n\n encoding : str, default=\"utf-8\"\n Name of the encoding that the gzip-decompressed file will be\n decoded with. The default is 'utf-8'.\n\n datetime_index: bool, default=True\n If this is set to True, the DataFrame index is converted to datetime with\n format=\"%Y-%m-%d\".\n The default is `True`.\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n DataFrame with each row representing one observation and each column\n representing the asset price of a given observation.\n \"\"\"\n path = resources.files(data_module).joinpath(data_filename)\n with path.open(\"rb\") as compressed_file:\n compressed_file = gzip.open(compressed_file, mode=\"rt\", encoding=encoding)\n df = pd.read_csv(compressed_file, sep=\",\", index_col=0)\n if datetime_index:\n df.index = pd.to_datetime(df.index, format=\"%Y-%m-%d\")\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 168, "func_end_lineno": 204, "func_code": "def load_sp500_dataset() -> pd.DataFrame:\n \"\"\"Load the prices of 20 assets from the S&P 500 Index composition.\n\n This dataset is composed of the daily prices of 20 assets from the S&P 500\n composition starting from 1990-01-02 up to 2022-12-28.\n\n The data comes from the Yahoo public API.\n The price is the adjusted close which is the closing price after adjustments for\n all applicable splits and dividend distributions.\n The adjustment uses appropriate split and dividend multipliers, adhering to\n the Center for Research in Security Prices (CRSP) standards.\n\n ============== ==================\n Observations 8313\n Assets 20\n ============== ==================\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n Prices DataFrame\n\n Examples\n --------\n >>> from skfolio.datasets import load_sp500_dataset\n >>> prices = load_sp500_dataset()\n >>> prices.head()\n AAPL AMD BAC ... UNH WMT XOM\n 1990-01-02 0.332589 4.1250 11.65625 ... 0.382813 5.890625 12.5000\n 1990-01-03 0.334821 4.0000 11.75000 ... 0.375000 5.890625 12.3750\n 1990-01-04 0.335938 3.9375 11.50000 ... 0.371094 5.859375 12.2500\n 1990-01-05 0.337054 3.8125 11.25000 ... 0.355469 5.796875 12.1875\n 1990-01-08 0.339286 3.8125 11.31250 ... 0.347656 5.875000 12.3750\n \"\"\"\n data_filename = \"sp500_dataset.csv.gz\"\n df = load_gzip_compressed_csv_data(data_filename)\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 247, "func_end_lineno": 292, "func_code": "def load_factors_dataset() -> pd.DataFrame:\n \"\"\"Load the prices of 5 factor ETFs.\n\n This dataset is composed of the daily prices of 5 ETF representing common factors\n starting from 2014-01-02 up to 2022-12-28.\n\n The factors are:\n\n * \"MTUM\": Momentum\n * \"QUAL\": Quality\n * \"SIZE\": Size\n * \"VLUE\": Value\n * \"USMV\": low volatility\n\n The data comes from the Yahoo public API.\n The price is the adjusted close which is the closing price after adjustments for\n all applicable splits and dividend distributions.\n The adjustment uses appropriate split and dividend multipliers, adhering to\n the Center for Research in Security Prices (CRSP) standards.\n\n ============== ==================\n Observations 2264\n Assets 5\n ============== ==================\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n Prices DataFrame\n\n Examples\n --------\n >>> from skfolio.datasets import load_factors_dataset\n >>> prices = load_factors_dataset()\n >>> prices.head()\n MTUM QUAL SIZE USMV VLUE\n Date\n 2014-01-02 52.704 48.351 48.986 29.338 47.054\n 2014-01-03 52.792 48.256 48.722 29.330 46.999\n 2014-01-06 52.677 48.067 48.722 29.263 46.991\n 2014-01-07 53.112 48.455 48.731 29.430 47.253\n 2014-01-08 53.502 48.437 48.731 29.422 47.253\n \"\"\"\n data_filename = \"factors_dataset.csv.gz\"\n df = load_gzip_compressed_csv_data(data_filename)\n return df"}, {"class_start_lineno": 17, "class_end_lineno": 202, "func_start_lineno": 93, "func_end_lineno": 106, "func_code": " def get_metadata_routing(self):\n # noinspection PyTypeChecker\n router = (\n skm.MetadataRouter(owner=self.__class__.__name__)\n .add(\n mu_estimator=self.mu_estimator,\n method_mapping=skm.MethodMapping().add(caller=\"fit\", callee=\"fit\"),\n )\n .add(\n covariance_estimator=self.covariance_estimator,\n method_mapping=skm.MethodMapping().add(caller=\"fit\", callee=\"fit\"),\n )\n )\n return router"}, {"class_start_lineno": 17, "class_end_lineno": 202, "func_start_lineno": 108, "func_end_lineno": 202, "func_code": " def fit(self, X: npt.ArrayLike, y=None, **fit_params) -> \"EmpiricalPrior\":\n \"\"\"Fit the Empirical Prior estimator.\n\n Parameters\n ----------\n X : array-like of shape (n_observations, n_assets)\n Price returns of the assets.\n\n y : Ignored\n Not used, present for API consistency by convention.\n\n **fit_params : dict\n Parameters to pass to the underlying estimators.\n Only available if `enable_metadata_routing=True`, which can be\n set by using ``sklearn.set_config(enable_metadata_routing=True)``.\n See :ref:`Metadata Routing User Guide ` for\n more details.\n\n Returns\n -------\n self : EmpiricalPrior\n Fitted estimator.\n \"\"\"\n routed_params = skm.process_routing(self, \"fit\", **fit_params)\n\n self.mu_estimator_ = check_estimator(\n self.mu_estimator,\n default=EmpiricalMu(),\n check_type=BaseMu,\n )\n self.covariance_estimator_ = check_estimator(\n self.covariance_estimator,\n default=EmpiricalCovariance(),\n check_type=BaseCovariance,\n )\n # fitting estimators\n if not self.is_log_normal:\n if self.investment_horizon is not None:\n raise ValueError(\n \"`investment_horizon` must be `None` when \"\n \"`is_log_normal` is `False`\"\n )\n # Expected returns\n # noinspection PyArgumentList\n self.mu_estimator_.fit(X, y, **routed_params.mu_estimator.fit)\n mu = self.mu_estimator_.mu_\n\n # Covariance\n # noinspection PyArgumentList\n self.covariance_estimator_.fit(\n X, y, **routed_params.covariance_estimator.fit\n )\n covariance = self.covariance_estimator_.covariance_\n else:\n if self.investment_horizon is None:\n raise ValueError(\n \"`investment_horizon` must be provided when \"\n \"`is_log_normal` is `True`\"\n )\n # Convert linear returns to log returns\n X_log = np.log(1 + X)\n y_log = np.log(1 + y) if y is not None else None\n\n # Estimates the moments on the log returns\n # Expected returns\n # noinspection PyArgumentList\n self.mu_estimator_.fit(X_log, y_log, **routed_params.mu_estimator.fit)\n mu = self.mu_estimator_.mu_\n\n # Covariance\n # noinspection PyArgumentList\n self.covariance_estimator_.fit(\n X_log, y_log, **routed_params.covariance_estimator.fit\n )\n covariance = self.covariance_estimator_.covariance_\n\n # Using the property of aggregation across time we scale this distribution\n # to the investment horizon by the “square-root rule”.\n mu *= self.investment_horizon\n covariance *= self.investment_horizon\n\n # We convert it into a distribution of linear returns over the investment\n # horizon\n mu = np.exp(mu + 0.5 * np.diag(covariance))\n covariance = np.outer(mu, mu) * (np.exp(covariance) - 1)\n\n # we validate and convert to numpy after all models have been fitted to keep\n # features names information.\n X = skv.validate_data(self, X)\n self.prior_model_ = PriorModel(\n mu=mu,\n covariance=covariance,\n returns=X,\n )\n return self"}], "type": ["function_empty", "Development"], "node": ["skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.datasets._base.load_sp500_dataset", "skfolio.datasets._base.load_factors_dataset", "skfolio.prior._empirical.EmpiricalPrior.get_metadata_routing", "skfolio.prior._empirical.EmpiricalPrior.fit"], "language": "Python", "toolfunc_count": 3, "func_count": 5, "pytest_info": {"total_num": 8, "base_passed_num": 0}} {"id": ["skfolio.src.skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.src.skfolio.datasets._base.load_sp500_dataset", "skfolio.src.skfolio.measures._measures.semi_variance", "skfolio.src.skfolio.measures._measures.semi_deviation"], "project": "skfolio", "origin_file": ["skfolio/datasets/_base.py", "skfolio/datasets/_base.py", "skfolio/measures/_measures.py", "skfolio/measures/_measures.py"], "test_list": ["tests/test_population/test_population.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 71, "func_end_lineno": 113, "func_code": "def load_gzip_compressed_csv_data(\n data_filename: str,\n data_module: str = DATA_MODULE,\n encoding=\"utf-8\",\n datetime_index: bool = True,\n) -> pd.DataFrame:\n \"\"\"Load gzip-compressed csv files with `importlib.resources`.\n\n 1) Open resource file with `importlib.resources.open_binary`\n 2) Decompress csv file with `gzip.open`\n 3) Load decompressed data with `pd.read_csv`\n\n Parameters\n ----------\n data_filename : str\n Name of gzip-compressed csv file (`'*.csv.gz'`) to be loaded from\n `data_module/data_file_name`. For example `'SPX500.csv.gz'`.\n\n data_module : str or module, default='skfolio.datasets.data'\n Module where data lives. The default is `'skfolio.datasets.data'`.\n\n encoding : str, default=\"utf-8\"\n Name of the encoding that the gzip-decompressed file will be\n decoded with. The default is 'utf-8'.\n\n datetime_index: bool, default=True\n If this is set to True, the DataFrame index is converted to datetime with\n format=\"%Y-%m-%d\".\n The default is `True`.\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n DataFrame with each row representing one observation and each column\n representing the asset price of a given observation.\n \"\"\"\n path = resources.files(data_module).joinpath(data_filename)\n with path.open(\"rb\") as compressed_file:\n compressed_file = gzip.open(compressed_file, mode=\"rt\", encoding=encoding)\n df = pd.read_csv(compressed_file, sep=\",\", index_col=0)\n if datetime_index:\n df.index = pd.to_datetime(df.index, format=\"%Y-%m-%d\")\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 168, "func_end_lineno": 204, "func_code": "def load_sp500_dataset() -> pd.DataFrame:\n \"\"\"Load the prices of 20 assets from the S&P 500 Index composition.\n\n This dataset is composed of the daily prices of 20 assets from the S&P 500\n composition starting from 1990-01-02 up to 2022-12-28.\n\n The data comes from the Yahoo public API.\n The price is the adjusted close which is the closing price after adjustments for\n all applicable splits and dividend distributions.\n The adjustment uses appropriate split and dividend multipliers, adhering to\n the Center for Research in Security Prices (CRSP) standards.\n\n ============== ==================\n Observations 8313\n Assets 20\n ============== ==================\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n Prices DataFrame\n\n Examples\n --------\n >>> from skfolio.datasets import load_sp500_dataset\n >>> prices = load_sp500_dataset()\n >>> prices.head()\n AAPL AMD BAC ... UNH WMT XOM\n 1990-01-02 0.332589 4.1250 11.65625 ... 0.382813 5.890625 12.5000\n 1990-01-03 0.334821 4.0000 11.75000 ... 0.375000 5.890625 12.3750\n 1990-01-04 0.335938 3.9375 11.50000 ... 0.371094 5.859375 12.2500\n 1990-01-05 0.337054 3.8125 11.25000 ... 0.355469 5.796875 12.1875\n 1990-01-08 0.339286 3.8125 11.31250 ... 0.347656 5.875000 12.3750\n \"\"\"\n data_filename = \"sp500_dataset.csv.gz\"\n df = load_gzip_compressed_csv_data(data_filename)\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 633, "func_start_lineno": 98, "func_end_lineno": 124, "func_code": "def semi_variance(\n returns: np.ndarray, min_acceptable_return: float | None = None\n) -> float:\n \"\"\"Compute the semi-variance (second lower partial moment).\n\n The semi-variance is the variance of the returns below a minimum acceptable return.\n\n Parameters\n ----------\n returns : ndarray of shape (n_observations,)\n Vector of returns\n\n min_acceptable_return : float, optional\n Minimum acceptable return. It is the return target to distinguish \"downside\" and\n \"upside\" returns.\n The default (`None`) is to use the mean.\n\n Returns\n -------\n value : float\n Semi-variance.\n \"\"\"\n if min_acceptable_return is None:\n min_acceptable_return = np.mean(returns, axis=0)\n return np.sum(np.power(np.minimum(0, returns - min_acceptable_return), 2)) / (\n len(returns) - 1\n )"}, {"class_start_lineno": 1, "class_end_lineno": 633, "func_start_lineno": 143, "func_end_lineno": 166, "func_code": "def semi_deviation(\n returns: np.ndarray, min_acceptable_return: float | None = None\n) -> float:\n \"\"\"Compute the semi standard-deviation (semi-deviation) (square root of the second lower\n partial moment).\n\n Parameters\n ----------\n returns : ndarray of shape (n_observations,)\n Vector of returns.\n\n min_acceptable_return : float, optional\n Minimum acceptable return. It is the return target to distinguish \"downside\" and\n \"upside\" returns.\n The default (`None`) is to use the returns mean.\n\n Returns\n -------\n value : float\n Semi-standard-deviation.\n \"\"\"\n return np.sqrt(\n semi_variance(returns=returns, min_acceptable_return=min_acceptable_return)\n )"}], "type": ["function_empty"], "node": ["skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.datasets._base.load_sp500_dataset", "skfolio.measures._measures.semi_variance", "skfolio.measures._measures.semi_deviation"], "language": "Python", "toolfunc_count": 4, "func_count": 4, "pytest_info": {"total_num": 10, "base_passed_num": 0}} {"id": ["skfolio.src.skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.src.skfolio.datasets._base.load_sp500_dataset", "skfolio.src.skfolio.measures._measures.variance", "skfolio.src.skfolio.measures._measures.standard_deviation"], "project": "skfolio", "origin_file": ["skfolio/datasets/_base.py", "skfolio/datasets/_base.py", "skfolio/measures/_measures.py", "skfolio/measures/_measures.py"], "test_list": ["tests/test_portfolio/test_multi_period_portfolio.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 71, "func_end_lineno": 113, "func_code": "def load_gzip_compressed_csv_data(\n data_filename: str,\n data_module: str = DATA_MODULE,\n encoding=\"utf-8\",\n datetime_index: bool = True,\n) -> pd.DataFrame:\n \"\"\"Load gzip-compressed csv files with `importlib.resources`.\n\n 1) Open resource file with `importlib.resources.open_binary`\n 2) Decompress csv file with `gzip.open`\n 3) Load decompressed data with `pd.read_csv`\n\n Parameters\n ----------\n data_filename : str\n Name of gzip-compressed csv file (`'*.csv.gz'`) to be loaded from\n `data_module/data_file_name`. For example `'SPX500.csv.gz'`.\n\n data_module : str or module, default='skfolio.datasets.data'\n Module where data lives. The default is `'skfolio.datasets.data'`.\n\n encoding : str, default=\"utf-8\"\n Name of the encoding that the gzip-decompressed file will be\n decoded with. The default is 'utf-8'.\n\n datetime_index: bool, default=True\n If this is set to True, the DataFrame index is converted to datetime with\n format=\"%Y-%m-%d\".\n The default is `True`.\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n DataFrame with each row representing one observation and each column\n representing the asset price of a given observation.\n \"\"\"\n path = resources.files(data_module).joinpath(data_filename)\n with path.open(\"rb\") as compressed_file:\n compressed_file = gzip.open(compressed_file, mode=\"rt\", encoding=encoding)\n df = pd.read_csv(compressed_file, sep=\",\", index_col=0)\n if datetime_index:\n df.index = pd.to_datetime(df.index, format=\"%Y-%m-%d\")\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 168, "func_end_lineno": 204, "func_code": "def load_sp500_dataset() -> pd.DataFrame:\n \"\"\"Load the prices of 20 assets from the S&P 500 Index composition.\n\n This dataset is composed of the daily prices of 20 assets from the S&P 500\n composition starting from 1990-01-02 up to 2022-12-28.\n\n The data comes from the Yahoo public API.\n The price is the adjusted close which is the closing price after adjustments for\n all applicable splits and dividend distributions.\n The adjustment uses appropriate split and dividend multipliers, adhering to\n the Center for Research in Security Prices (CRSP) standards.\n\n ============== ==================\n Observations 8313\n Assets 20\n ============== ==================\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n Prices DataFrame\n\n Examples\n --------\n >>> from skfolio.datasets import load_sp500_dataset\n >>> prices = load_sp500_dataset()\n >>> prices.head()\n AAPL AMD BAC ... UNH WMT XOM\n 1990-01-02 0.332589 4.1250 11.65625 ... 0.382813 5.890625 12.5000\n 1990-01-03 0.334821 4.0000 11.75000 ... 0.375000 5.890625 12.3750\n 1990-01-04 0.335938 3.9375 11.50000 ... 0.371094 5.859375 12.2500\n 1990-01-05 0.337054 3.8125 11.25000 ... 0.355469 5.796875 12.1875\n 1990-01-08 0.339286 3.8125 11.31250 ... 0.347656 5.875000 12.3750\n \"\"\"\n data_filename = \"sp500_dataset.csv.gz\"\n df = load_gzip_compressed_csv_data(data_filename)\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 633, "func_start_lineno": 82, "func_end_lineno": 95, "func_code": "def variance(returns: np.ndarray) -> float:\n \"\"\"Compute the variance (second moment).\n\n Parameters\n ----------\n returns : ndarray of shape (n_observations,)\n Vector of returns.\n\n Returns\n -------\n value : float\n Variance.\n \"\"\"\n return returns.var(ddof=1)"}, {"class_start_lineno": 1, "class_end_lineno": 633, "func_start_lineno": 127, "func_end_lineno": 140, "func_code": "def standard_deviation(returns: np.ndarray) -> float:\n \"\"\"Compute the standard-deviation (square root of the second moment).\n\n Parameters\n ----------\n returns : ndarray of shape (n_observations,)\n Vector of returns.\n\n Returns\n -------\n value : float\n Standard-deviation.\n \"\"\"\n return np.sqrt(variance(returns=returns))"}], "type": ["function_empty"], "node": ["skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.datasets._base.load_sp500_dataset", "skfolio.measures._measures.variance", "skfolio.measures._measures.standard_deviation"], "language": "Python", "toolfunc_count": 4, "func_count": 4, "pytest_info": {"total_num": 106, "base_passed_num": 0}} {"id": ["skfolio.src.skfolio.utils.tools.safe_indexing", "skfolio.src.skfolio.utils.tools.safe_split", "skfolio.src.skfolio.model_selection._validation.cross_val_predict"], "project": "skfolio", "origin_file": ["skfolio/utils/tools.py", "skfolio/utils/tools.py", "skfolio/model_selection/_validation.py"], "test_list": ["tests/test_pre_selection/test_select_non_expiring.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 787, "func_start_lineno": 190, "func_end_lineno": 219, "func_code": "def safe_indexing(\n X: npt.ArrayLike | pd.DataFrame, indices: npt.ArrayLike | None, axis: int = 0\n):\n \"\"\"Return rows, items or columns of X using indices.\n\n Parameters\n ----------\n X : array-like\n Data from which to sample rows.\n\n indices : array-like, optional\n Indices of rows or columns.\n The default (`None`) is to select the entire data.\n\n axis : int, default=0\n The axis along which `X` will be sub-sampled. `axis=0` will select\n rows while `axis=1` will select columns.\n\n Returns\n -------\n subset :\n Subset of X on axis 0.\n \"\"\"\n if indices is None:\n return X\n if hasattr(X, \"iloc\"):\n return X.take(indices, axis=axis)\n if axis == 0:\n return X[indices]\n return X[:, indices]"}, {"class_start_lineno": 1, "class_end_lineno": 787, "func_start_lineno": 222, "func_end_lineno": 261, "func_code": "def safe_split(\n X: npt.ArrayLike,\n y: npt.ArrayLike | None = None,\n indices: np.ndarray | None = None,\n axis: int = 0,\n):\n \"\"\"Create subset of dataset.\n\n Slice X, y according to indices for cross-validation.\n\n Parameters\n ----------\n X : array-like\n Data to be indexed.\n\n y : array-like\n Data to be indexed.\n\n indices : ndarray of int, optional\n Rows or columns to select from X and y.\n The default (`None`) is to select the entire data.\n\n axis : int, default=0\n The axis along which `X` will be sub-sampled. `axis=0` will select\n rows while `axis=1` will select columns.\n\n Returns\n -------\n X_subset : array-like\n Indexed data.\n\n y_subset : array-like\n Indexed targets.\n \"\"\"\n X_subset = safe_indexing(X, indices=indices, axis=axis)\n if y is not None:\n y_subset = safe_indexing(y, indices=indices, axis=axis)\n else:\n y_subset = None\n return X_subset, y_subset"}, {"class_start_lineno": 1, "class_end_lineno": 254, "func_start_lineno": 38, "func_end_lineno": 254, "func_code": "def cross_val_predict(\n estimator: skb.BaseEstimator,\n X: npt.ArrayLike,\n y: npt.ArrayLike = None,\n cv: sks.BaseCrossValidator | BaseCombinatorialCV | int | None = None,\n n_jobs: int | None = None,\n method: str = \"predict\",\n verbose: int = 0,\n params: dict | None = None,\n pre_dispatch: str = \"2*n_jobs\",\n column_indices: np.ndarray | None = None,\n portfolio_params: dict | None = None,\n) -> MultiPeriodPortfolio | Population:\n \"\"\"Generate cross-validated `Portfolios` estimates.\n\n The data is split according to the `cv` parameter.\n The optimization estimator is fitted on the training set and portfolios are\n predicted on the corresponding test set.\n\n For non-combinatorial cross-validation like `Kfold`, the output is the predicted\n :class:`~skfolio.portfolio.MultiPeriodPortfolio` where\n each :class:`~skfolio.portfolio.Portfolio` corresponds to the prediction on each\n train/test pair (`k` portfolios for `Kfold`).\n\n For combinatorial cross-validation\n like :class:`~skfolio.model_selection.CombinatorialPurgedCV`, the output is the\n predicted :class:`~skfolio.population.Population` of multiple\n :class:`~skfolio.portfolio.MultiPeriodPortfolio` (each test outputs are a\n collection of multiple paths instead of one single path).\n\n Parameters\n ----------\n estimator : BaseOptimization\n :ref:`Optimization estimators ` use to fit the data.\n\n X : array-like of shape (n_observations, n_assets)\n Price returns of the assets.\n\n y : array-like of shape (n_observations, n_targets), optional\n Target data (optional).\n For example, the price returns of the factors.\n\n cv : int | cross-validation generator, optional\n Determines the cross-validation splitting strategy.\n Possible inputs for cv are:\n\n * None, to use the default 5-fold cross validation,\n * int, to specify the number of folds in a `(Stratified)KFold`,\n * `CV splitter`,\n * An iterable that generates (train, test) splits as arrays of indices.\n\n n_jobs : int, optional\n The number of jobs to run in parallel for `fit` of all `estimators`.\n `None` means 1 unless in a `joblib.parallel_backend` context. -1 means\n using all processors.\n\n method : str\n Invokes the passed method name of the passed estimator.\n\n verbose : int, default=0\n The verbosity level.\n\n params : dict, optional\n Parameters to pass to the underlying estimator's ``fit`` and the CV splitter.\n\n pre_dispatch : int or str, default='2*n_jobs'\n Controls the number of jobs that get dispatched during parallel\n execution. Reducing this number can be useful to avoid an\n explosion of memory consumption when more jobs get dispatched\n than CPUs can process. This parameter can be:\n\n * None, in which case all the jobs are immediately\n created and spawned. Use this for lightweight and\n fast-running jobs, to avoid delays due to on-demand\n spawning of the jobs\n\n * An int, giving the exact number of total jobs that are\n spawned\n\n * A str, giving an expression as a function of n_jobs,\n as in '2*n_jobs'\n\n column_indices : ndarray, optional\n Indices of the `X` columns to cross-validate on.\n\n portfolio_params : dict, optional\n Additional portfolio parameters passed to `MultiPeriodPortfolio`.\n\n Returns\n -------\n predictions : MultiPeriodPortfolio | Population\n This is the result of calling `predict`\n \"\"\"\n params = {} if params is None else params\n\n X, y = safe_split(X, y, indices=column_indices, axis=1)\n X, y = sku.indexable(X, y)\n\n if _routing_enabled():\n # For estimators, a MetadataRouter is created in get_metadata_routing\n # methods. For these router methods, we create the router to use\n # `process_routing` on it.\n # noinspection PyTypeChecker\n router = (\n skm.MetadataRouter(owner=\"cross_validate\")\n .add(\n splitter=cv,\n method_mapping=skm.MethodMapping().add(caller=\"fit\", callee=\"split\"),\n )\n .add(\n estimator=estimator,\n method_mapping=skm.MethodMapping().add(caller=\"fit\", callee=\"fit\"),\n )\n )\n try:\n routed_params = skm.process_routing(router, \"fit\", **params)\n except ske.UnsetMetadataPassedError as e:\n # The default exception would mention `fit` since in the above\n # `process_routing` code, we pass `fit` as the caller. However,\n # the user is not calling `fit` directly, so we change the message\n # to make it more suitable for this case.\n unrequested_params = sorted(e.unrequested_params)\n raise ske.UnsetMetadataPassedError(\n message=(\n f\"{unrequested_params} are passed to `cross_val_predict` but are\"\n \" not explicitly set as requested or not requested for\"\n f\" cross_validate's estimator: {estimator.__class__.__name__} Call\"\n \" `.set_fit_request({{metadata}}=True)` on the estimator for\"\n f\" each metadata in {unrequested_params} that you want to use and\"\n \" `metadata=False` for not using it. See the Metadata Routing User\"\n \" guide \"\n \" for more information.\"\n ),\n unrequested_params=e.unrequested_params,\n routed_params=e.routed_params,\n ) from None\n else:\n routed_params = sku.Bunch()\n routed_params.splitter = sku.Bunch(split={})\n routed_params.estimator = sku.Bunch(fit=params)\n\n cv = sks.check_cv(cv, y)\n splits = list(cv.split(X, y, **routed_params.splitter.split))\n\n portfolio_params = {} if portfolio_params is None else portfolio_params.copy()\n\n # We ensure that the folds are not shuffled\n if not isinstance(cv, BaseCombinatorialCV):\n try:\n if cv.shuffle:\n raise ValueError(\n \"`cross_val_predict` only works with cross-validation setting\"\n \" `shuffle=False`\"\n )\n except AttributeError:\n # If we cannot find the attribute shuffle, we check if the first folds\n # are shuffled\n for fold in splits[0]:\n if not np.all(np.diff(fold) > 0):\n raise ValueError(\n \"`cross_val_predict` only works with un-shuffled folds\"\n ) from None\n\n # We clone the estimator to make sure that all the folds are independent\n # and that it is pickle-able.\n parallel = skp.Parallel(n_jobs=n_jobs, verbose=verbose, pre_dispatch=pre_dispatch)\n # TODO remove when https://github.com/joblib/joblib/issues/1071 is fixed\n # noinspection PyCallingNonCallable\n predictions = parallel(\n skp.delayed(fit_and_predict)(\n sk.clone(estimator),\n X,\n y,\n train=train,\n test=test,\n fit_params=routed_params.estimator.fit,\n method=method,\n )\n for train, test in splits\n )\n\n if isinstance(cv, BaseCombinatorialCV):\n path_ids = cv.get_path_ids()\n path_nb = np.max(path_ids) + 1\n portfolios = [[] for _ in range(path_nb)]\n for i, prediction in enumerate(predictions):\n for j, p in enumerate(prediction):\n path_id = path_ids[i, j]\n portfolios[path_id].append(p)\n name = portfolio_params.pop(\"name\", \"path\")\n pred = Population(\n [\n MultiPeriodPortfolio(\n name=f\"{name}_{i}\", portfolios=portfolios[i], **portfolio_params\n )\n for i in range(path_nb)\n ]\n )\n else:\n # We need to re-order the test folds in case they were un-ordered by the\n # CV generator.\n # Because the tests folds are not shuffled, we use the first index of each\n # fold to order them.\n test_indices = np.concatenate([test for _, test in splits])\n if np.unique(test_indices, axis=0).shape[0] != test_indices.shape[0]:\n raise ValueError(\n \"`cross_val_predict` only works with non-duplicated test indices\"\n )\n test_indices = [test for _, test in splits]\n sorted_fold_id = np.argsort([x[0] for x in test_indices])\n pred = MultiPeriodPortfolio(\n portfolios=[predictions[fold_id] for fold_id in sorted_fold_id],\n check_observations_order=False,\n **portfolio_params,\n )\n\n return pred"}], "type": ["function_empty"], "node": ["skfolio.utils.tools.safe_indexing", "skfolio.utils.tools.safe_split", "skfolio.model_selection._validation.cross_val_predict"], "language": "Python", "toolfunc_count": 3, "func_count": 3, "pytest_info": {"total_num": 2, "base_passed_num": 1}} {"id": ["skfolio.src.skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.src.skfolio.datasets._base.load_factors_dataset", "skfolio.src.skfolio.datasets._base.load_sp500_dataset"], "project": "skfolio", "origin_file": ["skfolio/datasets/_base.py", "skfolio/datasets/_base.py", "skfolio/datasets/_base.py"], "test_list": ["tests/test_preprocessing/test_returns.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 71, "func_end_lineno": 113, "func_code": "def load_gzip_compressed_csv_data(\n data_filename: str,\n data_module: str = DATA_MODULE,\n encoding=\"utf-8\",\n datetime_index: bool = True,\n) -> pd.DataFrame:\n \"\"\"Load gzip-compressed csv files with `importlib.resources`.\n\n 1) Open resource file with `importlib.resources.open_binary`\n 2) Decompress csv file with `gzip.open`\n 3) Load decompressed data with `pd.read_csv`\n\n Parameters\n ----------\n data_filename : str\n Name of gzip-compressed csv file (`'*.csv.gz'`) to be loaded from\n `data_module/data_file_name`. For example `'SPX500.csv.gz'`.\n\n data_module : str or module, default='skfolio.datasets.data'\n Module where data lives. The default is `'skfolio.datasets.data'`.\n\n encoding : str, default=\"utf-8\"\n Name of the encoding that the gzip-decompressed file will be\n decoded with. The default is 'utf-8'.\n\n datetime_index: bool, default=True\n If this is set to True, the DataFrame index is converted to datetime with\n format=\"%Y-%m-%d\".\n The default is `True`.\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n DataFrame with each row representing one observation and each column\n representing the asset price of a given observation.\n \"\"\"\n path = resources.files(data_module).joinpath(data_filename)\n with path.open(\"rb\") as compressed_file:\n compressed_file = gzip.open(compressed_file, mode=\"rt\", encoding=encoding)\n df = pd.read_csv(compressed_file, sep=\",\", index_col=0)\n if datetime_index:\n df.index = pd.to_datetime(df.index, format=\"%Y-%m-%d\")\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 247, "func_end_lineno": 292, "func_code": "def load_factors_dataset() -> pd.DataFrame:\n \"\"\"Load the prices of 5 factor ETFs.\n\n This dataset is composed of the daily prices of 5 ETF representing common factors\n starting from 2014-01-02 up to 2022-12-28.\n\n The factors are:\n\n * \"MTUM\": Momentum\n * \"QUAL\": Quality\n * \"SIZE\": Size\n * \"VLUE\": Value\n * \"USMV\": low volatility\n\n The data comes from the Yahoo public API.\n The price is the adjusted close which is the closing price after adjustments for\n all applicable splits and dividend distributions.\n The adjustment uses appropriate split and dividend multipliers, adhering to\n the Center for Research in Security Prices (CRSP) standards.\n\n ============== ==================\n Observations 2264\n Assets 5\n ============== ==================\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n Prices DataFrame\n\n Examples\n --------\n >>> from skfolio.datasets import load_factors_dataset\n >>> prices = load_factors_dataset()\n >>> prices.head()\n MTUM QUAL SIZE USMV VLUE\n Date\n 2014-01-02 52.704 48.351 48.986 29.338 47.054\n 2014-01-03 52.792 48.256 48.722 29.330 46.999\n 2014-01-06 52.677 48.067 48.722 29.263 46.991\n 2014-01-07 53.112 48.455 48.731 29.430 47.253\n 2014-01-08 53.502 48.437 48.731 29.422 47.253\n \"\"\"\n data_filename = \"factors_dataset.csv.gz\"\n df = load_gzip_compressed_csv_data(data_filename)\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 168, "func_end_lineno": 204, "func_code": "def load_sp500_dataset() -> pd.DataFrame:\n \"\"\"Load the prices of 20 assets from the S&P 500 Index composition.\n\n This dataset is composed of the daily prices of 20 assets from the S&P 500\n composition starting from 1990-01-02 up to 2022-12-28.\n\n The data comes from the Yahoo public API.\n The price is the adjusted close which is the closing price after adjustments for\n all applicable splits and dividend distributions.\n The adjustment uses appropriate split and dividend multipliers, adhering to\n the Center for Research in Security Prices (CRSP) standards.\n\n ============== ==================\n Observations 8313\n Assets 20\n ============== ==================\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n Prices DataFrame\n\n Examples\n --------\n >>> from skfolio.datasets import load_sp500_dataset\n >>> prices = load_sp500_dataset()\n >>> prices.head()\n AAPL AMD BAC ... UNH WMT XOM\n 1990-01-02 0.332589 4.1250 11.65625 ... 0.382813 5.890625 12.5000\n 1990-01-03 0.334821 4.0000 11.75000 ... 0.375000 5.890625 12.3750\n 1990-01-04 0.335938 3.9375 11.50000 ... 0.371094 5.859375 12.2500\n 1990-01-05 0.337054 3.8125 11.25000 ... 0.355469 5.796875 12.1875\n 1990-01-08 0.339286 3.8125 11.31250 ... 0.347656 5.875000 12.3750\n \"\"\"\n data_filename = \"sp500_dataset.csv.gz\"\n df = load_gzip_compressed_csv_data(data_filename)\n return df"}], "type": ["function_empty"], "node": ["skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.datasets._base.load_factors_dataset", "skfolio.datasets._base.load_sp500_dataset"], "language": "Python", "toolfunc_count": 3, "func_count": 3, "pytest_info": {"total_num": 2, "base_passed_num": 0}} {"id": ["skfolio.src.skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.src.skfolio.datasets._base.load_sp500_dataset", "skfolio.src.skfolio.utils.equations._validate_groups", "skfolio.src.skfolio.utils.equations.equations_to_matrix"], "project": "skfolio", "origin_file": ["skfolio/datasets/_base.py", "skfolio/datasets/_base.py", "skfolio/utils/equations.py", "skfolio/utils/equations.py"], "test_list": ["tests/test_prior/test_black_litterman.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 71, "func_end_lineno": 113, "func_code": "def load_gzip_compressed_csv_data(\n data_filename: str,\n data_module: str = DATA_MODULE,\n encoding=\"utf-8\",\n datetime_index: bool = True,\n) -> pd.DataFrame:\n \"\"\"Load gzip-compressed csv files with `importlib.resources`.\n\n 1) Open resource file with `importlib.resources.open_binary`\n 2) Decompress csv file with `gzip.open`\n 3) Load decompressed data with `pd.read_csv`\n\n Parameters\n ----------\n data_filename : str\n Name of gzip-compressed csv file (`'*.csv.gz'`) to be loaded from\n `data_module/data_file_name`. For example `'SPX500.csv.gz'`.\n\n data_module : str or module, default='skfolio.datasets.data'\n Module where data lives. The default is `'skfolio.datasets.data'`.\n\n encoding : str, default=\"utf-8\"\n Name of the encoding that the gzip-decompressed file will be\n decoded with. The default is 'utf-8'.\n\n datetime_index: bool, default=True\n If this is set to True, the DataFrame index is converted to datetime with\n format=\"%Y-%m-%d\".\n The default is `True`.\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n DataFrame with each row representing one observation and each column\n representing the asset price of a given observation.\n \"\"\"\n path = resources.files(data_module).joinpath(data_filename)\n with path.open(\"rb\") as compressed_file:\n compressed_file = gzip.open(compressed_file, mode=\"rt\", encoding=encoding)\n df = pd.read_csv(compressed_file, sep=\",\", index_col=0)\n if datetime_index:\n df.index = pd.to_datetime(df.index, format=\"%Y-%m-%d\")\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 168, "func_end_lineno": 204, "func_code": "def load_sp500_dataset() -> pd.DataFrame:\n \"\"\"Load the prices of 20 assets from the S&P 500 Index composition.\n\n This dataset is composed of the daily prices of 20 assets from the S&P 500\n composition starting from 1990-01-02 up to 2022-12-28.\n\n The data comes from the Yahoo public API.\n The price is the adjusted close which is the closing price after adjustments for\n all applicable splits and dividend distributions.\n The adjustment uses appropriate split and dividend multipliers, adhering to\n the Center for Research in Security Prices (CRSP) standards.\n\n ============== ==================\n Observations 8313\n Assets 20\n ============== ==================\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n Prices DataFrame\n\n Examples\n --------\n >>> from skfolio.datasets import load_sp500_dataset\n >>> prices = load_sp500_dataset()\n >>> prices.head()\n AAPL AMD BAC ... UNH WMT XOM\n 1990-01-02 0.332589 4.1250 11.65625 ... 0.382813 5.890625 12.5000\n 1990-01-03 0.334821 4.0000 11.75000 ... 0.375000 5.890625 12.3750\n 1990-01-04 0.335938 3.9375 11.50000 ... 0.371094 5.859375 12.2500\n 1990-01-05 0.337054 3.8125 11.25000 ... 0.355469 5.796875 12.1875\n 1990-01-08 0.339286 3.8125 11.31250 ... 0.347656 5.875000 12.3750\n \"\"\"\n data_filename = \"sp500_dataset.csv.gz\"\n df = load_gzip_compressed_csv_data(data_filename)\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 499, "func_start_lineno": 195, "func_end_lineno": 226, "func_code": "def _validate_groups(groups: npt.ArrayLike, name: str = \"groups\") -> np.ndarray:\n \"\"\"Validate groups by checking its dim and if group names don't appear in multiple\n levels and convert to numpy array.\n\n Parameters\n ----------\n groups : array-like of shape (n_groups, n_assets)\n 2D-array of strings.\n\n Returns\n -------\n groups : ndarray of shape (n_groups, n_assets)\n 2D-array of strings.\n \"\"\"\n groups = np.asarray(groups)\n if groups.ndim != 2:\n raise ValueError(\n f\"`{name} must be a 2D array, got {groups.ndim}D array instead.\"\n )\n n = len(groups)\n group_sets = [set(groups[i]) for i in range(n)]\n for i in range(n - 1):\n for e in group_sets[i]:\n for j in range(i + 1, n):\n if e in group_sets[j]:\n raise DuplicateGroupsError(\n f\"'{e}' appear in two levels: {list(groups[i])} \"\n f\"and {list(groups[i])}. \"\n f\"{name} must be in only one level.\"\n )\n\n return groups"}, {"class_start_lineno": 1, "class_end_lineno": 499, "func_start_lineno": 32, "func_end_lineno": 134, "func_code": "def equations_to_matrix(\n groups: npt.ArrayLike,\n equations: npt.ArrayLike,\n sum_to_one: bool = False,\n raise_if_group_missing: bool = False,\n names: tuple[str, str] = (\"groups\", \"equations\"),\n) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:\n \"\"\"Convert a list of linear equations into the left and right matrices of the\n inequality A <= B and equality A == B.\n\n Parameters\n ----------\n groups : array-like of shape (n_groups, n_assets)\n 2D array of assets groups.\n\n For example:\n\n groups = np.array(\n [\n [\"SPX\", \"SX5E\", \"NKY\", \"TLT\"],\n [\"Equity\", \"Equity\", \"Equity\", \"Bond\"],\n [\"US\", \"Europe\", \"Japan\", \"US\"],\n ]\n )\n\n equations : array-like of shape (n_equations,)\n 1D array of equations.\n\n Example of valid equation patterns:\n * \"number_1 * group_1 + number_3 <= number_4 * group_3 + number_5\"\n * \"group_1 == number * group_2\"\n * \"group_1 <= number\"\n * \"group_1 == number\"\n\n \"group_1\" and \"group_2\" are the group names defined in `groups`.\n The second expression means that the sum of all assets in \"group_1\" should be\n less or equal to \"number\" times the sum of all assets in \"group_2\".\n\n For example:\n\n equations = [\n \"Equity <= 3 * Bond\",\n \"US >= 1.5\",\n \"Europe >= 0.5 * Japan\",\n \"Japan == 1\",\n \"3*SPX + 5*SX5E == 2*TLT + 3\",\n ]\n\n sum_to_one : bool\n If this is set to True, all elements in a group sum to one (used in the `views`\n of the Black-Litterman model).\n\n raise_if_group_missing : bool, default=False\n If this is set to True, an error is raised when a group is not found in the\n groups, otherwise only a warning is shown.\n The default is False.\n\n names : tuple[str, str], default=('groups', 'equations')\n The group and equation names used in error messages.\n The default is `('groups', 'equations')`.\n\n Returns\n -------\n left_equality: ndarray of shape (n_equations_equality, n_assets)\n right_equality: ndarray of shape (n_equations_equality,)\n The left and right matrices of the inequality A <= B.\n\n left_inequality: ndarray of shape (n_equations_inequality, n_assets)\n right_inequality: ndarray of shape (n_equations_inequality,)\n The left and right matrices of the equality A == B.\n \"\"\"\n groups = _validate_groups(groups, name=names[0])\n equations = _validate_equations(equations, name=names[1])\n\n a_equality = []\n b_equality = []\n\n a_inequality = []\n b_inequality = []\n\n for string in equations:\n try:\n left, right, is_inequality = _string_to_equation(\n groups=groups,\n string=string,\n sum_to_one=sum_to_one,\n )\n if is_inequality:\n a_inequality.append(left)\n b_inequality.append(right)\n else:\n a_equality.append(left)\n b_equality.append(right)\n except GroupNotFoundError as e:\n if raise_if_group_missing:\n raise\n warnings.warn(str(e), stacklevel=2)\n return (\n np.array(a_equality),\n np.array(b_equality),\n np.array(a_inequality),\n np.array(b_inequality),\n )"}], "type": ["function_empty", "Development"], "node": ["skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.datasets._base.load_sp500_dataset", "skfolio.utils.equations._validate_groups", "skfolio.utils.equations.equations_to_matrix"], "language": "Python", "toolfunc_count": 3, "func_count": 4, "pytest_info": {"total_num": 4, "base_passed_num": 0}} {"id": ["skfolio.src.skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.src.skfolio.datasets._base.load_sp500_dataset", "skfolio.src.skfolio.distribution.multivariate._utils.ChildNode::central", "skfolio.src.skfolio.distribution.multivariate._utils.Tree::set_edges_from_mst"], "project": "skfolio", "origin_file": ["skfolio/datasets/_base.py", "skfolio/datasets/_base.py", "skfolio/distribution/multivariate/_utils.py", "skfolio/distribution/multivariate/_utils.py", "skfolio/distribution/multivariate/_utils.py"], "test_list": ["tests/test_prior/test_synthetic_data.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 71, "func_end_lineno": 113, "func_code": "def load_gzip_compressed_csv_data(\n data_filename: str,\n data_module: str = DATA_MODULE,\n encoding=\"utf-8\",\n datetime_index: bool = True,\n) -> pd.DataFrame:\n \"\"\"Load gzip-compressed csv files with `importlib.resources`.\n\n 1) Open resource file with `importlib.resources.open_binary`\n 2) Decompress csv file with `gzip.open`\n 3) Load decompressed data with `pd.read_csv`\n\n Parameters\n ----------\n data_filename : str\n Name of gzip-compressed csv file (`'*.csv.gz'`) to be loaded from\n `data_module/data_file_name`. For example `'SPX500.csv.gz'`.\n\n data_module : str or module, default='skfolio.datasets.data'\n Module where data lives. The default is `'skfolio.datasets.data'`.\n\n encoding : str, default=\"utf-8\"\n Name of the encoding that the gzip-decompressed file will be\n decoded with. The default is 'utf-8'.\n\n datetime_index: bool, default=True\n If this is set to True, the DataFrame index is converted to datetime with\n format=\"%Y-%m-%d\".\n The default is `True`.\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n DataFrame with each row representing one observation and each column\n representing the asset price of a given observation.\n \"\"\"\n path = resources.files(data_module).joinpath(data_filename)\n with path.open(\"rb\") as compressed_file:\n compressed_file = gzip.open(compressed_file, mode=\"rt\", encoding=encoding)\n df = pd.read_csv(compressed_file, sep=\",\", index_col=0)\n if datetime_index:\n df.index = pd.to_datetime(df.index, format=\"%Y-%m-%d\")\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 168, "func_end_lineno": 204, "func_code": "def load_sp500_dataset() -> pd.DataFrame:\n \"\"\"Load the prices of 20 assets from the S&P 500 Index composition.\n\n This dataset is composed of the daily prices of 20 assets from the S&P 500\n composition starting from 1990-01-02 up to 2022-12-28.\n\n The data comes from the Yahoo public API.\n The price is the adjusted close which is the closing price after adjustments for\n all applicable splits and dividend distributions.\n The adjustment uses appropriate split and dividend multipliers, adhering to\n the Center for Research in Security Prices (CRSP) standards.\n\n ============== ==================\n Observations 8313\n Assets 20\n ============== ==================\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n Prices DataFrame\n\n Examples\n --------\n >>> from skfolio.datasets import load_sp500_dataset\n >>> prices = load_sp500_dataset()\n >>> prices.head()\n AAPL AMD BAC ... UNH WMT XOM\n 1990-01-02 0.332589 4.1250 11.65625 ... 0.382813 5.890625 12.5000\n 1990-01-03 0.334821 4.0000 11.75000 ... 0.375000 5.890625 12.3750\n 1990-01-04 0.335938 3.9375 11.50000 ... 0.371094 5.859375 12.2500\n 1990-01-05 0.337054 3.8125 11.25000 ... 0.355469 5.796875 12.1875\n 1990-01-08 0.339286 3.8125 11.31250 ... 0.347656 5.875000 12.3750\n \"\"\"\n data_filename = \"sp500_dataset.csv.gz\"\n df = load_gzip_compressed_csv_data(data_filename)\n return df"}, {"class_start_lineno": 160, "class_end_lineno": 324, "func_start_lineno": 191, "func_end_lineno": 202, "func_code": " def central(self) -> bool:\n \"\"\"Determine whether this node is considered central.\n It is inherited from the associated edge's centrality.\n\n Returns\n -------\n central: bool\n True if the node is central; otherwise, False.\n \"\"\"\n if self._central is None:\n self._central = self.ref.strongly_central\n return self._central"}, {"class_start_lineno": 327, "class_end_lineno": 479, "func_start_lineno": 365, "func_end_lineno": 369, "func_code": " def weakly_central(self) -> bool:\n \"\"\"Determine if the edge is weakly central.\n An edge is weakly central if at least one of its two nodes is central.\n \"\"\"\n return self.node1.central or self.node2.central"}, {"class_start_lineno": 482, "class_end_lineno": 591, "func_start_lineno": 520, "func_end_lineno": 582, "func_code": " def set_edges_from_mst(self, dependence_method: DependenceMethod) -> None:\n \"\"\"Construct the Maximum Spanning Tree (MST) from the current nodes using\n the specified dependence method.\n\n The MST is built based on pairwise dependence measures computed between nodes.\n If any edge is (weakly) central, a central factor is added to the dependence\n measure to favor edges connected to central nodes.\n\n Parameters\n ----------\n dependence_method : DependenceMethod\n The method used to compute the dependence measure between nodes (e.g.,\n Kendall's tau).\n\n Returns\n -------\n None\n \"\"\"\n n = len(self.nodes)\n dependence_matrix = np.zeros((n, n))\n eligible_edges = {}\n central = False\n for i, j in combinations(range(n), 2):\n node1 = self.nodes[i]\n node2 = self.nodes[j]\n if self.level == 0 or node1.ref.share_one_node(node2.ref):\n edge = Edge(\n node1=node1, node2=node2, dependence_method=dependence_method\n )\n if not central and edge.weakly_central:\n central = True\n # Negate the matrix to use minimum_spanning_tree for maximum spanning\n # Add a cst to ensure that even if dep is 0, we still build a valid MST\n dep = abs(edge.dependence) + 1e-5\n dependence_matrix[i, j] = dep\n eligible_edges[(i, j)] = edge\n\n if np.any(np.isnan(dependence_matrix)):\n raise RuntimeError(\"dependence_matrix contains NaNs\")\n\n if central:\n max_dep = np.max(dependence_matrix)\n for (i, j), edge in eligible_edges.items():\n if edge.weakly_central:\n if edge.strongly_central:\n central_factor = 3 * max_dep\n else:\n central_factor = 2 * max_dep\n dep = dependence_matrix[i, j] + central_factor\n dependence_matrix[i, j] = dep\n\n # Compute the minimum spanning tree\n mst = ssc.minimum_spanning_tree(-dependence_matrix, overwrite=True)\n\n edges = []\n # Extract the indices of the non-zero entries (edges)\n for i, j in zip(*mst.nonzero(), strict=True):\n edge = eligible_edges[(i, j)]\n # connect Nodes to Edges\n edge.ref_to_nodes()\n edges.append(edge)\n\n self.edges = edges"}], "type": ["function_empty"], "node": ["skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.datasets._base.load_sp500_dataset", "skfolio.distribution.multivariate._utils.ChildNode.central", "skfolio.distribution.multivariate._utils.Edge.weakly_central", "skfolio.distribution.multivariate._utils.Tree.set_edges_from_mst"], "language": "Python", "toolfunc_count": 4, "func_count": 4, "pytest_info": {"total_num": 4, "base_passed_num": 0}} {"id": ["skfolio.src.skfolio.utils.equations._split_equation_string", "skfolio.src.skfolio.utils.equations._string_to_equation", "skfolio.src.skfolio.utils.equations._validate_groups", "skfolio.src.skfolio.utils.equations.equations_to_matrix"], "project": "skfolio", "origin_file": ["skfolio/utils/equations.py", "skfolio/utils/equations.py", "skfolio/utils/equations.py", "skfolio/utils/equations.py"], "test_list": ["tests/test_utils/test_equations.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 499, "func_start_lineno": 347, "func_end_lineno": 371, "func_code": "def _split_equation_string(string: str) -> list[str]:\n \"\"\"Split an equation strings by operators.\"\"\"\n comp_pattern = \"(?=\" + \"|\".join([\".+\\\\\" + e for e in _COMPARISON_OPERATORS]) + \")\"\n if not bool(re.match(comp_pattern, string)):\n raise EquationToMatrixError(\n f\"The string must contains a comparison operator: \"\n f\"{list(_COMPARISON_OPERATORS)}\"\n )\n\n # Regex to match only '>' and '<' but not '<=' or '>='\n invalid_pattern = r\"(?(?!=)|(?)<(?!=)\"\n invalid_matches = re.findall(invalid_pattern, string)\n\n if len(invalid_matches) > 0:\n raise EquationToMatrixError(\n f\"{invalid_matches[0]} is an invalid comparison operator. \"\n f\"Valid comparison operators are: {list(_COMPARISON_OPERATORS)}\"\n )\n\n # '==' needs to be before '='\n operators = sorted(_OPERATORS, reverse=True)\n pattern = \"((?:\" + \"|\".join([\"\\\\\" + e for e in operators]) + \"))\"\n res = [x.strip() for x in re.split(pattern, string)]\n res = [x for x in res if x != \"\"]\n return res"}, {"class_start_lineno": 1, "class_end_lineno": 499, "func_start_lineno": 374, "func_end_lineno": 499, "func_code": "def _string_to_equation(\n groups: np.ndarray,\n string: str,\n sum_to_one: bool,\n) -> tuple[np.ndarray, float, bool]:\n \"\"\"Convert a string to a left 1D-array and right float of the form:\n `groups @ left <= right` or `groups @ left == right` and return whether it's an\n equality or inequality.\n\n Parameters\n ----------\n groups : ndarray of shape (n_groups, n_assets)\n Groups 2D-array\n\n string : str\n String to convert\n\n sum_to_one : bool\n If this is set to True, the 1D-array is scaled to have a sum of one.\n\n Returns\n -------\n left : 1D-array of shape (n_assets,)\n right : float\n is_inequality : bool\n \"\"\"\n n = groups.shape[1]\n err_msg = f\"Wrong pattern encountered while converting the string '{string}'\"\n\n iterator = iter(_split_equation_string(string))\n group_names = set(groups.flatten())\n\n def is_group(name: str) -> bool:\n return name in group_names\n\n left = np.zeros(n)\n right = 0\n main_sign = 1\n comparison_sign = None\n is_inequality = None\n e = next(iterator, None)\n i = 0\n while True:\n i += 1\n if i > 1e6:\n raise RecursionError(err_msg)\n if e is None:\n break\n sign = 1\n if e in _COMPARISON_OPERATORS:\n if e in _INEQUALITY_OPERATORS:\n is_inequality = True\n else:\n is_inequality = False\n main_sign = -1\n comparison_sign = _comparison_operator_sign(e)\n e = next(iterator, None)\n if e in _SUB_ADD_OPERATORS:\n sign *= _sub_add_operator_sign(e)\n e = next(iterator, None)\n elif e in _SUB_ADD_OPERATORS:\n sign *= _sub_add_operator_sign(e)\n e = next(iterator, None)\n elif e in _MUL_OPERATORS:\n raise EquationToMatrixError(\n f\"{err_msg}: the character '{e}' is wrongly positioned\"\n )\n sign *= main_sign\n # next can only be a number or a group\n if e is None or e in _OPERATORS:\n raise EquationToMatrixError(\n f\"{err_msg}: the character '{e}' is wrongly positioned\"\n )\n if is_group(e):\n arr = _matching_array(values=groups, key=e, sum_to_one=sum_to_one)\n # next can only be a '*' or an ['-', '+', '>=', '<=', '==', '='] or None\n e = next(iterator, None)\n if e is None or e in _NON_MUL_OPERATORS:\n left += sign * arr\n elif e in _MUL_OPERATORS:\n # next can only a number\n e = next(iterator, None)\n try:\n number = float(e)\n except ValueError:\n raise GroupNotFoundError(\n f\"{err_msg}: the group '{e}' is missing from the groups\"\n f\" {groups}\"\n ) from None\n\n left += number * sign * arr\n e = next(iterator, None)\n else:\n raise EquationToMatrixError(\n f\"{err_msg}: the character '{e}' is wrongly positioned\"\n )\n else:\n try:\n number = float(e)\n except ValueError:\n raise GroupNotFoundError(\n f\"{err_msg}: the group '{e}' is missing from the groups {groups}\"\n ) from None\n # next can only be a '*' or an operator or None\n e = next(iterator, None)\n if e in _MUL_OPERATORS:\n # next can only a group\n e = next(iterator, None)\n if not is_group(e):\n raise EquationToMatrixError(\n f\"{err_msg}: the character '{e}' is wrongly positioned\"\n )\n arr = _matching_array(values=groups, key=e, sum_to_one=sum_to_one)\n left += number * sign * arr\n e = next(iterator, None)\n elif e is None or e in _NON_MUL_OPERATORS:\n right += number * sign\n else:\n raise EquationToMatrixError(\n f\"{err_msg}: the character '{e}' is wrongly positioned\"\n )\n\n left *= comparison_sign\n right *= -comparison_sign\n\n return left, right, is_inequality"}, {"class_start_lineno": 1, "class_end_lineno": 499, "func_start_lineno": 195, "func_end_lineno": 226, "func_code": "def _validate_groups(groups: npt.ArrayLike, name: str = \"groups\") -> np.ndarray:\n \"\"\"Validate groups by checking its dim and if group names don't appear in multiple\n levels and convert to numpy array.\n\n Parameters\n ----------\n groups : array-like of shape (n_groups, n_assets)\n 2D-array of strings.\n\n Returns\n -------\n groups : ndarray of shape (n_groups, n_assets)\n 2D-array of strings.\n \"\"\"\n groups = np.asarray(groups)\n if groups.ndim != 2:\n raise ValueError(\n f\"`{name} must be a 2D array, got {groups.ndim}D array instead.\"\n )\n n = len(groups)\n group_sets = [set(groups[i]) for i in range(n)]\n for i in range(n - 1):\n for e in group_sets[i]:\n for j in range(i + 1, n):\n if e in group_sets[j]:\n raise DuplicateGroupsError(\n f\"'{e}' appear in two levels: {list(groups[i])} \"\n f\"and {list(groups[i])}. \"\n f\"{name} must be in only one level.\"\n )\n\n return groups"}, {"class_start_lineno": 1, "class_end_lineno": 499, "func_start_lineno": 32, "func_end_lineno": 134, "func_code": "def equations_to_matrix(\n groups: npt.ArrayLike,\n equations: npt.ArrayLike,\n sum_to_one: bool = False,\n raise_if_group_missing: bool = False,\n names: tuple[str, str] = (\"groups\", \"equations\"),\n) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:\n \"\"\"Convert a list of linear equations into the left and right matrices of the\n inequality A <= B and equality A == B.\n\n Parameters\n ----------\n groups : array-like of shape (n_groups, n_assets)\n 2D array of assets groups.\n\n For example:\n\n groups = np.array(\n [\n [\"SPX\", \"SX5E\", \"NKY\", \"TLT\"],\n [\"Equity\", \"Equity\", \"Equity\", \"Bond\"],\n [\"US\", \"Europe\", \"Japan\", \"US\"],\n ]\n )\n\n equations : array-like of shape (n_equations,)\n 1D array of equations.\n\n Example of valid equation patterns:\n * \"number_1 * group_1 + number_3 <= number_4 * group_3 + number_5\"\n * \"group_1 == number * group_2\"\n * \"group_1 <= number\"\n * \"group_1 == number\"\n\n \"group_1\" and \"group_2\" are the group names defined in `groups`.\n The second expression means that the sum of all assets in \"group_1\" should be\n less or equal to \"number\" times the sum of all assets in \"group_2\".\n\n For example:\n\n equations = [\n \"Equity <= 3 * Bond\",\n \"US >= 1.5\",\n \"Europe >= 0.5 * Japan\",\n \"Japan == 1\",\n \"3*SPX + 5*SX5E == 2*TLT + 3\",\n ]\n\n sum_to_one : bool\n If this is set to True, all elements in a group sum to one (used in the `views`\n of the Black-Litterman model).\n\n raise_if_group_missing : bool, default=False\n If this is set to True, an error is raised when a group is not found in the\n groups, otherwise only a warning is shown.\n The default is False.\n\n names : tuple[str, str], default=('groups', 'equations')\n The group and equation names used in error messages.\n The default is `('groups', 'equations')`.\n\n Returns\n -------\n left_equality: ndarray of shape (n_equations_equality, n_assets)\n right_equality: ndarray of shape (n_equations_equality,)\n The left and right matrices of the inequality A <= B.\n\n left_inequality: ndarray of shape (n_equations_inequality, n_assets)\n right_inequality: ndarray of shape (n_equations_inequality,)\n The left and right matrices of the equality A == B.\n \"\"\"\n groups = _validate_groups(groups, name=names[0])\n equations = _validate_equations(equations, name=names[1])\n\n a_equality = []\n b_equality = []\n\n a_inequality = []\n b_inequality = []\n\n for string in equations:\n try:\n left, right, is_inequality = _string_to_equation(\n groups=groups,\n string=string,\n sum_to_one=sum_to_one,\n )\n if is_inequality:\n a_inequality.append(left)\n b_inequality.append(right)\n else:\n a_equality.append(left)\n b_equality.append(right)\n except GroupNotFoundError as e:\n if raise_if_group_missing:\n raise\n warnings.warn(str(e), stacklevel=2)\n return (\n np.array(a_equality),\n np.array(b_equality),\n np.array(a_inequality),\n np.array(b_inequality),\n )"}], "type": ["function_empty", "Development"], "node": ["skfolio.utils.equations._split_equation_string", "skfolio.utils.equations._string_to_equation", "skfolio.utils.equations._validate_groups", "skfolio.utils.equations.equations_to_matrix"], "language": "Python", "toolfunc_count": 2, "func_count": 4, "pytest_info": {"total_num": 12, "base_passed_num": 2}} {"id": ["skfolio.src.skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.src.skfolio.datasets._base.load_sp500_dataset", "skfolio.src.skfolio.datasets._base.get_data_home", "skfolio.src.skfolio.datasets._base.download_dataset", "skfolio.src.skfolio.datasets._base.load_nasdaq_dataset"], "project": "skfolio", "origin_file": ["skfolio/datasets/_base.py", "skfolio/datasets/_base.py", "skfolio/datasets/_base.py", "skfolio/datasets/_base.py", "skfolio/datasets/_base.py"], "test_list": ["tests/test_utils/test_stats.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 71, "func_end_lineno": 113, "func_code": "def load_gzip_compressed_csv_data(\n data_filename: str,\n data_module: str = DATA_MODULE,\n encoding=\"utf-8\",\n datetime_index: bool = True,\n) -> pd.DataFrame:\n \"\"\"Load gzip-compressed csv files with `importlib.resources`.\n\n 1) Open resource file with `importlib.resources.open_binary`\n 2) Decompress csv file with `gzip.open`\n 3) Load decompressed data with `pd.read_csv`\n\n Parameters\n ----------\n data_filename : str\n Name of gzip-compressed csv file (`'*.csv.gz'`) to be loaded from\n `data_module/data_file_name`. For example `'SPX500.csv.gz'`.\n\n data_module : str or module, default='skfolio.datasets.data'\n Module where data lives. The default is `'skfolio.datasets.data'`.\n\n encoding : str, default=\"utf-8\"\n Name of the encoding that the gzip-decompressed file will be\n decoded with. The default is 'utf-8'.\n\n datetime_index: bool, default=True\n If this is set to True, the DataFrame index is converted to datetime with\n format=\"%Y-%m-%d\".\n The default is `True`.\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n DataFrame with each row representing one observation and each column\n representing the asset price of a given observation.\n \"\"\"\n path = resources.files(data_module).joinpath(data_filename)\n with path.open(\"rb\") as compressed_file:\n compressed_file = gzip.open(compressed_file, mode=\"rt\", encoding=encoding)\n df = pd.read_csv(compressed_file, sep=\",\", index_col=0)\n if datetime_index:\n df.index = pd.to_datetime(df.index, format=\"%Y-%m-%d\")\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 168, "func_end_lineno": 204, "func_code": "def load_sp500_dataset() -> pd.DataFrame:\n \"\"\"Load the prices of 20 assets from the S&P 500 Index composition.\n\n This dataset is composed of the daily prices of 20 assets from the S&P 500\n composition starting from 1990-01-02 up to 2022-12-28.\n\n The data comes from the Yahoo public API.\n The price is the adjusted close which is the closing price after adjustments for\n all applicable splits and dividend distributions.\n The adjustment uses appropriate split and dividend multipliers, adhering to\n the Center for Research in Security Prices (CRSP) standards.\n\n ============== ==================\n Observations 8313\n Assets 20\n ============== ==================\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n Prices DataFrame\n\n Examples\n --------\n >>> from skfolio.datasets import load_sp500_dataset\n >>> prices = load_sp500_dataset()\n >>> prices.head()\n AAPL AMD BAC ... UNH WMT XOM\n 1990-01-02 0.332589 4.1250 11.65625 ... 0.382813 5.890625 12.5000\n 1990-01-03 0.334821 4.0000 11.75000 ... 0.375000 5.890625 12.3750\n 1990-01-04 0.335938 3.9375 11.50000 ... 0.371094 5.859375 12.2500\n 1990-01-05 0.337054 3.8125 11.25000 ... 0.355469 5.796875 12.1875\n 1990-01-08 0.339286 3.8125 11.31250 ... 0.347656 5.875000 12.3750\n \"\"\"\n data_filename = \"sp500_dataset.csv.gz\"\n df = load_gzip_compressed_csv_data(data_filename)\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 25, "func_end_lineno": 55, "func_code": "def get_data_home(data_home: str | Path | None = None) -> str:\n \"\"\"Return the path of the skfolio data directory.\n\n This folder is used by some large dataset loaders to avoid downloading the\n data several times.\n\n By default, the data directory is set to a folder named 'skfolio_data' in the\n user home folder.\n\n Alternatively, it can be set by the 'SKFOLIO_DATA' environment\n variable or programmatically by giving an explicit folder path. The '~'\n symbol is expanded to the user home folder.\n\n If the folder does not already exist, it is automatically created.\n\n Parameters\n ----------\n data_home : str, optional\n The path to skfolio data directory. If `None`, the default path\n is `~/skfolio_data`.\n\n Returns\n -------\n data_home: str or path-like, optional\n The path to skfolio data directory.\n \"\"\"\n if data_home is None:\n data_home = os.environ.get(\"SKFOLIO_DATA\", os.path.join(\"~\", \"skfolio_data\"))\n data_home = os.path.expanduser(data_home)\n os.makedirs(data_home, exist_ok=True)\n return data_home"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 116, "func_end_lineno": 165, "func_code": "def download_dataset(\n data_filename: str,\n data_home: str | Path | None = None,\n download_if_missing: bool = True,\n) -> pd.DataFrame:\n \"\"\"Download and save locally a dataset from the remote GitHub dataset folder.\n\n Parameters\n ----------\n data_filename : str\n Name of gzip-compressed csv file (`'*.csv.gz'`) to be loaded from a remote\n GitHub dataset folder.\n\n data_home : str or path-like, optional\n Specify another download and cache folder for the datasets. By default,\n all skfolio data is stored in `~/skfolio_data` sub-folders.\n\n download_if_missing : bool, default=True\n If False, raise an OSError if the data is not locally available\n instead of trying to download the data from the source site.\n The default is `True`.\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n DataFrame with each row representing one observation and each column\n representing the asset price of a given observation.\n \"\"\"\n # Use a CORS proxy when triggering requests from the browser\n url_prefix = \"https://corsproxy.io/?\" if sys.platform == \"emscripten\" else \"\"\n url = url_prefix + (\n f\"https://github.com/skfolio/skfolio-datasets/raw/main/\"\n f\"datasets/{data_filename}.csv.gz\"\n )\n\n data_home = get_data_home(data_home=data_home)\n filepath = os.path.join(data_home, f\"{data_filename}.pkz\")\n\n if os.path.exists(filepath):\n return joblib.load(filepath)\n\n if not download_if_missing:\n raise OSError(\"Data not found and `download_if_missing` is False\")\n\n archive_path = os.path.join(data_home, os.path.basename(url))\n ur.urlretrieve(url, archive_path)\n df = load_gzip_compressed_csv_data(archive_path)\n joblib.dump(df, filepath, compress=6)\n os.remove(archive_path)\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 348, "func_end_lineno": 397, "func_code": "def load_nasdaq_dataset(data_home=None, download_if_missing=True) -> pd.DataFrame:\n \"\"\"Load the prices of 1455 assets from the NASDAQ Composite Index.\n\n This dataset is composed of the daily prices of 1455 assets from the NASDAQ\n Composite starting from 2018-01-02 up to 2023-05-31.\n\n The data comes from the Yahoo public API.\n The price is the adjusted close which is the closing price after adjustments for\n all applicable splits and dividend distributions.\n The adjustment uses appropriate split and dividend multipliers, adhering to\n the Center for Research in Security Prices (CRSP) standards.\n\n ============== ==================\n Observations 1362\n Assets 1455\n ============== ==================\n\n Parameters\n ----------\n data_home : str, optional\n Specify another download and cache folder for the datasets.\n By default, all skfolio data is stored in `~/skfolio_data` subfolders.\n\n download_if_missing : bool, default=True\n If False, raise an OSError if the data is not locally available\n instead of trying to download the data from the source site.\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n Prices DataFrame\n\n Examples\n --------\n >>> from skfolio.datasets import load_nasdaq_dataset\n >>> prices = load_nasdaq_dataset()\n >>> prices.head()\n AAL AAOI AAON AAPL ... ZVRA ZYME ZYNE ZYXI\n Date ...\n 2018-01-02 51.648 37.91 35.621 41.310 ... 66.4 7.933 12.995 2.922\n 2018-01-03 51.014 37.89 36.247 41.303 ... 72.8 7.965 13.460 2.913\n 2018-01-04 51.336 38.38 36.103 41.495 ... 78.4 8.430 12.700 2.869\n 2018-01-05 51.316 38.89 36.681 41.967 ... 77.6 8.400 12.495 2.780\n 2018-01-08 50.809 38.37 36.103 41.811 ... 82.4 8.310 12.550 2.825\n \"\"\"\n data_filename = \"nasdaq_dataset\"\n df = download_dataset(\n data_filename, data_home=data_home, download_if_missing=download_if_missing\n )\n return df"}], "type": ["function_empty"], "node": ["skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.datasets._base.load_sp500_dataset", "skfolio.datasets._base.get_data_home", "skfolio.datasets._base.download_dataset", "skfolio.datasets._base.load_nasdaq_dataset"], "language": "Python", "toolfunc_count": 5, "func_count": 5, "pytest_info": {"total_num": 37, "base_passed_num": 33}} {"id": ["skfolio.src.skfolio.utils.tools.optimal_rounding_decimals", "skfolio.src.skfolio.utils.tools.format_measure", "skfolio.src.skfolio.utils.tools.safe_indexing", "skfolio.src.skfolio.utils.tools.safe_split"], "project": "skfolio", "origin_file": ["skfolio/utils/tools.py", "skfolio/utils/tools.py", "skfolio/utils/tools.py", "skfolio/utils/tools.py"], "test_list": ["tests/test_utils/test_tools.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 787, "func_start_lineno": 537, "func_end_lineno": 550, "func_code": "def optimal_rounding_decimals(x: float) -> int:\n \"\"\"Return the optimal rounding decimal number for a user-friendly formatting.\n\n Parameters\n ----------\n x : float\n Number to round.\n\n Returns\n -------\n n : int\n Rounding decimal number.\n \"\"\"\n return min(6, max(int(-np.log10(abs(x))) + 2, 2))"}, {"class_start_lineno": 1, "class_end_lineno": 787, "func_start_lineno": 506, "func_end_lineno": 534, "func_code": "def format_measure(x: float, percent: bool = False) -> str:\n \"\"\"Format a measure number into a user-friendly string.\n\n Parameters\n ----------\n x : float\n Number to format.\n\n percent : bool, default=False\n If this is set to True, the number is formatted in percentage.\n\n Returns\n -------\n formatted : str\n Formatted string.\n \"\"\"\n if np.isnan(x):\n return str(x)\n if percent:\n xn = x * 100\n f = \"%\"\n else:\n xn = x\n f = \"f\"\n if xn == 0:\n n = 0\n else:\n n = optimal_rounding_decimals(xn)\n return \"{value:{fmt}}\".format(value=x, fmt=f\".{n}{f}\")"}, {"class_start_lineno": 1, "class_end_lineno": 787, "func_start_lineno": 190, "func_end_lineno": 219, "func_code": "def safe_indexing(\n X: npt.ArrayLike | pd.DataFrame, indices: npt.ArrayLike | None, axis: int = 0\n):\n \"\"\"Return rows, items or columns of X using indices.\n\n Parameters\n ----------\n X : array-like\n Data from which to sample rows.\n\n indices : array-like, optional\n Indices of rows or columns.\n The default (`None`) is to select the entire data.\n\n axis : int, default=0\n The axis along which `X` will be sub-sampled. `axis=0` will select\n rows while `axis=1` will select columns.\n\n Returns\n -------\n subset :\n Subset of X on axis 0.\n \"\"\"\n if indices is None:\n return X\n if hasattr(X, \"iloc\"):\n return X.take(indices, axis=axis)\n if axis == 0:\n return X[indices]\n return X[:, indices]"}, {"class_start_lineno": 1, "class_end_lineno": 787, "func_start_lineno": 222, "func_end_lineno": 261, "func_code": "def safe_split(\n X: npt.ArrayLike,\n y: npt.ArrayLike | None = None,\n indices: np.ndarray | None = None,\n axis: int = 0,\n):\n \"\"\"Create subset of dataset.\n\n Slice X, y according to indices for cross-validation.\n\n Parameters\n ----------\n X : array-like\n Data to be indexed.\n\n y : array-like\n Data to be indexed.\n\n indices : ndarray of int, optional\n Rows or columns to select from X and y.\n The default (`None`) is to select the entire data.\n\n axis : int, default=0\n The axis along which `X` will be sub-sampled. `axis=0` will select\n rows while `axis=1` will select columns.\n\n Returns\n -------\n X_subset : array-like\n Indexed data.\n\n y_subset : array-like\n Indexed targets.\n \"\"\"\n X_subset = safe_indexing(X, indices=indices, axis=axis)\n if y is not None:\n y_subset = safe_indexing(y, indices=indices, axis=axis)\n else:\n y_subset = None\n return X_subset, y_subset"}], "type": ["function_empty", "Development"], "node": ["skfolio.utils.tools.optimal_rounding_decimals", "skfolio.utils.tools.format_measure", "skfolio.utils.tools.safe_indexing", "skfolio.utils.tools.safe_split"], "language": "Python", "toolfunc_count": 3, "func_count": 4, "pytest_info": {"total_num": 21, "base_passed_num": 16}} {"id": ["d3rlpy.d3rlpy.dataset.transition_pickers.BasicTransitionPicker::__call__", "d3rlpy.d3rlpy.metrics.evaluators.make_batches", "d3rlpy.d3rlpy.models.encoders.DefaultEncoderFactory::create", "d3rlpy.d3rlpy.models.builders.create_discrete_q_function"], "project": "d3rlpy", "origin_file": ["d3rlpy/dataset/transition_pickers.py", "d3rlpy/metrics/evaluators.py", "d3rlpy/metrics/evaluators.py", "d3rlpy/models/encoders.py", "d3rlpy/models/builders.py"], "test_list": ["tests_copy/metrics/test_evaluators.py"], "prob_info": [{"class_start_lineno": 43, "class_end_lineno": 72, "func_start_lineno": 49, "func_end_lineno": 72, "func_code": " def __call__(self, episode: EpisodeBase, index: int) -> Transition:\n _validate_index(episode, index)\n\n observation = retrieve_observation(episode.observations, index)\n is_terminal = episode.terminated and index == episode.size() - 1\n if is_terminal:\n next_observation = create_zero_observation(observation)\n next_action = np.zeros_like(episode.actions[index])\n else:\n next_observation = retrieve_observation(\n episode.observations, index + 1\n )\n next_action = episode.actions[index + 1]\n\n return Transition(\n observation=observation,\n action=episode.actions[index],\n reward=episode.rewards[index],\n next_observation=next_observation,\n next_action=next_action,\n terminal=float(is_terminal),\n interval=1,\n rewards_to_go=episode.rewards[index:],\n )"}, {"class_start_lineno": 1, "class_end_lineno": 548, "func_start_lineno": 52, "func_end_lineno": 68, "func_code": "def make_batches(\n episode: EpisodeBase,\n window_size: int,\n transition_picker: TransitionPickerProtocol,\n) -> Iterator[TransitionMiniBatch]:\n n_batches = len(episode) // window_size\n if len(episode) % window_size != 0:\n n_batches += 1\n for i in range(n_batches):\n head_index = i * window_size\n last_index = min(head_index + window_size, episode.transition_count)\n transitions = [\n transition_picker(episode, index)\n for index in range(head_index, last_index)\n ]\n batch = TransitionMiniBatch.from_transitions(transitions)\n yield batch"}, {"class_start_lineno": 71, "class_end_lineno": 121, "func_start_lineno": 93, "func_end_lineno": 121, "func_code": " def __call__(\n self,\n algo: QLearningAlgoProtocol,\n dataset: ReplayBufferBase,\n ) -> float:\n total_errors = []\n episodes = self._episodes if self._episodes else dataset.episodes\n for episode in episodes:\n for batch in make_batches(\n episode, WINDOW_SIZE, dataset.transition_picker\n ):\n # estimate values for current observations\n values = algo.predict_value(batch.observations, batch.actions)\n\n # estimate values for next observations\n next_actions = algo.predict(batch.next_observations)\n next_values = algo.predict_value(\n batch.next_observations, next_actions\n )\n\n # calculate td errors\n mask = (1.0 - batch.terminals).reshape(-1)\n rewards = np.asarray(batch.rewards).reshape(-1)\n if algo.reward_scaler:\n rewards = algo.reward_scaler.transform_numpy(rewards)\n y = rewards + algo.gamma * next_values * mask\n total_errors += ((values - y) ** 2).tolist()\n\n return float(np.mean(total_errors))"}, {"class_start_lineno": 209, "class_end_lineno": 265, "func_start_lineno": 224, "func_end_lineno": 238, "func_code": " def create(self, observation_shape: Shape) -> Encoder:\n factory: Union[PixelEncoderFactory, VectorEncoderFactory]\n if len(observation_shape) == 3:\n factory = PixelEncoderFactory(\n activation=self.activation,\n use_batch_norm=self.use_batch_norm,\n dropout_rate=self.dropout_rate,\n )\n else:\n factory = VectorEncoderFactory(\n activation=self.activation,\n use_batch_norm=self.use_batch_norm,\n dropout_rate=self.dropout_rate,\n )\n return factory.create(observation_shape)"}, {"class_start_lineno": 1, "class_end_lineno": 403, "func_start_lineno": 47, "func_end_lineno": 82, "func_code": "def create_discrete_q_function(\n observation_shape: Shape,\n action_size: int,\n encoder_factory: EncoderFactory,\n q_func_factory: QFunctionFactory,\n device: str,\n enable_ddp: bool,\n n_ensembles: int = 1,\n) -> tuple[nn.ModuleList, DiscreteEnsembleQFunctionForwarder]:\n if q_func_factory.share_encoder:\n encoder = encoder_factory.create(observation_shape)\n hidden_size = compute_output_size([observation_shape], encoder)\n # normalize gradient scale by ensemble size\n for p in cast(nn.Module, encoder).parameters():\n p.register_hook(lambda grad: grad / n_ensembles)\n\n q_funcs = []\n forwarders = []\n for _ in range(n_ensembles):\n if not q_func_factory.share_encoder:\n encoder = encoder_factory.create(observation_shape)\n hidden_size = compute_output_size([observation_shape], encoder)\n q_func, forwarder = q_func_factory.create_discrete(\n encoder, hidden_size, action_size\n )\n q_func.to(device)\n if enable_ddp:\n q_func = wrap_model_by_ddp(q_func)\n forwarder.set_q_func(q_func)\n q_funcs.append(q_func)\n forwarders.append(forwarder)\n q_func_modules = nn.ModuleList(q_funcs)\n ensemble_forwarder = DiscreteEnsembleQFunctionForwarder(\n forwarders, action_size\n )\n return q_func_modules, ensemble_forwarder"}], "type": ["BugFix"], "node": ["d3rlpy.dataset.transition_pickers.BasicTransitionPicker.__call__", "d3rlpy.metrics.evaluators.make_batches", "d3rlpy.metrics.evaluators.TDErrorEvaluator.__call__", "d3rlpy.models.encoders.DefaultEncoderFactory.create", "d3rlpy.models.builders.create_discrete_q_function"], "language": "Python", "toolfunc_count": 0, "func_count": 4, "pytest_info": {"total_num": 19, "base_passed_num": 0}} {"id": ["d3rlpy.d3rlpy.models.encoders.DefaultEncoderFactory::create", "d3rlpy.d3rlpy.models.builders.create_discrete_q_function", "d3rlpy.d3rlpy.models.encoders.DefaultEncoderFactory::create_with_action", "d3rlpy.d3rlpy.models.builders.create_continuous_q_function"], "project": "d3rlpy", "origin_file": ["d3rlpy/models/encoders.py", "d3rlpy/models/builders.py", "d3rlpy/models/encoders.py", "d3rlpy/models/builders.py"], "test_list": ["tests_copy/models/test_builders.py"], "prob_info": [{"class_start_lineno": 209, "class_end_lineno": 265, "func_start_lineno": 224, "func_end_lineno": 238, "func_code": " def create(self, observation_shape: Shape) -> Encoder:\n factory: Union[PixelEncoderFactory, VectorEncoderFactory]\n if len(observation_shape) == 3:\n factory = PixelEncoderFactory(\n activation=self.activation,\n use_batch_norm=self.use_batch_norm,\n dropout_rate=self.dropout_rate,\n )\n else:\n factory = VectorEncoderFactory(\n activation=self.activation,\n use_batch_norm=self.use_batch_norm,\n dropout_rate=self.dropout_rate,\n )\n return factory.create(observation_shape)"}, {"class_start_lineno": 1, "class_end_lineno": 403, "func_start_lineno": 47, "func_end_lineno": 82, "func_code": "def create_discrete_q_function(\n observation_shape: Shape,\n action_size: int,\n encoder_factory: EncoderFactory,\n q_func_factory: QFunctionFactory,\n device: str,\n enable_ddp: bool,\n n_ensembles: int = 1,\n) -> tuple[nn.ModuleList, DiscreteEnsembleQFunctionForwarder]:\n if q_func_factory.share_encoder:\n encoder = encoder_factory.create(observation_shape)\n hidden_size = compute_output_size([observation_shape], encoder)\n # normalize gradient scale by ensemble size\n for p in cast(nn.Module, encoder).parameters():\n p.register_hook(lambda grad: grad / n_ensembles)\n\n q_funcs = []\n forwarders = []\n for _ in range(n_ensembles):\n if not q_func_factory.share_encoder:\n encoder = encoder_factory.create(observation_shape)\n hidden_size = compute_output_size([observation_shape], encoder)\n q_func, forwarder = q_func_factory.create_discrete(\n encoder, hidden_size, action_size\n )\n q_func.to(device)\n if enable_ddp:\n q_func = wrap_model_by_ddp(q_func)\n forwarder.set_q_func(q_func)\n q_funcs.append(q_func)\n forwarders.append(forwarder)\n q_func_modules = nn.ModuleList(q_funcs)\n ensemble_forwarder = DiscreteEnsembleQFunctionForwarder(\n forwarders, action_size\n )\n return q_func_modules, ensemble_forwarder"}, {"class_start_lineno": 209, "class_end_lineno": 265, "func_start_lineno": 240, "func_end_lineno": 261, "func_code": " def create_with_action(\n self,\n observation_shape: Shape,\n action_size: int,\n discrete_action: bool = False,\n ) -> EncoderWithAction:\n factory: Union[PixelEncoderFactory, VectorEncoderFactory]\n if len(observation_shape) == 3:\n factory = PixelEncoderFactory(\n activation=self.activation,\n use_batch_norm=self.use_batch_norm,\n dropout_rate=self.dropout_rate,\n )\n else:\n factory = VectorEncoderFactory(\n activation=self.activation,\n use_batch_norm=self.use_batch_norm,\n dropout_rate=self.dropout_rate,\n )\n return factory.create_with_action(\n observation_shape, action_size, discrete_action\n )"}, {"class_start_lineno": 1, "class_end_lineno": 403, "func_start_lineno": 85, "func_end_lineno": 128, "func_code": "def create_continuous_q_function(\n observation_shape: Shape,\n action_size: int,\n encoder_factory: EncoderFactory,\n q_func_factory: QFunctionFactory,\n device: str,\n enable_ddp: bool,\n n_ensembles: int = 1,\n) -> tuple[nn.ModuleList, ContinuousEnsembleQFunctionForwarder]:\n if q_func_factory.share_encoder:\n encoder = encoder_factory.create_with_action(\n observation_shape, action_size\n )\n hidden_size = compute_output_size(\n [observation_shape, (action_size,)], encoder\n )\n # normalize gradient scale by ensemble size\n for p in cast(nn.Module, encoder).parameters():\n p.register_hook(lambda grad: grad / n_ensembles)\n\n q_funcs = []\n forwarders = []\n for _ in range(n_ensembles):\n if not q_func_factory.share_encoder:\n encoder = encoder_factory.create_with_action(\n observation_shape, action_size\n )\n hidden_size = compute_output_size(\n [observation_shape, (action_size,)], encoder\n )\n q_func, forwarder = q_func_factory.create_continuous(\n encoder, hidden_size\n )\n q_func.to(device)\n if enable_ddp:\n q_func = wrap_model_by_ddp(q_func)\n forwarder.set_q_func(q_func)\n q_funcs.append(q_func)\n forwarders.append(forwarder)\n q_func_modules = nn.ModuleList(q_funcs)\n ensemble_forwarder = ContinuousEnsembleQFunctionForwarder(\n forwarders, action_size\n )\n return q_func_modules, ensemble_forwarder"}], "type": ["BugFix"], "node": ["d3rlpy.models.encoders.DefaultEncoderFactory.create", "d3rlpy.models.builders.create_discrete_q_function", "d3rlpy.models.encoders.DefaultEncoderFactory.create_with_action", "d3rlpy.models.builders.create_continuous_q_function"], "language": "Python", "toolfunc_count": 0, "func_count": 4, "pytest_info": {"total_num": 39, "base_passed_num": 25}} {"id": ["d3rlpy.d3rlpy.models.torch.q_functions.ensemble_q_function._gather_quantiles_by_indices", "d3rlpy.d3rlpy.models.torch.q_functions.ensemble_q_function._reduce_quantile_ensemble", "d3rlpy.d3rlpy.models.torch.q_functions.mean_q_function.DiscreteMeanQFunctionForwarder::compute_error", "d3rlpy.d3rlpy.models.torch.q_functions.ensemble_q_function.compute_ensemble_q_function_error"], "project": "d3rlpy", "origin_file": ["d3rlpy/models/torch/q_functions/ensemble_q_function.py", "d3rlpy/models/torch/q_functions/ensemble_q_function.py", "d3rlpy/models/torch/q_functions/mean_q_function.py", "d3rlpy/models/torch/q_functions/ensemble_q_function.py", "d3rlpy/models/torch/q_functions/ensemble_q_function.py"], "test_list": ["tests_copy/models/torch/q_functions/test_ensemble_q_function.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 367, "func_start_lineno": 35, "func_end_lineno": 52, "func_code": "def _gather_quantiles_by_indices(\n y: torch.Tensor, indices: torch.Tensor\n) -> torch.Tensor:\n # TODO: implement this in general case\n if y.dim() == 3:\n # (N, batch, n_quantiles) -> (batch, n_quantiles)\n return y.transpose(0, 1)[torch.arange(y.shape[1]), indices]\n elif y.dim() == 4:\n # (N, batch, action, n_quantiles) -> (batch, action, N, n_quantiles)\n transposed_y = y.transpose(0, 1).transpose(1, 2)\n # (batch, action, N, n_quantiles) -> (batch * action, N, n_quantiles)\n flat_y = transposed_y.reshape(-1, y.shape[0], y.shape[3])\n head_indices = torch.arange(y.shape[1] * y.shape[2])\n # (batch * action, N, n_quantiles) -> (batch * action, n_quantiles)\n gathered_y = flat_y[head_indices, indices.view(-1)]\n # (batch * action, n_quantiles) -> (batch, action, n_quantiles)\n return gathered_y.view(y.shape[1], y.shape[2], -1)\n raise ValueError"}, {"class_start_lineno": 1, "class_end_lineno": 367, "func_start_lineno": 55, "func_end_lineno": 74, "func_code": "def _reduce_quantile_ensemble(\n y: torch.Tensor, reduction: str = \"min\", dim: int = 0, lam: float = 0.75\n) -> torch.Tensor:\n # reduction beased on expectation\n mean = y.mean(dim=-1)\n if reduction == \"min\":\n indices = mean.min(dim=dim).indices\n return _gather_quantiles_by_indices(y, indices)\n elif reduction == \"max\":\n indices = mean.max(dim=dim).indices\n return _gather_quantiles_by_indices(y, indices)\n elif reduction == \"none\":\n return y\n elif reduction == \"mix\":\n min_indices = mean.min(dim=dim).indices\n max_indices = mean.max(dim=dim).indices\n min_values = _gather_quantiles_by_indices(y, min_indices)\n max_values = _gather_quantiles_by_indices(y, max_indices)\n return lam * min_values + (1.0 - lam) * max_values\n raise ValueError"}, {"class_start_lineno": 47, "class_end_lineno": 86, "func_start_lineno": 58, "func_end_lineno": 74, "func_code": " def compute_error(\n self,\n observations: TorchObservation,\n actions: torch.Tensor,\n rewards: torch.Tensor,\n target: torch.Tensor,\n terminals: torch.Tensor,\n gamma: Union[float, torch.Tensor] = 0.99,\n reduction: str = \"mean\",\n ) -> torch.Tensor:\n one_hot = F.one_hot(actions.view(-1), num_classes=self._action_size)\n value = (self._q_func(observations).q_value * one_hot.float()).sum(\n dim=1, keepdim=True\n )\n y = rewards + gamma * target * (1 - terminals)\n loss = compute_huber_loss(value, y)\n return compute_reduce(loss, reduction)"}, {"class_start_lineno": 1, "class_end_lineno": 367, "func_start_lineno": 77, "func_end_lineno": 109, "func_code": "def compute_ensemble_q_function_error(\n forwarders: Union[\n Sequence[DiscreteQFunctionForwarder],\n Sequence[ContinuousQFunctionForwarder],\n ],\n observations: TorchObservation,\n actions: torch.Tensor,\n rewards: torch.Tensor,\n target: torch.Tensor,\n terminals: torch.Tensor,\n gamma: Union[float, torch.Tensor] = 0.99,\n masks: Optional[torch.Tensor] = None,\n) -> torch.Tensor:\n assert target.ndim == 2\n td_sum = torch.tensor(\n 0.0,\n dtype=torch.float32,\n device=get_device(observations),\n )\n for forwarder in forwarders:\n loss = forwarder.compute_error(\n observations=observations,\n actions=actions,\n rewards=rewards,\n target=target,\n terminals=terminals,\n gamma=gamma,\n reduction=\"none\",\n )\n if masks is not None:\n loss = loss * masks\n td_sum += loss.mean()\n return td_sum"}, {"class_start_lineno": 150, "class_end_lineno": 218, "func_start_lineno": 179, "func_end_lineno": 198, "func_code": " def compute_error(\n self,\n observations: TorchObservation,\n actions: torch.Tensor,\n rewards: torch.Tensor,\n target: torch.Tensor,\n terminals: torch.Tensor,\n gamma: Union[float, torch.Tensor] = 0.99,\n masks: Optional[torch.Tensor] = None,\n ) -> torch.Tensor:\n return compute_ensemble_q_function_error(\n forwarders=self._forwarders,\n observations=observations,\n actions=actions,\n rewards=rewards,\n target=target,\n terminals=terminals,\n gamma=gamma,\n masks=masks,\n )"}], "type": ["BugFix"], "node": ["d3rlpy.models.torch.q_functions.ensemble_q_function._gather_quantiles_by_indices", "d3rlpy.models.torch.q_functions.ensemble_q_function._reduce_quantile_ensemble", "d3rlpy.models.torch.q_functions.mean_q_function.DiscreteMeanQFunctionForwarder.compute_error", "d3rlpy.models.torch.q_functions.ensemble_q_function.compute_ensemble_q_function_error", "d3rlpy.models.torch.q_functions.ensemble_q_function.DiscreteEnsembleQFunctionForwarder.compute_error"], "language": "Python", "toolfunc_count": 0, "func_count": 4, "pytest_info": {"total_num": 30, "base_passed_num": 10}} {"id": ["d3rlpy.d3rlpy.dataset.transition_pickers.BasicTransitionPicker::__call__", "d3rlpy.d3rlpy.preprocessing.reward_scalers.MinMaxRewardScaler::fit_with_transition_picker"], "project": "d3rlpy", "origin_file": ["d3rlpy/dataset/transition_pickers.py", "d3rlpy/preprocessing/reward_scalers.py"], "test_list": ["tests_copy/preprocessing/test_reward_scalers.py"], "prob_info": [{"class_start_lineno": 43, "class_end_lineno": 72, "func_start_lineno": 49, "func_end_lineno": 72, "func_code": " def __call__(self, episode: EpisodeBase, index: int) -> Transition:\n _validate_index(episode, index)\n\n observation = retrieve_observation(episode.observations, index)\n is_terminal = episode.terminated and index == episode.size() - 1\n if is_terminal:\n next_observation = create_zero_observation(observation)\n next_action = np.zeros_like(episode.actions[index])\n else:\n next_observation = retrieve_observation(\n episode.observations, index + 1\n )\n next_action = episode.actions[index + 1]\n\n return Transition(\n observation=observation,\n action=episode.actions[index],\n reward=episode.rewards[index],\n next_observation=next_observation,\n next_action=next_action,\n terminal=float(is_terminal),\n interval=1,\n rewards_to_go=episode.rewards[index:],\n )"}, {"class_start_lineno": 149, "class_end_lineno": 239, "func_start_lineno": 180, "func_end_lineno": 192, "func_code": " def fit_with_transition_picker(\n self,\n episodes: Sequence[EpisodeBase],\n transition_picker: TransitionPickerProtocol,\n ) -> None:\n assert not self.built\n rewards = []\n for episode in episodes:\n for i in range(episode.transition_count):\n transition = transition_picker(episode, i)\n rewards.append(transition.reward)\n self.minimum = float(np.min(rewards))\n self.maximum = float(np.max(rewards))"}], "type": ["BugFix"], "node": ["d3rlpy.dataset.transition_pickers.BasicTransitionPicker.__call__", "d3rlpy.preprocessing.reward_scalers.MinMaxRewardScaler.fit_with_transition_picker"], "language": "Python", "toolfunc_count": 0, "func_count": 2, "pytest_info": {"total_num": 15, "base_passed_num": 12}} {"id": ["datachain.src.datachain.lib.file.File::ensure_cached", "datachain.src.datachain.lib.file.File::open", "datachain.src.datachain.lib.file.File::_symlink_to"], "project": "datachain", "origin_file": ["datachain/lib/file.py", "datachain/lib/file.py", "datachain/lib/file.py"], "test_list": ["tests/unit/lib/test_file.py"], "prob_info": [{"class_start_lineno": 125, "class_end_lineno": 468, "func_start_lineno": 331, "func_end_lineno": 337, "func_code": " def ensure_cached(self) -> None:\n if self._catalog is None:\n raise RuntimeError(\n \"cannot download file to cache because catalog is not setup\"\n )\n client = self._catalog.get_client(self.source)\n client.download(self, callback=self._download_cb)"}, {"class_start_lineno": 125, "class_end_lineno": 468, "func_start_lineno": 243, "func_end_lineno": 256, "func_code": " def open(self, mode: Literal[\"rb\", \"r\"] = \"rb\") -> Iterator[Any]:\n \"\"\"Open the file and return a file object.\"\"\"\n if self.location:\n with VFileRegistry.resolve(self, self.location) as f: # type: ignore[arg-type]\n yield f\n\n else:\n if self._caching_enabled:\n self.ensure_cached()\n client: Client = self._catalog.get_client(self.source)\n with client.open_object(\n self, use_cache=self._caching_enabled, cb=self._download_cb\n ) as f:\n yield io.TextIOWrapper(f) if mode == \"r\" else f"}, {"class_start_lineno": 125, "class_end_lineno": 468, "func_start_lineno": 282, "func_end_lineno": 295, "func_code": " def _symlink_to(self, destination: str):\n if self.location:\n raise OSError(errno.ENOTSUP, \"Symlinking virtual file is not supported\")\n\n if self._caching_enabled:\n self.ensure_cached()\n source = self.get_local_path()\n assert source, \"File was not cached\"\n elif self.source.startswith(\"file://\"):\n source = self.get_path()\n else:\n raise OSError(errno.EXDEV, \"can't link across filesystems\")\n\n return os.symlink(source, destination)"}], "type": ["BugFix"], "node": ["datachain.lib.file.File.ensure_cached", "datachain.lib.file.File.open", "datachain.lib.file.File._symlink_to"], "language": "Python", "toolfunc_count": 0, "func_count": 3, "pytest_info": {"total_num": 33, "base_passed_num": 0}} {"id": ["datachain.src.datachain.lib.signal_schema.SignalSchema::_get_flat_tree", "datachain.src.datachain.lib.signal_schema.SignalSchema::get_column_type", "datachain.src.datachain.lib.signal_schema.SignalSchema::mutate"], "project": "datachain", "origin_file": ["datachain/lib/signal_schema.py", "datachain/lib/signal_schema.py", "datachain/lib/signal_schema.py"], "test_list": ["tests/unit/lib/test_signal_schema.py"], "prob_info": [{"class_start_lineno": 135, "class_end_lineno": 751, "func_start_lineno": 630, "func_end_lineno": 639, "func_code": " def _get_flat_tree(\n self, tree: dict, prefix: list[str], depth: int\n ) -> Iterator[tuple[list[str], DataType, bool, int]]:\n for name, (type_, substree) in tree.items():\n suffix = name.split(\".\")\n new_prefix = prefix + suffix\n has_subtree = substree is not None\n yield new_prefix, type_, has_subtree, depth\n if substree is not None:\n yield from self._get_flat_tree(substree, new_prefix, depth + 1)"}, {"class_start_lineno": 135, "class_end_lineno": 751, "func_start_lineno": 464, "func_end_lineno": 479, "func_code": " def get_column_type(self, col_name: str, with_subtree: bool = False) -> DataType:\n \"\"\"\n Returns column type by column name.\n\n If `with_subtree` is True, then it will return the type of the column\n even if it has a subtree (e.g. model with nested fields), otherwise it will\n return the type of the column (standard type field, not the model).\n\n If column is not found, raises `SignalResolvingError`.\n \"\"\"\n for path, _type, has_subtree, _ in self.get_flat_tree():\n if (with_subtree or not has_subtree) and DEFAULT_DELIMITER.join(\n path\n ) == col_name:\n return _type\n raise SignalResolvingError([col_name], \"is not found\")"}, {"class_start_lineno": 135, "class_end_lineno": 751, "func_start_lineno": 557, "func_end_lineno": 585, "func_code": " def mutate(self, args_map: dict) -> \"SignalSchema\":\n new_values = self.values.copy()\n\n for name, value in args_map.items():\n if isinstance(value, Column) and value.name in self.values:\n # renaming existing signal\n del new_values[value.name]\n new_values[name] = self.values[value.name]\n continue\n if isinstance(value, Column):\n # adding new signal from existing signal field\n try:\n new_values[name] = self.get_column_type(\n value.name, with_subtree=True\n )\n continue\n except SignalResolvingError:\n pass\n if isinstance(value, Func):\n # adding new signal with function\n new_values[name] = value.get_result_type(self)\n continue\n if isinstance(value, ColumnElement):\n # adding new signal\n new_values[name] = sql_to_python(value)\n continue\n new_values[name] = value\n\n return SignalSchema(new_values)"}], "type": ["BugFix"], "node": ["datachain.lib.signal_schema.SignalSchema._get_flat_tree", "datachain.lib.signal_schema.SignalSchema.get_column_type", "datachain.lib.signal_schema.SignalSchema.mutate"], "language": "Python", "toolfunc_count": 0, "func_count": 3, "pytest_info": {"total_num": 58, "base_passed_num": 56}} {"id": ["datachain.src.datachain.lib.webdataset.Builder::add", "datachain.src.datachain.lib.webdataset.get_tar_groups"], "project": "datachain", "origin_file": ["datachain/lib/webdataset.py", "datachain/lib/webdataset.py"], "test_list": ["tests/unit/lib/test_webdataset.py"], "prob_info": [{"class_start_lineno": 104, "class_end_lineno": 194, "func_start_lineno": 134, "func_end_lineno": 171, "func_code": " def add(self, file: tarfile.TarInfo):\n fstream = File(path=file.name)\n ext = fstream.get_file_ext()\n stem = fstream.get_file_stem()\n\n if self.state.stem is not None and self.state.stem != stem:\n raise StopIteration\n\n if self.state.stem is None:\n self.state.stem = stem\n\n if ext in self._core_extensions:\n if self.state.core_file is not None:\n raise CoreFileDuplicationError(\n self._tar_stream, file.name, self.state.core_file.name\n )\n self.state.core_file = file\n elif ext in self.state.data:\n raise WDSError(\n self._tar_stream,\n f\"file with extension '.{ext}' already exists in the archive\",\n )\n else:\n type_ = self._get_type(ext)\n if type_ is None:\n raise UnknownFileExtensionError(self._tar_stream, fstream.name, ext)\n\n if issubclass(type_, WDSReadableSubclass):\n reader = type_._reader\n else:\n reader = self.DEFAULT_TYPES_READERS.get(type_, None)\n\n if reader is None:\n raise WDSError(\n self._tar_stream,\n f\"unable to find a reader for type {type_}, extension .{ext}\",\n )\n self.state.data[ext] = reader(self, file)"}, {"class_start_lineno": 1, "class_end_lineno": 220, "func_start_lineno": 197, "func_end_lineno": 209, "func_code": "def get_tar_groups(stream, tar, core_extensions, spec, encoding=\"utf-8\"):\n builder = Builder(stream, core_extensions, spec, tar, encoding)\n\n for item in sorted(tar.getmembers(), key=lambda m: Path(m.name).stem):\n if not item.isfile():\n continue\n try:\n builder.add(item)\n except StopIteration:\n yield builder.produce()\n builder.add(item)\n if builder.state.stem is not None:\n yield builder.produce()"}], "type": ["BugFix"], "node": ["datachain.lib.webdataset.Builder.add", "datachain.lib.webdataset.get_tar_groups"], "language": "Python", "toolfunc_count": 0, "func_count": 2, "pytest_info": {"total_num": 7, "base_passed_num": 3}} {"id": ["haystack.haystack.utils.auth.EnvVarSecret::resolve_value", "haystack.haystack.components.rankers.transformers_similarity.TransformersSimilarityRanker::warm_up"], "project": "haystack", "origin_file": ["haystack/utils/auth.py", "haystack/components/rankers/transformers_similarity.py"], "test_list": ["test/components/rankers/test_transformers_similarity.py"], "prob_info": [{"class_start_lineno": 171, "class_end_lineno": 211, "func_start_lineno": 196, "func_end_lineno": 206, "func_code": " def resolve_value(self) -> Optional[Any]:\n \"\"\"Resolve the secret to an atomic value. The semantics of the value is secret-dependent.\"\"\"\n out = None\n for env_var in self._env_vars:\n value = os.getenv(env_var)\n if value is not None:\n out = value\n break\n if out is None and self._strict:\n raise ValueError(f\"None of the following authentication environment variables are set: {self._env_vars}\")\n return out"}, {"class_start_lineno": 24, "class_end_lineno": 309, "func_start_lineno": 142, "func_end_lineno": 155, "func_code": " def warm_up(self):\n \"\"\"\n Initializes the component.\n \"\"\"\n if self.model is None:\n self.model = AutoModelForSequenceClassification.from_pretrained(\n self.model_name_or_path, token=self.token.resolve_value() if self.token else None, **self.model_kwargs\n )\n self.tokenizer = AutoTokenizer.from_pretrained(\n self.model_name_or_path,\n token=self.token.resolve_value() if self.token else None,\n **self.tokenizer_kwargs,\n )\n self.device = ComponentDevice.from_multiple(device_map=DeviceMap.from_hf(self.model.hf_device_map))"}], "type": ["BugFix"], "node": ["haystack.utils.auth.EnvVarSecret.resolve_value", "haystack.components.rankers.transformers_similarity.TransformersSimilarityRanker.warm_up"], "language": "Python", "toolfunc_count": 0, "func_count": 2, "pytest_info": {"total_num": 26, "base_passed_num": 14}} {"id": ["transformers.src.transformers.models.llava_next.image_processing_llava_next.LlavaNextImageProcessor::pad", "transformers.src.transformers.models.llava_next.image_processing_llava_next.LlavaNextImageProcessor::_pad_for_patching"], "project": "transformers", "origin_file": ["transformers/models/llava_next/image_processing_llava_next.py", "transformers/models/llava_next/image_processing_llava_next.py"], "test_list": ["tests/models/llava_next/test_image_processing_llava_next.py"], "prob_info": [{"class_start_lineno": 142, "class_end_lineno": 749, "func_start_lineno": 284, "func_end_lineno": 350, "func_code": " def pad(\n self,\n image: np.ndarray,\n padding: Union[int, Tuple[int, int], Iterable[Tuple[int, int]]],\n mode: PaddingMode = PaddingMode.CONSTANT,\n constant_values: Union[float, Iterable[float]] = 0.0,\n data_format: Optional[Union[str, ChannelDimension]] = None,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n ) -> np.ndarray:\n \"\"\"\n Pads the `image` with the specified `padding` and `mode`. Padding can be in the (`height`, `width`)\n dimension of in the (`num_patches`) dimension. In the second case an iterable if tuples is expected\n as input.\n\n Args:\n image (`np.ndarray`):\n The image to pad.\n padding (`int` or `Tuple[int, int]` or `Iterable[Tuple[int, int]]`):\n Padding to apply to the edges of the height, width axes. Can be one of three formats:\n - `((before_height, after_height), (before_width, after_width))` unique pad widths for each axis.\n - `((before, after),)` yields same before and after pad for height and width.\n - `(pad,)` or int is a shortcut for before = after = pad width for all axes.\n mode (`PaddingMode`):\n The padding mode to use. Can be one of:\n - `\"constant\"`: pads with a constant value.\n - `\"reflect\"`: pads with the reflection of the vector mirrored on the first and last values of the\n vector along each axis.\n - `\"replicate\"`: pads with the replication of the last value on the edge of the array along each axis.\n - `\"symmetric\"`: pads with the reflection of the vector mirrored along the edge of the array.\n constant_values (`float` or `Iterable[float]`, *optional*):\n The value to use for the padding if `mode` is `\"constant\"`.\n data_format (`str` or `ChannelDimension`, *optional*):\n The channel dimension format for the output image. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n If unset, will use same as the input image.\n input_data_format (`str` or `ChannelDimension`, *optional*):\n The channel dimension format for the input image. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n If unset, will use the inferred format of the input image.\n\n Returns:\n `np.ndarray`: The padded image.\n\n \"\"\"\n\n # call the general `pad` if padding on `height/width`, otherwise it's the `num_patched` dim\n if isinstance(padding, int) or len(padding) != 4:\n return pad(image, padding, mode, constant_values, data_format, input_data_format)\n\n if input_data_format is None:\n input_data_format = infer_channel_dimension_format(image)\n if mode == PaddingMode.CONSTANT:\n image = np.pad(image, padding, mode=\"constant\", constant_values=constant_values)\n elif mode == PaddingMode.REFLECT:\n image = np.pad(image, padding, mode=\"reflect\")\n elif mode == PaddingMode.REPLICATE:\n image = np.pad(image, padding, mode=\"edge\")\n elif mode == PaddingMode.SYMMETRIC:\n image = np.pad(image, padding, mode=\"symmetric\")\n else:\n raise ValueError(f\"Invalid padding mode: {mode}\")\n image = (\n to_channel_dimension_format(image, data_format, input_data_format) if data_format is not None else image\n )\n return image"}, {"class_start_lineno": 142, "class_end_lineno": 749, "func_start_lineno": 462, "func_end_lineno": 476, "func_code": " def _pad_for_patching(\n self, image: np.array, target_resolution: tuple, input_data_format: ChannelDimension\n ) -> np.array:\n \"\"\"\n Pad an image to a target resolution while maintaining aspect ratio.\n \"\"\"\n target_height, target_width = target_resolution\n new_height, new_width = _get_patch_output_size(image, target_resolution, input_data_format)\n\n paste_x = (target_width - new_width) // 2\n paste_y = (target_height - new_height) // 2\n\n padded_image = self.pad(image, padding=((paste_y, paste_y), (paste_x, paste_x)))\n\n return padded_image"}], "type": ["BugFix"], "node": ["transformers.models.llava_next.image_processing_llava_next.LlavaNextImageProcessor.pad", "transformers.models.llava_next.image_processing_llava_next.LlavaNextImageProcessor._pad_for_patching"], "language": "Python", "toolfunc_count": 0, "func_count": 2, "pytest_info": {"total_num": 13, "base_passed_num": 0}} {"id": ["langchain.libs.langchain.langchain.agents.agent.AgentExecutor::_perform_agent_action", "langchain.libs.langchain.langchain.agents.agent_iterator.AgentExecutorIterator::__iter__"], "project": "langchain", "origin_file": ["langchain/agents/agent.py", "langchain/agents/agent.py", "langchain/agents/agent_iterator.py"], "test_list": ["libs/langchain/tests/unit_tests/agents/test_agent.py"], "prob_info": [{"class_start_lineno": 1047, "class_end_lineno": 1806, "func_start_lineno": 1419, "func_end_lineno": 1456, "func_code": " def _perform_agent_action(\n self,\n name_to_tool_map: Dict[str, BaseTool],\n color_mapping: Dict[str, str],\n agent_action: AgentAction,\n run_manager: Optional[CallbackManagerForChainRun] = None,\n ) -> AgentStep:\n if run_manager:\n run_manager.on_agent_action(agent_action, color=\"green\")\n # Otherwise we lookup the tool\n if agent_action.tool in name_to_tool_map:\n tool = name_to_tool_map[agent_action.tool]\n return_direct = tool.return_direct\n color = color_mapping[agent_action.tool]\n tool_run_kwargs = self._action_agent.tool_run_logging_kwargs()\n if return_direct:\n tool_run_kwargs[\"llm_prefix\"] = \"\"\n # We then call the tool on the tool input to get an observation\n observation = tool.run(\n agent_action.tool_input,\n verbose=self.verbose,\n color=color,\n callbacks=run_manager.get_child() if run_manager else None,\n **tool_run_kwargs,\n )\n else:\n tool_run_kwargs = self._action_agent.tool_run_logging_kwargs()\n observation = InvalidTool().run(\n {\n \"requested_tool_name\": agent_action.tool,\n \"available_tool_names\": list(name_to_tool_map.keys()),\n },\n verbose=self.verbose,\n color=None,\n callbacks=run_manager.get_child() if run_manager else None,\n **tool_run_kwargs,\n )\n return AgentStep(action=agent_action, observation=observation)"}, {"class_start_lineno": 1047, "class_end_lineno": 1806, "func_start_lineno": 1342, "func_end_lineno": 1417, "func_code": " def _iter_next_step(\n self,\n name_to_tool_map: Dict[str, BaseTool],\n color_mapping: Dict[str, str],\n inputs: Dict[str, str],\n intermediate_steps: List[Tuple[AgentAction, str]],\n run_manager: Optional[CallbackManagerForChainRun] = None,\n ) -> Iterator[Union[AgentFinish, AgentAction, AgentStep]]:\n \"\"\"Take a single step in the thought-action-observation loop.\n\n Override this to take control of how the agent makes and acts on choices.\n \"\"\"\n try:\n intermediate_steps = self._prepare_intermediate_steps(intermediate_steps)\n\n # Call the LLM to see what to do.\n output = self._action_agent.plan(\n intermediate_steps,\n callbacks=run_manager.get_child() if run_manager else None,\n **inputs,\n )\n except OutputParserException as e:\n if isinstance(self.handle_parsing_errors, bool):\n raise_error = not self.handle_parsing_errors\n else:\n raise_error = False\n if raise_error:\n raise ValueError(\n \"An output parsing error occurred. \"\n \"In order to pass this error back to the agent and have it try \"\n \"again, pass `handle_parsing_errors=True` to the AgentExecutor. \"\n f\"This is the error: {str(e)}\"\n )\n text = str(e)\n if isinstance(self.handle_parsing_errors, bool):\n if e.send_to_llm:\n observation = str(e.observation)\n text = str(e.llm_output)\n else:\n observation = \"Invalid or incomplete response\"\n elif isinstance(self.handle_parsing_errors, str):\n observation = self.handle_parsing_errors\n elif callable(self.handle_parsing_errors):\n observation = self.handle_parsing_errors(e)\n else:\n raise ValueError(\"Got unexpected type of `handle_parsing_errors`\")\n output = AgentAction(\"_Exception\", observation, text)\n if run_manager:\n run_manager.on_agent_action(output, color=\"green\")\n tool_run_kwargs = self._action_agent.tool_run_logging_kwargs()\n observation = ExceptionTool().run(\n output.tool_input,\n verbose=self.verbose,\n color=None,\n callbacks=run_manager.get_child() if run_manager else None,\n **tool_run_kwargs,\n )\n yield AgentStep(action=output, observation=observation)\n return\n\n # If the tool chosen is the finishing tool, then we end and return.\n if isinstance(output, AgentFinish):\n yield output\n return\n\n actions: List[AgentAction]\n if isinstance(output, AgentAction):\n actions = [output]\n else:\n actions = output\n for agent_action in actions:\n yield agent_action\n for agent_action in actions:\n yield self._perform_agent_action(\n name_to_tool_map, color_mapping, agent_action, run_manager\n )"}, {"class_start_lineno": 46, "class_end_lineno": 418, "func_start_lineno": 174, "func_end_lineno": 234, "func_code": " def __iter__(self: \"AgentExecutorIterator\") -> Iterator[AddableDict]:\n logger.debug(\"Initialising AgentExecutorIterator\")\n self.reset()\n callback_manager = CallbackManager.configure(\n self.callbacks,\n self.agent_executor.callbacks,\n self.agent_executor.verbose,\n self.tags,\n self.agent_executor.tags,\n self.metadata,\n self.agent_executor.metadata,\n )\n run_manager = callback_manager.on_chain_start(\n dumpd(self.agent_executor),\n self.inputs,\n self.run_id,\n name=self.run_name,\n )\n try:\n while self.agent_executor._should_continue(\n self.iterations, self.time_elapsed\n ):\n # take the next step: this plans next action, executes it,\n # yielding action and observation as they are generated\n next_step_seq: NextStepOutput = []\n for chunk in self.agent_executor._iter_next_step(\n self.name_to_tool_map,\n self.color_mapping,\n self.inputs,\n self.intermediate_steps,\n run_manager,\n ):\n next_step_seq.append(chunk)\n # if we're yielding actions, yield them as they come\n # do not yield AgentFinish, which will be handled below\n if self.yield_actions:\n if isinstance(chunk, AgentAction):\n yield AddableDict(actions=[chunk], messages=chunk.messages)\n elif isinstance(chunk, AgentStep):\n yield AddableDict(steps=[chunk], messages=chunk.messages)\n\n # convert iterator output to format handled by _process_next_step_output\n next_step = self.agent_executor._consume_next_step(next_step_seq)\n # update iterations and time elapsed\n self.update_iterations()\n # decide if this is the final output\n output = self._process_next_step_output(next_step, run_manager)\n is_final = \"intermediate_step\" not in output\n # yield the final output always\n # for backwards compat, yield int. output if not yielding actions\n if not self.yield_actions or is_final:\n yield output\n # if final output reached, stop iteration\n if is_final:\n return\n except BaseException as e:\n run_manager.on_chain_error(e)\n raise\n\n # if we got here means we exhausted iterations or time\n yield self._stop(run_manager)"}], "type": ["BugFix"], "node": ["langchain.agents.agent.AgentExecutor._perform_agent_action", "langchain.agents.agent.AgentExecutor._iter_next_step", "langchain.agents.agent_iterator.AgentExecutorIterator.__iter__"], "language": "Python", "toolfunc_count": 0, "func_count": 2, "pytest_info": {"total_num": 14, "base_passed_num": 13}} {"id": ["cloudnetpy.cloudnetpy.utils.cumsumr", "cloudnetpy.cloudnetpy.categorize.atmos_utils.calc_adiabatic_lwc"], "project": "cloudnetpy", "origin_file": ["cloudnetpy/utils.py", "cloudnetpy/categorize/atmos_utils.py"], "test_list": ["tests/unit/test_atmos_utils.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 1151, "func_start_lineno": 532, "func_end_lineno": 549, "func_code": "def cumsumr(array: np.ndarray, axis: int = 0) -> np.ndarray:\n \"\"\"Finds cumulative sum that resets on 0.\n\n Args:\n array: Input array.\n axis: Axis where the sum is calculated. Default is 0.\n\n Returns:\n Cumulative sum, restarted at 0.\n\n Examples:\n >>> x = np.array([0, 0, 1, 1, 0, 0, 0, 1, 1, 1])\n >>> cumsumr(x)\n [0, 0, 1, 2, 0, 0, 0, 1, 2, 3]\n\n \"\"\"\n cums = array.cumsum(axis=axis)\n return cums - np.maximum.accumulate(cums * (array == 0), axis=axis)"}, {"class_start_lineno": 1, "class_end_lineno": 357, "func_start_lineno": 302, "func_end_lineno": 318, "func_code": "def calc_adiabatic_lwc(lwc_dz: np.ndarray, height: np.ndarray) -> np.ndarray:\n \"\"\"Calculates adiabatic liquid water content (kg m-3).\n\n Args:\n lwc_dz: Liquid water content change rate (kg m-3 m-1) calculated at the\n base of each cloud and filled to that cloud.\n height: Height vector (m).\n\n Returns:\n Liquid water content (kg m-3).\n\n \"\"\"\n is_cloud = lwc_dz != 0\n cloud_indices = utils.cumsumr(is_cloud, axis=1)\n dz = utils.path_lengths_from_ground(height) * np.ones_like(lwc_dz)\n dz[cloud_indices < 1] = 0\n return utils.cumsumr(dz, axis=1) * lwc_dz"}], "type": ["function_empty"], "node": ["cloudnetpy.utils.cumsumr", "cloudnetpy.categorize.atmos_utils.calc_adiabatic_lwc"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 5, "base_passed_num": 4}} {"id": ["cloudnetpy.cloudnetpy.output._get_netcdf_dimensions", "cloudnetpy.cloudnetpy.output.save_level1b", "cloudnetpy.cloudnetpy.utils.isscalar", "cloudnetpy.cloudnetpy.output._get_dimensions"], "project": "cloudnetpy", "origin_file": ["cloudnetpy/output.py", "cloudnetpy/output.py", "cloudnetpy/utils.py", "cloudnetpy/output.py"], "test_list": ["tests/unit/test_basta.py", "tests/unit/test_bowtie.py", "tests/unit/test_categorize.py", "tests/unit/test_hatpro.py", "tests/unit/test_mrr.py", "tests/unit/test_plotting.py", "tests/unit/test_radiometrics.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 494, "func_start_lineno": 54, "func_end_lineno": 74, "func_code": "def _get_netcdf_dimensions(obj) -> dict:\n dimensions = {\n key: len(obj.data[key][:]) for key in (\"time\", \"range\") if key in obj.data\n }\n # RPG cloud radar\n if \"chirp_start_indices\" in obj.data:\n dimensions[\"chirp_sequence\"] = len(obj.data[\"chirp_start_indices\"][:])\n # disdrometer\n if hasattr(obj, \"n_diameter\") and hasattr(obj, \"n_velocity\"):\n dimensions[\"diameter\"] = obj.n_diameter\n dimensions[\"velocity\"] = obj.n_velocity\n dimensions[\"nv\"] = 2\n # HATPRO l1c\n if \"tb\" in obj.data:\n dimensions[\"frequency\"] = obj.data[\"tb\"][:].shape[1]\n dimensions[\"receiver_nb\"] = len(obj.data[\"receiver_nb\"][:])\n dimensions[\"band\"] = 2\n dimensions[\"t_amb_nb\"] = 2\n if \"irt\" in obj.data:\n dimensions[\"ir_channel\"] = obj.data[\"irt\"][:].shape[1]\n return dimensions"}, {"class_start_lineno": 1, "class_end_lineno": 494, "func_start_lineno": 21, "func_end_lineno": 51, "func_code": "def save_level1b(\n obj,\n output_file: PathLike | str,\n uuid: UUID | str | None = None,\n) -> str:\n \"\"\"Saves Cloudnet Level 1b file.\"\"\"\n dimensions = _get_netcdf_dimensions(obj)\n with init_file(output_file, dimensions, obj.data, uuid) as nc:\n file_uuid = nc.file_uuid\n fix_attribute_name(nc)\n location = obj.site_meta[\"name\"]\n nc.cloudnet_file_type = obj.instrument.domain\n nc.title = get_l1b_title(obj.instrument, location)\n if isinstance(obj.date, list):\n nc.year, nc.month, nc.day = obj.date\n elif isinstance(obj.date, datetime.date):\n nc.year = str(obj.date.year)\n nc.month = str(obj.date.month).zfill(2)\n nc.day = str(obj.date.day).zfill(2)\n else:\n raise TypeError\n nc.location = location\n nc.history = get_l1b_history(obj.instrument)\n nc.source = get_l1b_source(obj.instrument)\n if hasattr(obj, \"serial_number\") and obj.serial_number is not None:\n nc.serial_number = obj.serial_number\n if hasattr(obj, \"software\"):\n for software, version in obj.software.items():\n nc.setncattr(f\"{software}_version\", version)\n nc.references = get_references()\n return file_uuid"}, {"class_start_lineno": 1, "class_end_lineno": 1151, "func_start_lineno": 655, "func_end_lineno": 672, "func_code": "def isscalar(array: np.ndarray | float | list | netCDF4.Variable) -> bool:\n \"\"\"Tests if input is scalar.\n\n By \"scalar\" we mean that array has a single value.\n\n Examples:\n >>> isscalar(1)\n True\n >>> isscalar([1])\n True\n >>> isscalar(np.array(1))\n True\n >>> isscalar(np.array([1]))\n True\n\n \"\"\"\n arr = ma.array(array)\n return not hasattr(arr, \"__len__\") or arr.shape == () or len(arr) == 1"}, {"class_start_lineno": 1, "class_end_lineno": 494, "func_start_lineno": 417, "func_end_lineno": 427, "func_code": "def _get_dimensions(nc: netCDF4.Dataset, data: np.ndarray) -> tuple:\n \"\"\"Finds correct dimensions for a variable.\"\"\"\n if utils.isscalar(data):\n return ()\n variable_size: list = []\n file_dims = nc.dimensions\n array_dims = data.shape\n for length in array_dims:\n dim = [key for key in file_dims if file_dims[key].size == length][0] # noqa: RUF015\n variable_size = [*variable_size, dim]\n return tuple(variable_size)"}], "type": ["function_empty", "TDD"], "node": ["cloudnetpy.output._get_netcdf_dimensions", "cloudnetpy.output.save_level1b", "cloudnetpy.utils.isscalar", "cloudnetpy.output._get_dimensions"], "language": "Python", "toolfunc_count": 1, "func_count": 4, "pytest_info": {"total_num": 80, "base_passed_num": 23}} {"id": ["cloudnetpy.cloudnetpy.instruments.ceilo._initialize_ceilo", "cloudnetpy.cloudnetpy.instruments.ceilo.ceilo2nc", "cloudnetpy.cloudnetpy.output._get_netcdf_dimensions", "cloudnetpy.cloudnetpy.output.save_level1b"], "project": "cloudnetpy", "origin_file": ["cloudnetpy/instruments/ceilo.py", "cloudnetpy/instruments/ceilo.py", "cloudnetpy/output.py", "cloudnetpy/output.py"], "test_list": ["tests/unit/test_ceilo.py", "tests/unit/test_vaisala.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 278, "func_start_lineno": 129, "func_end_lineno": 159, "func_code": "def _initialize_ceilo(\n full_path: str,\n site_meta: dict,\n date: str | None = None,\n) -> ClCeilo | Ct25k | LufftCeilo | Cl61d | Cs135:\n if \"model\" in site_meta:\n if site_meta[\"model\"] not in (\n \"cl31\",\n \"cl51\",\n \"cl61d\",\n \"ct25k\",\n \"chm15k\",\n \"cs135\",\n ):\n msg = f\"Invalid ceilometer model: {site_meta['model']}\"\n raise ValueError(msg)\n if site_meta[\"model\"] in (\"cl31\", \"cl51\"):\n model = \"cl31_or_cl51\"\n else:\n model = site_meta[\"model\"]\n else:\n model = _find_ceilo_model(full_path)\n if model == \"cl31_or_cl51\":\n return ClCeilo(full_path, site_meta, date)\n if model == \"ct25k\":\n return Ct25k(full_path, site_meta, date)\n if model == \"cl61d\":\n return Cl61d(full_path, site_meta, date)\n if model == \"cs135\":\n return Cs135(full_path, site_meta, date)\n return LufftCeilo(full_path, site_meta, date)"}, {"class_start_lineno": 1, "class_end_lineno": 278, "func_start_lineno": 15, "func_end_lineno": 113, "func_code": "def ceilo2nc(\n full_path: str,\n output_file: str,\n site_meta: dict,\n uuid: str | None = None,\n date: str | None = None,\n) -> str:\n \"\"\"Converts Vaisala, Lufft and Campbell Scientific ceilometer data into\n Cloudnet Level 1b netCDF file.\n\n This function reads raw Vaisala (CT25k, CL31, CL51, CL61), Lufft\n (CHM 15k, CHM 15k-x) and Campbell Scientific (CS135) ceilometer files and writes\n the data into netCDF file. Three variants of the backscatter are saved:\n\n 1. Raw backscatter, `beta_raw`\n 2. Signal-to-noise screened backscatter, `beta`\n 3. SNR-screened backscatter with smoothed weak background, `beta_smooth`\n\n With CL61 two additional depolarisation parameters are saved:\n\n 1. Signal-to-noise screened depolarisation, `depolarisation`\n 2. SNR-screened depolarisation with smoothed weak background,\n `depolarisation_smooth`\n\n CL61 screened backscatter is screened using beta_smooth mask to improve detection\n of weak aerosol layers and supercooled liquid clouds.\n\n Args:\n full_path: Ceilometer file name.\n output_file: Output file name, e.g. 'ceilo.nc'.\n site_meta: Dictionary containing information about the site and instrument.\n Required key value pairs are `name` and `altitude` (metres above mean\n sea level). Also, 'calibration_factor' is recommended because the default\n value is probably incorrect. If the background noise is *not*\n range-corrected, you must define: {'range_corrected': False}.\n You can also explicitly set the instrument model with\n e.g. {'model': 'cl61d'}.\n uuid: Set specific UUID for the file.\n date: Expected date as YYYY-MM-DD of all profiles in the file.\n\n Returns:\n UUID of the generated file.\n\n Raises:\n RuntimeError: Failed to read or process raw ceilometer data.\n\n Examples:\n >>> from cloudnetpy.instruments import ceilo2nc\n >>> site_meta = {'name': 'Mace-Head', 'altitude': 5}\n >>> ceilo2nc('vaisala_raw.txt', 'vaisala.nc', site_meta)\n >>> site_meta = {'name': 'Juelich', 'altitude': 108,\n 'calibration_factor': 2.3e-12}\n >>> ceilo2nc('chm15k_raw.nc', 'chm15k.nc', site_meta)\n\n \"\"\"\n snr_limit = 5\n ceilo_obj = _initialize_ceilo(full_path, site_meta, date)\n calibration_factor = site_meta.get(\"calibration_factor\")\n range_corrected = site_meta.get(\"range_corrected\", True)\n ceilo_obj.read_ceilometer_file(calibration_factor)\n ceilo_obj.check_beta_raw_shape()\n n_negatives = _get_n_negatives(ceilo_obj)\n ceilo_obj.data[\"beta\"] = ceilo_obj.calc_screened_product(\n ceilo_obj.data[\"beta_raw\"],\n snr_limit,\n range_corrected=range_corrected,\n n_negatives=n_negatives,\n )\n ceilo_obj.data[\"beta_smooth\"] = ceilo_obj.calc_beta_smooth(\n ceilo_obj.data[\"beta\"],\n snr_limit,\n range_corrected=range_corrected,\n n_negatives=n_negatives,\n )\n if ceilo_obj.instrument is None or ceilo_obj.instrument.model is None:\n msg = \"Failed to read ceilometer model\"\n raise RuntimeError(msg)\n if (\n any(\n model in ceilo_obj.instrument.model.lower()\n for model in (\"cl61\", \"chm15k\", \"chm15kx\", \"cl51\", \"cl31\")\n )\n and range_corrected\n ):\n mask = ceilo_obj.data[\"beta_smooth\"].mask\n ceilo_obj.data[\"beta\"] = ma.masked_where(mask, ceilo_obj.data[\"beta_raw\"])\n ceilo_obj.data[\"beta\"][ceilo_obj.data[\"beta\"] <= 0] = ma.masked\n if \"depolarisation\" in ceilo_obj.data:\n ceilo_obj.data[\"depolarisation\"].mask = ceilo_obj.data[\"beta\"].mask\n ceilo_obj.screen_depol()\n ceilo_obj.screen_invalid_values()\n ceilo_obj.prepare_data()\n ceilo_obj.data_to_cloudnet_arrays()\n ceilo_obj.add_site_geolocation()\n attributes = output.add_time_attribute(ATTRIBUTES, ceilo_obj.date)\n output.update_attributes(ceilo_obj.data, attributes)\n for key in (\"beta\", \"beta_smooth\"):\n ceilo_obj.add_snr_info(key, snr_limit)\n return output.save_level1b(ceilo_obj, output_file, uuid)"}, {"class_start_lineno": 1, "class_end_lineno": 494, "func_start_lineno": 54, "func_end_lineno": 74, "func_code": "def _get_netcdf_dimensions(obj) -> dict:\n dimensions = {\n key: len(obj.data[key][:]) for key in (\"time\", \"range\") if key in obj.data\n }\n # RPG cloud radar\n if \"chirp_start_indices\" in obj.data:\n dimensions[\"chirp_sequence\"] = len(obj.data[\"chirp_start_indices\"][:])\n # disdrometer\n if hasattr(obj, \"n_diameter\") and hasattr(obj, \"n_velocity\"):\n dimensions[\"diameter\"] = obj.n_diameter\n dimensions[\"velocity\"] = obj.n_velocity\n dimensions[\"nv\"] = 2\n # HATPRO l1c\n if \"tb\" in obj.data:\n dimensions[\"frequency\"] = obj.data[\"tb\"][:].shape[1]\n dimensions[\"receiver_nb\"] = len(obj.data[\"receiver_nb\"][:])\n dimensions[\"band\"] = 2\n dimensions[\"t_amb_nb\"] = 2\n if \"irt\" in obj.data:\n dimensions[\"ir_channel\"] = obj.data[\"irt\"][:].shape[1]\n return dimensions"}, {"class_start_lineno": 1, "class_end_lineno": 494, "func_start_lineno": 21, "func_end_lineno": 51, "func_code": "def save_level1b(\n obj,\n output_file: PathLike | str,\n uuid: UUID | str | None = None,\n) -> str:\n \"\"\"Saves Cloudnet Level 1b file.\"\"\"\n dimensions = _get_netcdf_dimensions(obj)\n with init_file(output_file, dimensions, obj.data, uuid) as nc:\n file_uuid = nc.file_uuid\n fix_attribute_name(nc)\n location = obj.site_meta[\"name\"]\n nc.cloudnet_file_type = obj.instrument.domain\n nc.title = get_l1b_title(obj.instrument, location)\n if isinstance(obj.date, list):\n nc.year, nc.month, nc.day = obj.date\n elif isinstance(obj.date, datetime.date):\n nc.year = str(obj.date.year)\n nc.month = str(obj.date.month).zfill(2)\n nc.day = str(obj.date.day).zfill(2)\n else:\n raise TypeError\n nc.location = location\n nc.history = get_l1b_history(obj.instrument)\n nc.source = get_l1b_source(obj.instrument)\n if hasattr(obj, \"serial_number\") and obj.serial_number is not None:\n nc.serial_number = obj.serial_number\n if hasattr(obj, \"software\"):\n for software, version in obj.software.items():\n nc.setncattr(f\"{software}_version\", version)\n nc.references = get_references()\n return file_uuid"}], "type": ["function_empty", "TDD"], "node": ["cloudnetpy.instruments.ceilo._initialize_ceilo", "cloudnetpy.instruments.ceilo.ceilo2nc", "cloudnetpy.output._get_netcdf_dimensions", "cloudnetpy.output.save_level1b"], "language": "Python", "toolfunc_count": 2, "func_count": 4, "pytest_info": {"total_num": 33, "base_passed_num": 5}} {"id": ["cloudnetpy.cloudnetpy.concat_lib._Concat::__init__", "cloudnetpy.cloudnetpy.concat_lib.concatenate_files", "cloudnetpy.cloudnetpy.concat_lib._Concat::_write_initial_data", "cloudnetpy.cloudnetpy.concat_lib._Concat::concat_data"], "project": "cloudnetpy", "origin_file": ["cloudnetpy/concat_lib.py", "cloudnetpy/concat_lib.py", "cloudnetpy/concat_lib.py", "cloudnetpy/concat_lib.py"], "test_list": ["tests/unit/test_cl61d.py", "tests/unit/test_concat_lib.py", "tests/unit/test_copernicus.py", "tests/unit/test_galileo.py", "tests/unit/test_lufft.py"], "prob_info": [{"class_start_lineno": 122, "class_end_lineno": 253, "func_start_lineno": 125, "func_end_lineno": 136, "func_code": " def __init__(\n self,\n filenames: Iterable[PathLike | str],\n output_file: str,\n concat_dimension: str = \"time\",\n ):\n self.filenames = sorted(map(Path, filenames), key=lambda f: f.name)\n self.concat_dimension = concat_dimension\n self.first_filename = self.filenames[0]\n self.first_file = netCDF4.Dataset(self.first_filename)\n self.concatenated_file = self._init_output_file(output_file)\n self.common_variables = set()"}, {"class_start_lineno": 1, "class_end_lineno": 352, "func_start_lineno": 85, "func_end_lineno": 119, "func_code": "def concatenate_files(\n filenames: Iterable[PathLike | str],\n output_file: str,\n concat_dimension: str = \"time\",\n variables: list | None = None,\n new_attributes: dict | None = None,\n ignore: list | None = None,\n allow_difference: list | None = None,\n) -> list:\n \"\"\"Concatenate netCDF files in one dimension.\n\n Args:\n filenames: List of files to be concatenated.\n output_file: Output file name.\n concat_dimension: Dimension name for concatenation. Default is 'time'.\n variables: List of variables with the 'concat_dimension' to be concatenated.\n Default is None when all variables with 'concat_dimension' will be saved.\n new_attributes: Optional new global attributes as {'attribute_name': value}.\n ignore: List of variables to be ignored.\n allow_difference: Names of scalar variables that can differ from one file to\n another (value from the first file is saved).\n\n Returns:\n List of filenames that were successfully concatenated.\n\n Notes:\n Arrays without 'concat_dimension', scalars, and global attributes will be taken\n from the first file. Groups, possibly present in a NETCDF4 formatted file,\n are ignored.\n\n \"\"\"\n with _Concat(filenames, output_file, concat_dimension) as concat:\n concat.get_common_variables()\n concat.create_global_attributes(new_attributes)\n return concat.concat_data(variables, ignore, allow_difference)"}, {"class_start_lineno": 122, "class_end_lineno": 253, "func_start_lineno": 173, "func_end_lineno": 202, "func_code": " def _write_initial_data(self, variables: list | None, ignore: list | None) -> None:\n for key in self.first_file.variables:\n if (\n variables is not None\n and key not in variables\n and key not in self.common_variables\n and key != self.concat_dimension\n ):\n continue\n if ignore and key in ignore:\n continue\n\n auto_scale = False\n self.first_file[key].set_auto_scale(auto_scale)\n array = self.first_file[key][:]\n dimensions = self.first_file[key].dimensions\n fill_value = getattr(self.first_file[key], \"_FillValue\", None)\n var = self.concatenated_file.createVariable(\n key,\n array.dtype,\n dimensions,\n zlib=True,\n complevel=3,\n shuffle=False,\n fill_value=fill_value,\n )\n auto_scale = False\n var.set_auto_scale(auto_scale)\n var[:] = array\n _copy_attributes(self.first_file[key], var)"}, {"class_start_lineno": 122, "class_end_lineno": 253, "func_start_lineno": 151, "func_end_lineno": 171, "func_code": " def concat_data(\n self,\n variables: list | None,\n ignore: list | None,\n allow_vary: list | None,\n ) -> list:\n \"\"\"Concatenates data arrays.\"\"\"\n self._write_initial_data(variables, ignore)\n output = [self.first_filename]\n if len(self.filenames) > 1:\n for filename in self.filenames[1:]:\n try:\n self._append_data(filename, allow_vary)\n except RuntimeError as e:\n if \"NetCDF: HDF error\" in str(e):\n msg = f\"Caught a NetCDF HDF error. Skipping file '{filename}'.\"\n logging.exception(msg)\n continue\n raise\n output.append(filename)\n return output"}], "type": ["function_empty", "TDD"], "node": ["cloudnetpy.concat_lib._Concat.__init__", "cloudnetpy.concat_lib.concatenate_files", "cloudnetpy.concat_lib._Concat._write_initial_data", "cloudnetpy.concat_lib._Concat.concat_data"], "language": "Python", "toolfunc_count": 2, "func_count": 4, "pytest_info": {"total_num": 69, "base_passed_num": 0}} {"id": ["cloudnetpy.cloudnetpy.utils.binvec", "cloudnetpy.cloudnetpy.utils.rebin_2d", "cloudnetpy.cloudnetpy.cloudnetarray.CloudnetArray::rebin_data"], "project": "cloudnetpy", "origin_file": ["cloudnetpy/utils.py", "cloudnetpy/utils.py", "cloudnetpy/cloudnetarray.py"], "test_list": ["tests/unit/test_cloudnetarray.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 1151, "func_start_lineno": 124, "func_end_lineno": 140, "func_code": "def binvec(x: np.ndarray | list) -> np.ndarray:\n \"\"\"Converts 1-D center points to bins with even spacing.\n\n Args:\n x: 1-D array of N real values.\n\n Returns:\n ndarray: N + 1 edge values.\n\n Examples:\n >>> binvec([1, 2, 3])\n [0.5, 1.5, 2.5, 3.5]\n\n \"\"\"\n edge1 = x[0] - (x[1] - x[0]) / 2\n edge2 = x[-1] + (x[-1] - x[-2]) / 2\n return np.linspace(edge1, edge2, len(x) + 1)"}, {"class_start_lineno": 1, "class_end_lineno": 1151, "func_start_lineno": 143, "func_end_lineno": 192, "func_code": "def rebin_2d(\n x_in: np.ndarray,\n array: ma.MaskedArray,\n x_new: np.ndarray,\n statistic: Literal[\"mean\", \"std\"] = \"mean\",\n n_min: int = 1,\n *,\n mask_zeros: bool = True,\n) -> tuple[ma.MaskedArray, list]:\n \"\"\"Rebins 2-D data in one dimension.\n\n Args:\n x_in: 1-D array with shape (n,).\n array: 2-D input data with shape (n, m).\n x_new: 1-D target vector (center points) with shape (N,).\n statistic: Statistic to be calculated. Possible statistics are 'mean', 'std'.\n Default is 'mean'.\n n_min: Minimum number of points to have good statistics in a bin. Default is 1.\n mask_zeros: Whether to mask 0 values in the returned array. Default is True.\n\n Returns:\n tuple: Rebinned data with shape (N, m) and indices of bins without enough data.\n \"\"\"\n edges = binvec(x_new)\n result = np.zeros((len(x_new), array.shape[1]))\n array_screened = ma.masked_invalid(array, copy=True) # data may contain nan-values\n for ind, values in enumerate(array_screened.T):\n mask = ~values.mask\n if ma.any(values[mask]):\n result[:, ind], _, _ = stats.binned_statistic(\n x_in[mask],\n values[mask],\n statistic=statistic,\n bins=edges,\n )\n result[~np.isfinite(result)] = 0\n if mask_zeros is True:\n masked_result = ma.masked_equal(result, 0)\n else:\n masked_result = ma.array(result)\n\n # Fill bins with not enough profiles\n x_hist, _ = np.histogram(x_in, bins=edges)\n empty_mask = x_hist < n_min\n masked_result[empty_mask, :] = ma.masked\n empty_indices = list(np.nonzero(empty_mask)[0])\n if len(empty_indices) > 0:\n logging.debug(\"No data in %s bins\", len(empty_indices))\n\n return masked_result, empty_indices"}, {"class_start_lineno": 14, "class_end_lineno": 211, "func_start_lineno": 61, "func_end_lineno": 84, "func_code": " def rebin_data(\n self, time: np.ndarray, time_new: np.ndarray, *, mask_zeros: bool = True\n ) -> list:\n \"\"\"Rebins `data` in time.\n\n Args:\n time: 1D time array.\n time_new: 1D new time array.\n mask_zeros: Whether to mask 0 values in the returned array. Default is True.\n\n Returns:\n Time indices without data.\n\n \"\"\"\n if self.data.ndim == 1:\n self.data = utils.rebin_1d(time, self.data, time_new, mask_zeros=mask_zeros)\n bad_indices = list(np.where(self.data == ma.masked)[0])\n else:\n if not isinstance(self.data, ma.MaskedArray):\n self.data = ma.masked_array(self.data)\n self.data, bad_indices = utils.rebin_2d(\n time, self.data, time_new, mask_zeros=mask_zeros\n )\n return bad_indices"}], "type": ["function_empty", "TDD"], "node": ["cloudnetpy.utils.binvec", "cloudnetpy.utils.rebin_2d", "cloudnetpy.cloudnetarray.CloudnetArray.rebin_data"], "language": "Python", "toolfunc_count": 2, "func_count": 3, "pytest_info": {"total_num": 17, "base_passed_num": 15}} {"id": ["cloudnetpy.cloudnetpy.instruments.disdrometer.parsivel._read_toa5", "cloudnetpy.cloudnetpy.instruments.disdrometer.parsivel._read_fmi", "cloudnetpy.cloudnetpy.instruments.disdrometer.parsivel.parsivel2nc", "cloudnetpy.cloudnetpy.output._get_netcdf_dimensions", "cloudnetpy.cloudnetpy.output.save_level1b"], "project": "cloudnetpy", "origin_file": ["cloudnetpy/instruments/disdrometer/parsivel.py", "cloudnetpy/instruments/disdrometer/parsivel.py", "cloudnetpy/instruments/disdrometer/parsivel.py", "cloudnetpy/output.py", "cloudnetpy/output.py"], "test_list": ["tests/unit/test_disdrometer.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 713, "func_start_lineno": 450, "func_end_lineno": 519, "func_code": "def _read_toa5(filename: str | PathLike) -> dict[str, list]:\n \"\"\"Read ASCII data from Campbell Scientific datalogger such as CR1000.\n\n References:\n CR1000 Measurement and Control System.\n https://s.campbellsci.com/documents/us/manuals/cr1000.pdf\n \"\"\"\n with open(filename, errors=\"ignore\") as file:\n reader = csv.reader(file)\n _origin_line = next(reader)\n header_line = next(reader)\n headers = [\n TOA5_HEADERS.get(re.sub(r\"\\(.*\", \"\", field)) for field in header_line\n ]\n if unknown_headers := [\n header_line[i] for i in range(len(header_line)) if headers[i] is None\n ]:\n msg = \"Unknown headers: \" + \", \".join(unknown_headers)\n logging.warning(msg)\n _units_line = next(reader)\n _process_line = next(reader)\n data: dict[str, list] = {header: [] for header in headers if header is not None}\n n_rows = 0\n n_invalid_rows = 0\n for data_line in reader:\n n_rows += 1\n scalars: dict[str, datetime.datetime | int | float | str] = {}\n arrays: dict[str, list] = {\n \"number_concentration\": [],\n \"fall_velocity\": [],\n \"spectrum\": [],\n }\n try:\n for header, value in zip(headers, data_line, strict=True):\n if header is None:\n continue\n if header == \"_datetime\":\n scalars[header] = datetime.datetime.strptime(\n value,\n \"%Y-%m-%d %H:%M:%S\",\n )\n elif header in (\"number_concentration\", \"fall_velocity\"):\n arrays[header].append(float(value))\n elif header == \"spectrum\":\n arrays[header].append(int(value))\n elif PARSERS.get(header) == _parse_int:\n scalars[header] = int(value)\n elif PARSERS.get(header) == _parse_float:\n scalars[header] = float(value)\n else:\n scalars[header] = value\n except ValueError:\n n_invalid_rows += 1\n continue\n for header, scalar in scalars.items():\n data[header].append(scalar)\n if \"spectrum\" in headers:\n data[\"spectrum\"].append(\n np.array(arrays[\"spectrum\"], dtype=\"i2\").reshape((32, 32)),\n )\n if \"number_concentration\" in headers:\n data[\"number_concentration\"].append(arrays[\"number_concentration\"])\n if \"fall_velocity\" in headers:\n data[\"fall_velocity\"].append(arrays[\"fall_velocity\"])\n if n_invalid_rows == n_rows:\n msg = \"No valid data in file\"\n raise DisdrometerDataError(msg)\n if n_invalid_rows > 0:\n logging.info(\"Skipped %s invalid rows\", n_invalid_rows)\n return data"}, {"class_start_lineno": 1, "class_end_lineno": 713, "func_start_lineno": 618, "func_end_lineno": 657, "func_code": "def _read_fmi(content: str):\n r\"\"\"Read format used by Finnish Meteorological Institute and University of\n Helsinki.\n\n Format consists of sequence of the following:\n - \"[YYYY-MM-DD HH:MM:SS\\n\"\n - output of \"CS/PA\" command without non-printable characters at the end\n - \"]\\n\"\n \"\"\"\n output: dict[str, list] = {\"_datetime\": []}\n for m in re.finditer(\n r\"\\[(?P\\d+)-(?P\\d+)-(?P\\d+) \"\n r\"(?P\\d+):(?P\\d+):(?P\\d+)\"\n r\"(?P[^\\]]*)\\]\",\n content,\n ):\n try:\n record = _read_typ_op4a(m[\"output\"].splitlines())\n except ValueError:\n continue\n\n for key, value in record.items():\n if key not in output:\n output[key] = [None] * len(output[\"_datetime\"])\n output[key].append(value)\n for key in output:\n if key not in record and key != \"_datetime\":\n output[key].append(None)\n\n output[\"_datetime\"].append(\n datetime.datetime(\n int(m[\"year\"]),\n int(m[\"month\"]),\n int(m[\"day\"]),\n int(m[\"hour\"]),\n int(m[\"minute\"]),\n int(m[\"second\"]),\n )\n )\n return output"}, {"class_start_lineno": 1, "class_end_lineno": 713, "func_start_lineno": 23, "func_end_lineno": 77, "func_code": "def parsivel2nc(\n disdrometer_file: str | PathLike | Iterable[str | PathLike],\n output_file: str,\n site_meta: dict,\n uuid: str | None = None,\n date: str | datetime.date | None = None,\n telegram: Sequence[int | None] | None = None,\n timestamps: Sequence[datetime.datetime] | None = None,\n) -> str:\n \"\"\"Converts OTT Parsivel-2 disdrometer data into Cloudnet Level 1b netCDF\n file.\n\n Args:\n disdrometer_file: Filename of disdrometer file or list of filenames.\n output_file: Output filename.\n site_meta: Dictionary containing information about the site. Required key\n is `name`.\n uuid: Set specific UUID for the file.\n date: Expected date of the measurements as YYYY-MM-DD.\n telegram: List of measured value numbers as specified in section 11.2 of\n the instrument's operating instructions. Unknown values are indicated\n with None. Telegram is required if the input file doesn't contain a\n header.\n timestamps: Specify list of timestamps if they are missing in the input file.\n\n Returns:\n UUID of the generated file.\n\n Raises:\n DisdrometerDataError: Timestamps do not match the expected date, or unable\n to read the disdrometer file.\n\n Examples:\n >>> from cloudnetpy.instruments import parsivel2nc\n >>> site_meta = {'name': 'Lindenberg', 'altitude': 104, 'latitude': 52.2,\n 'longitude': 14.1}\n >>> uuid = parsivel2nc('parsivel.log', 'parsivel.nc', site_meta)\n\n \"\"\"\n if isinstance(date, str):\n date = datetime.date.fromisoformat(date)\n if isinstance(disdrometer_file, str | PathLike):\n disdrometer_file = [disdrometer_file]\n disdrometer = Parsivel(disdrometer_file, site_meta, telegram, date, timestamps)\n disdrometer.sort_timestamps()\n disdrometer.remove_duplicate_timestamps()\n disdrometer.mask_invalid_values()\n if len(disdrometer.data[\"time\"].data) < 2:\n msg = \"Too few data points\"\n raise DisdrometerDataError(msg)\n disdrometer.convert_units()\n disdrometer.add_meta()\n attributes = output.add_time_attribute(ATTRIBUTES, disdrometer.date)\n output.update_attributes(disdrometer.data, attributes)\n return output.save_level1b(disdrometer, output_file, uuid)"}, {"class_start_lineno": 1, "class_end_lineno": 494, "func_start_lineno": 54, "func_end_lineno": 74, "func_code": "def _get_netcdf_dimensions(obj) -> dict:\n dimensions = {\n key: len(obj.data[key][:]) for key in (\"time\", \"range\") if key in obj.data\n }\n # RPG cloud radar\n if \"chirp_start_indices\" in obj.data:\n dimensions[\"chirp_sequence\"] = len(obj.data[\"chirp_start_indices\"][:])\n # disdrometer\n if hasattr(obj, \"n_diameter\") and hasattr(obj, \"n_velocity\"):\n dimensions[\"diameter\"] = obj.n_diameter\n dimensions[\"velocity\"] = obj.n_velocity\n dimensions[\"nv\"] = 2\n # HATPRO l1c\n if \"tb\" in obj.data:\n dimensions[\"frequency\"] = obj.data[\"tb\"][:].shape[1]\n dimensions[\"receiver_nb\"] = len(obj.data[\"receiver_nb\"][:])\n dimensions[\"band\"] = 2\n dimensions[\"t_amb_nb\"] = 2\n if \"irt\" in obj.data:\n dimensions[\"ir_channel\"] = obj.data[\"irt\"][:].shape[1]\n return dimensions"}, {"class_start_lineno": 1, "class_end_lineno": 494, "func_start_lineno": 21, "func_end_lineno": 51, "func_code": "def save_level1b(\n obj,\n output_file: PathLike | str,\n uuid: UUID | str | None = None,\n) -> str:\n \"\"\"Saves Cloudnet Level 1b file.\"\"\"\n dimensions = _get_netcdf_dimensions(obj)\n with init_file(output_file, dimensions, obj.data, uuid) as nc:\n file_uuid = nc.file_uuid\n fix_attribute_name(nc)\n location = obj.site_meta[\"name\"]\n nc.cloudnet_file_type = obj.instrument.domain\n nc.title = get_l1b_title(obj.instrument, location)\n if isinstance(obj.date, list):\n nc.year, nc.month, nc.day = obj.date\n elif isinstance(obj.date, datetime.date):\n nc.year = str(obj.date.year)\n nc.month = str(obj.date.month).zfill(2)\n nc.day = str(obj.date.day).zfill(2)\n else:\n raise TypeError\n nc.location = location\n nc.history = get_l1b_history(obj.instrument)\n nc.source = get_l1b_source(obj.instrument)\n if hasattr(obj, \"serial_number\") and obj.serial_number is not None:\n nc.serial_number = obj.serial_number\n if hasattr(obj, \"software\"):\n for software, version in obj.software.items():\n nc.setncattr(f\"{software}_version\", version)\n nc.references = get_references()\n return file_uuid"}], "type": ["function_empty", "TDD"], "node": ["cloudnetpy.instruments.disdrometer.parsivel._read_toa5", "cloudnetpy.instruments.disdrometer.parsivel._read_fmi", "cloudnetpy.instruments.disdrometer.parsivel.parsivel2nc", "cloudnetpy.output._get_netcdf_dimensions", "cloudnetpy.output.save_level1b"], "language": "Python", "toolfunc_count": 4, "func_count": 5, "pytest_info": {"total_num": 54, "base_passed_num": 0}} {"id": ["cloudnetpy.cloudnetpy.products.drizzle_error._get_drizzle_indices", "cloudnetpy.cloudnetpy.products.drizzle_error.get_drizzle_error", "cloudnetpy.cloudnetpy.utils.l2norm_weighted", "cloudnetpy.cloudnetpy.products.drizzle_error._calc_error"], "project": "cloudnetpy", "origin_file": ["cloudnetpy/products/drizzle_error.py", "cloudnetpy/products/drizzle_error.py", "cloudnetpy/utils.py", "cloudnetpy/products/drizzle_error.py"], "test_list": ["tests/unit/test_drizzle.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 188, "func_start_lineno": 36, "func_end_lineno": 41, "func_code": "def _get_drizzle_indices(diameter: np.ndarray) -> dict:\n return {\n \"drizzle\": diameter > 0,\n \"small\": np.logical_and(diameter <= 1e-4, diameter > 1e-5),\n \"tiny\": np.logical_and(diameter <= 1e-5, diameter > 0),\n }"}, {"class_start_lineno": 1, "class_end_lineno": 188, "func_start_lineno": 11, "func_end_lineno": 33, "func_code": "def get_drizzle_error(\n categorize: DrizzleSource,\n drizzle_parameters: DrizzleSolver,\n) -> dict:\n \"\"\"Estimates error and bias for drizzle classification.\n\n Args:\n categorize: The :class:`DrizzleSource` instance.\n drizzle_parameters: The :class:`DrizzleSolver` instance.\n\n Returns:\n dict: Dictionary containing information of estimated error and bias for drizzle\n\n \"\"\"\n parameters = drizzle_parameters.params\n drizzle_indices = _get_drizzle_indices(parameters[\"Do\"])\n error_input = _read_input_uncertainty(categorize, \"error\")\n if utils.isscalar(error_input[0]) is True: # Constant Z error\n z_error, bias_error = error_input\n z_error = np.full(categorize.z.shape, z_error)\n error_input = z_error, bias_error\n bias_input = _read_input_uncertainty(categorize, \"bias\")\n return _calc_errors(drizzle_indices, error_input, bias_input)"}, {"class_start_lineno": 1, "class_end_lineno": 1151, "func_start_lineno": 504, "func_end_lineno": 529, "func_code": "def l2norm_weighted(\n values: tuple,\n overall_scale: float,\n term_weights: tuple,\n) -> ma.MaskedArray:\n \"\"\"Calculates scaled and weighted Euclidean distance.\n\n Calculated distance is of form: scale * sqrt((a1*a)**2 + (b1*b)**2 + ...)\n where a, b, ... are terms to be summed and a1, a2, ... are optional weights\n for the terms.\n\n Args:\n values: Tuple containing the values.\n overall_scale: Scale factor for the calculated Euclidean distance.\n term_weights: Weights for the terms. Must be single float or a list of numbers\n (one per term).\n\n Returns:\n Scaled and weighted Euclidean distance.\n\n TODO: Use masked arrays instead of tuples.\n\n \"\"\"\n generic_values = ma.array(values, dtype=object)\n weighted_values = ma.multiply(generic_values, term_weights)\n return overall_scale * l2norm(*weighted_values)"}, {"class_start_lineno": 1, "class_end_lineno": 188, "func_start_lineno": 140, "func_end_lineno": 153, "func_code": "def _calc_error(\n scale: float,\n weights: tuple,\n error_input: tuple,\n *,\n add_mu: bool = False,\n add_mu_small: bool = False,\n) -> ma.MaskedArray:\n error = utils.l2norm_weighted(error_input, scale, weights)\n if add_mu is True:\n error = utils.l2norm(error, MU_ERROR)\n if add_mu_small is True:\n error = utils.l2norm(error, MU_ERROR_SMALL)\n return error"}], "type": ["function_empty", "TDD"], "node": ["cloudnetpy.products.drizzle_error._get_drizzle_indices", "cloudnetpy.products.drizzle_error.get_drizzle_error", "cloudnetpy.utils.l2norm_weighted", "cloudnetpy.products.drizzle_error._calc_error"], "language": "Python", "toolfunc_count": 2, "func_count": 4, "pytest_info": {"total_num": 77, "base_passed_num": 55}} {"id": ["cloudnetpy.cloudnetpy.utils.l2norm_weighted", "cloudnetpy.cloudnetpy.products.drizzle_error._calc_error"], "project": "cloudnetpy", "origin_file": ["cloudnetpy/utils.py", "cloudnetpy/products/drizzle_error.py"], "test_list": ["tests/unit/test_drizzle_error.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 1151, "func_start_lineno": 504, "func_end_lineno": 529, "func_code": "def l2norm_weighted(\n values: tuple,\n overall_scale: float,\n term_weights: tuple,\n) -> ma.MaskedArray:\n \"\"\"Calculates scaled and weighted Euclidean distance.\n\n Calculated distance is of form: scale * sqrt((a1*a)**2 + (b1*b)**2 + ...)\n where a, b, ... are terms to be summed and a1, a2, ... are optional weights\n for the terms.\n\n Args:\n values: Tuple containing the values.\n overall_scale: Scale factor for the calculated Euclidean distance.\n term_weights: Weights for the terms. Must be single float or a list of numbers\n (one per term).\n\n Returns:\n Scaled and weighted Euclidean distance.\n\n TODO: Use masked arrays instead of tuples.\n\n \"\"\"\n generic_values = ma.array(values, dtype=object)\n weighted_values = ma.multiply(generic_values, term_weights)\n return overall_scale * l2norm(*weighted_values)"}, {"class_start_lineno": 1, "class_end_lineno": 188, "func_start_lineno": 140, "func_end_lineno": 153, "func_code": "def _calc_error(\n scale: float,\n weights: tuple,\n error_input: tuple,\n *,\n add_mu: bool = False,\n add_mu_small: bool = False,\n) -> ma.MaskedArray:\n error = utils.l2norm_weighted(error_input, scale, weights)\n if add_mu is True:\n error = utils.l2norm(error, MU_ERROR)\n if add_mu_small is True:\n error = utils.l2norm(error, MU_ERROR_SMALL)\n return error"}], "type": ["function_empty", "TDD"], "node": ["cloudnetpy.utils.l2norm_weighted", "cloudnetpy.products.drizzle_error._calc_error"], "language": "Python", "toolfunc_count": 1, "func_count": 2, "pytest_info": {"total_num": 26, "base_passed_num": 15}} {"id": ["cloudnetpy.cloudnetpy.categorize.droplet.interpolate_lwp", "cloudnetpy.cloudnetpy.categorize.droplet.find_liquid"], "project": "cloudnetpy", "origin_file": ["cloudnetpy/categorize/droplet.py", "cloudnetpy/categorize/droplet.py"], "test_list": ["tests/unit/test_droplet.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 245, "func_start_lineno": 225, "func_end_lineno": 238, "func_code": "def interpolate_lwp(obs: ClassData) -> np.ndarray:\n \"\"\"Linear interpolation of liquid water path to fill masked values.\n\n Args:\n obs: The :class:`ClassData` instance.\n\n Returns:\n Liquid water path where the masked values are filled by interpolation.\n\n \"\"\"\n if obs.lwp.all() is ma.masked:\n return np.zeros(obs.time.shape)\n ind = ma.where(obs.lwp)\n return np.interp(obs.time, obs.time[ind], obs.lwp[ind])"}, {"class_start_lineno": 1, "class_end_lineno": 245, "func_start_lineno": 52, "func_end_lineno": 121, "func_code": "def find_liquid(\n obs: ClassData,\n peak_amp: float = 1e-6,\n max_width: float = 300,\n min_points: int = 3,\n min_top_der: float = 1e-7,\n min_lwp: float = 0,\n min_alt: float = 100,\n) -> np.ndarray:\n \"\"\"Estimate liquid layers from SNR-screened attenuated backscatter.\n\n Args:\n obs: The :class:`ClassData` instance.\n peak_amp: Minimum value of peak. Default is 1e-6.\n max_width: Maximum width of peak. Default is 300 (m).\n min_points: Minimum number of valid points in peak. Default is 3.\n min_top_der: Minimum derivative above peak, defined as\n (beta_peak-beta_top) / (alt_top-alt_peak). Default is 1e-7.\n min_lwp: Minimum value from linearly interpolated lwp (kg m-2)\n measured by the mwr. Default is 0.\n min_alt: Minimum altitude of the peak from the ground. Default is 100 (m).\n\n Returns:\n 2-D boolean array denoting liquid layers.\n\n References:\n The method is based on Tuononen, M. et.al, 2019,\n https://acp.copernicus.org/articles/19/1985/2019/.\n\n \"\"\"\n\n def _is_proper_peak() -> bool:\n conditions = (\n npoints >= min_points,\n peak_width < max_width,\n top_der > min_top_der,\n is_positive_lwp,\n peak_alt > min_alt,\n )\n return all(conditions)\n\n lwp_int = interpolate_lwp(obs)\n beta = ma.copy(obs.beta)\n height = obs.height\n\n is_liquid = np.zeros(beta.shape, dtype=bool)\n base_below_peak = utils.n_elements(height, 200)\n top_above_peak = utils.n_elements(height, 150)\n difference = ma.array(np.diff(beta, axis=1))\n beta_diff = difference.filled(0)\n beta = beta.filled(0)\n peak_indices = _find_strong_peaks(beta, peak_amp)\n\n for n, peak in zip(*peak_indices, strict=True):\n lprof = beta[n, :]\n dprof = beta_diff[n, :]\n try:\n base = ind_base(dprof, peak, base_below_peak, 4)\n top = ind_top(dprof, peak, height.shape[0], top_above_peak, 4)\n except IndexError:\n continue\n npoints = np.count_nonzero(lprof[base : top + 1])\n peak_width = height[top] - height[base]\n peak_alt = height[peak] - height[0]\n top_der = (lprof[peak] - lprof[top]) / (height[top] - height[peak])\n is_positive_lwp = lwp_int[n] >= min_lwp\n if _is_proper_peak():\n is_liquid[n, base : top + 1] = True\n\n return is_liquid"}], "type": ["function_empty"], "node": ["cloudnetpy.categorize.droplet.interpolate_lwp", "cloudnetpy.categorize.droplet.find_liquid"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 18, "base_passed_num": 15}} {"id": ["cloudnetpy.cloudnetpy.categorize.itu._calc_line_shape", "cloudnetpy.cloudnetpy.categorize.itu._calc_oxygen_refractivity", "cloudnetpy.cloudnetpy.categorize.itu.calc_gas_specific_attenuation"], "project": "cloudnetpy", "origin_file": ["cloudnetpy/categorize/itu.py", "cloudnetpy/categorize/itu.py", "cloudnetpy/categorize/itu.py"], "test_list": ["tests/unit/test_itu.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 243, "func_start_lineno": 74, "func_end_lineno": 89, "func_code": "def _calc_line_shape(\n frequency: float | np.floating,\n center: npt.NDArray,\n width: npt.NDArray,\n correction: npt.NDArray | float,\n) -> npt.NDArray:\n return (\n frequency\n / center\n * (\n (width - correction * (center - frequency))\n / ((center - frequency) ** 2 + width**2)\n + (width - correction * (center + frequency))\n / ((center + frequency) ** 2 + width**2)\n )\n )"}, {"class_start_lineno": 1, "class_end_lineno": 243, "func_start_lineno": 92, "func_end_lineno": 116, "func_code": "def _calc_oxygen_refractivity(\n dry_pressure: npt.NDArray,\n vapor_pressure: npt.NDArray,\n frequency: float | np.floating,\n theta: npt.NDArray,\n) -> npt.NDArray:\n f0, a1, a2, a3, a4, a5, a6 = OXYGEN_TABLE[:, :, np.newaxis, np.newaxis]\n strength = a1 * 1e-7 * dry_pressure * theta**3 * np.exp(a2 * (1 - theta))\n width = (\n a3 * 1e-4 * (dry_pressure * theta ** (0.8 - a4) + 1.1 * vapor_pressure * theta)\n )\n width = np.sqrt(width**2 + 2.25e-6)\n correction = (a5 + a6 * theta) * 1e-4 * (dry_pressure + vapor_pressure) * theta**0.8\n shape = _calc_line_shape(frequency, f0, width, correction)\n d = 5.6e-4 * (dry_pressure + vapor_pressure) * theta**0.8\n continuum = (\n frequency\n * dry_pressure\n * theta**2\n * (\n 6.14e-5 / (d * (1 + (frequency / d) ** 2))\n + ((1.4e-12 * dry_pressure * theta**1.5) / (1 + 1.9e-5 * frequency**1.5))\n )\n )\n return np.sum(strength * shape, axis=0) + continuum"}, {"class_start_lineno": 1, "class_end_lineno": 243, "func_start_lineno": 42, "func_end_lineno": 71, "func_code": "def calc_gas_specific_attenuation(\n pressure: npt.NDArray,\n vapor_pressure: npt.NDArray,\n temperature: npt.NDArray,\n frequency: float | np.floating,\n) -> npt.NDArray:\n \"\"\"Calculate specific attenuation due to dry air and water vapor for\n frequency up to 1000 GHz.\n\n Args:\n pressure: Pressure (Pa)\n vapor_pressure: Water vapor partial pressure (Pa)\n temperature: Temperature (K)\n frequency: Frequency (GHz)\n\n References:\n ITU-R P.676-13: Attenuation by atmospheric gases and related effects.\n https://www.itu.int/dms_pubrec/itu-r/rec/p/R-REC-P.676-13-202208-I!!PDF-E.pdf\n \"\"\"\n pressure = pressure * con.PA_TO_HPA\n vapor_pressure = vapor_pressure * con.PA_TO_HPA\n dry_pressure = pressure - vapor_pressure\n theta = 300 / temperature\n oxygen_refractivity = _calc_oxygen_refractivity(\n dry_pressure, vapor_pressure, frequency, theta\n )\n vapor_refractivity = _calc_vapor_refractivity(\n dry_pressure, vapor_pressure, frequency, theta\n )\n return 0.1820 * frequency * (oxygen_refractivity + vapor_refractivity)"}], "type": ["function_empty", "TDD"], "node": ["cloudnetpy.categorize.itu._calc_line_shape", "cloudnetpy.categorize.itu._calc_oxygen_refractivity", "cloudnetpy.categorize.itu.calc_gas_specific_attenuation"], "language": "Python", "toolfunc_count": 1, "func_count": 3, "pytest_info": {"total_num": 2, "base_passed_num": 0}} {"id": ["cloudnetpy.cloudnetpy.categorize.atmos_utils.fill_clouds_with_lwc_dz", "cloudnetpy.cloudnetpy.products.lwc.Lwc::_init_lwc_adiabatic", "cloudnetpy.cloudnetpy.categorize.atmos_utils.calc_saturation_vapor_pressure", "cloudnetpy.cloudnetpy.categorize.atmos_utils.calc_mixing_ratio", "cloudnetpy.cloudnetpy.categorize.atmos_utils.calc_lwc_change_rate"], "project": "cloudnetpy", "origin_file": ["cloudnetpy/categorize/atmos_utils.py", "cloudnetpy/products/lwc.py", "cloudnetpy/products/lwc.py", "cloudnetpy/categorize/atmos_utils.py", "cloudnetpy/categorize/atmos_utils.py", "cloudnetpy/categorize/atmos_utils.py"], "test_list": ["tests/unit/test_lwc.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 357, "func_start_lineno": 154, "func_end_lineno": 172, "func_code": "def fill_clouds_with_lwc_dz(\n temperature: np.ndarray, pressure: np.ndarray, is_liquid: np.ndarray\n) -> np.ndarray:\n \"\"\"Fills liquid clouds with lwc change rate at the cloud bases.\n\n Args:\n temperature: 2D temperature array (K).\n pressure: 2D pressure array (Pa).\n is_liquid: Boolean array indicating presence of liquid clouds.\n\n Returns:\n Liquid water content change rate (kg m-3 m-1), so that for each cloud the base\n value is filled for the whole cloud.\n\n \"\"\"\n lwc_dz = get_lwc_change_rate_at_bases(temperature, pressure, is_liquid)\n lwc_dz_filled = ma.zeros(lwc_dz.shape)\n lwc_dz_filled[is_liquid] = utils.ffill(lwc_dz[is_liquid])\n return lwc_dz_filled"}, {"class_start_lineno": 120, "class_end_lineno": 167, "func_start_lineno": 146, "func_end_lineno": 152, "func_code": " def _init_lwc_adiabatic(self) -> np.ndarray:\n \"\"\"Returns theoretical adiabatic lwc in liquid clouds (kg/m3).\"\"\"\n lwc_dz = atmos_utils.fill_clouds_with_lwc_dz(\n *self.lwc_source.atmosphere,\n self.is_liquid,\n )\n return atmos_utils.calc_adiabatic_lwc(lwc_dz, self.height)"}, {"class_start_lineno": 120, "class_end_lineno": 167, "func_start_lineno": 134, "func_end_lineno": 140, "func_code": " def __init__(self, lwc_source: LwcSource):\n self.lwc_source = lwc_source\n self.height = lwc_source.getvar(\"height\")\n self.is_liquid = self._get_liquid()\n self.lwc_adiabatic = self._init_lwc_adiabatic()\n self.lwc = self._adiabatic_lwc_to_lwc()\n self._mask_rain()"}, {"class_start_lineno": 1, "class_end_lineno": 357, "func_start_lineno": 245, "func_end_lineno": 266, "func_code": "def calc_saturation_vapor_pressure(temperature: np.ndarray) -> np.ndarray:\n \"\"\"Goff-Gratch formula for saturation vapor pressure over water adopted by WMO.\n\n Args:\n temperature: Temperature (K).\n\n Returns:\n Saturation vapor pressure (Pa).\n\n \"\"\"\n ratio = con.T0 / temperature\n inv_ratio = ratio**-1\n return (\n 10\n ** (\n 10.79574 * (1 - ratio)\n - 5.028 * np.log10(inv_ratio)\n + 1.50475e-4 * (1 - (10 ** (-8.2969 * (inv_ratio - 1))))\n + 0.42873e-3 * (10 ** (4.76955 * (1 - ratio)) - 1)\n + 0.78614\n )\n ) * con.HPA_TO_PA"}, {"class_start_lineno": 1, "class_end_lineno": 357, "func_start_lineno": 269, "func_end_lineno": 280, "func_code": "def calc_mixing_ratio(vapor_pressure: np.ndarray, pressure: np.ndarray) -> np.ndarray:\n \"\"\"Calculates mixing ratio from partial vapor pressure and pressure.\n\n Args:\n vapor_pressure: Partial pressure of water vapor (Pa).\n pressure: Atmospheric pressure (Pa).\n\n Returns:\n Mixing ratio (kg kg-1).\n\n \"\"\"\n return con.MW_RATIO * vapor_pressure / (pressure - vapor_pressure)"}, {"class_start_lineno": 1, "class_end_lineno": 357, "func_start_lineno": 201, "func_end_lineno": 242, "func_code": "def calc_lwc_change_rate(temperature: np.ndarray, pressure: np.ndarray) -> np.ndarray:\n \"\"\"Returns rate of change of condensable water (LWC).\n\n Calculates the theoretical adiabatic rate of increase of LWC\n with height, given the cloud base temperature and pressure.\n\n Args:\n temperature: Temperature of cloud base (K).\n pressure: Pressure of cloud base (Pa).\n\n Returns:\n dlwc/dz (kg m-3 m-1)\n\n References:\n Brenguier, 1991, https://doi.org/10.1175/1520-0469(1991)048<0264:POTCPA>2.0.CO;2\n\n \"\"\"\n svp = calc_saturation_vapor_pressure(temperature)\n svp_mixing_ratio = calc_mixing_ratio(svp, pressure)\n air_density = calc_air_density(pressure, temperature, svp_mixing_ratio)\n\n e = 0.622\n Cp = 1004 # J kg-1 K-1\n Lv = 2.45e6 # J kg-1 = Pa m3 kg-1\n qs = svp_mixing_ratio # kg kg-1\n pa = air_density # kg m-3\n es = svp # Pa\n P = pressure # Pa\n T = temperature # K\n\n # See Appendix B in Brenguier (1991) for the derivation of the following equation\n dqs_dp = (\n -(1 - (Cp * T) / (e * Lv))\n * (((Cp * T) / (e * Lv)) + ((Lv * qs * pa) / (P - es))) ** -1\n * (e * es)\n * (P - es) ** -2\n )\n\n # Using hydrostatic equation to convert dqs_dp to dqs_dz\n dqs_dz = dqs_dp * air_density * -scipy.constants.g\n\n return dqs_dz * air_density"}], "type": ["function_empty", "TDD"], "node": ["cloudnetpy.categorize.atmos_utils.fill_clouds_with_lwc_dz", "cloudnetpy.products.lwc.Lwc._init_lwc_adiabatic", "cloudnetpy.products.lwc.Lwc.__init__", "cloudnetpy.categorize.atmos_utils.calc_saturation_vapor_pressure", "cloudnetpy.categorize.atmos_utils.calc_mixing_ratio", "cloudnetpy.categorize.atmos_utils.calc_lwc_change_rate"], "language": "Python", "toolfunc_count": 3, "func_count": 5, "pytest_info": {"total_num": 37, "base_passed_num": 0}} {"id": ["cloudnetpy.cloudnetpy.utils._parse_global_attribute_numeral", "cloudnetpy.cloudnetpy.utils.add_site_geolocation", "cloudnetpy.cloudnetpy.output._get_netcdf_dimensions", "cloudnetpy.cloudnetpy.output.save_level1b"], "project": "cloudnetpy", "origin_file": ["cloudnetpy/utils.py", "cloudnetpy/utils.py", "cloudnetpy/output.py", "cloudnetpy/output.py"], "test_list": ["tests/unit/test_mira.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 1151, "func_start_lineno": 1132, "func_end_lineno": 1140, "func_code": "def _parse_global_attribute_numeral(dataset: netCDF4.Dataset, key: str) -> float | None:\n new_str = \"\"\n attr = getattr(dataset, key)\n if attr == \"Unknown\":\n return None\n for char in attr:\n if char.isdigit() or char == \".\":\n new_str += char\n return float(new_str)"}, {"class_start_lineno": 1, "class_end_lineno": 1151, "func_start_lineno": 1057, "func_end_lineno": 1129, "func_code": "def add_site_geolocation(\n data: dict,\n *,\n gps: bool,\n site_meta: dict | None = None,\n dataset: netCDF4.Dataset | None = None,\n):\n tmp_data = {}\n tmp_source = {}\n\n for key in (\"latitude\", \"longitude\", \"altitude\"):\n value = None\n source = None\n # Prefer accurate GPS coordinates.\n if gps:\n values = None\n if isinstance(dataset, netCDF4.Dataset) and key in dataset.variables:\n values = dataset[key][:]\n elif key in data:\n values = data[key].data\n if (\n values is not None\n and not np.all(ma.getmaskarray(values))\n and np.any(values != 0)\n ):\n value = ma.masked_where(values == 0, values)\n source = \"GPS\"\n # User-supplied site coordinate.\n if value is None and site_meta is not None and key in site_meta:\n value = float(site_meta[key])\n source = \"site coordinates\"\n # From source data (CHM15k, CL61, MRR-PRO, Copernicus, Galileo...).\n # Assume value is manually set, so cannot trust it.\n if (\n value is None\n and isinstance(dataset, netCDF4.Dataset)\n and key in dataset.variables\n and not np.all(ma.getmaskarray(dataset[key][:]))\n ):\n value = dataset[key][:]\n source = \"raw file\"\n # From source global attributes (MIRA).\n # Seems to be manually set, so cannot trust it.\n if (\n value is None\n and isinstance(dataset, netCDF4.Dataset)\n and hasattr(dataset, key.capitalize())\n ):\n value = _parse_global_attribute_numeral(dataset, key.capitalize())\n source = \"raw file\"\n if value is not None:\n tmp_data[key] = value\n tmp_source[key] = source\n\n if \"latitude\" in tmp_data and \"longitude\" in tmp_data:\n lat = np.atleast_1d(tmp_data[\"latitude\"])\n lon = np.atleast_1d(tmp_data[\"longitude\"])\n lon[lon > 180] - 360\n if _are_stationary(lat, lon):\n tmp_data[\"latitude\"] = float(ma.mean(lat))\n tmp_data[\"longitude\"] = float(ma.mean(lon))\n else:\n tmp_data[\"latitude\"] = lat\n tmp_data[\"longitude\"] = lon\n\n if \"altitude\" in tmp_data:\n alt = np.atleast_1d(tmp_data[\"altitude\"])\n if ma.max(alt) - ma.min(alt) < 100:\n tmp_data[\"altitude\"] = float(ma.mean(alt))\n\n for key in (\"latitude\", \"longitude\", \"altitude\"):\n if key in tmp_data:\n data[key] = CloudnetArray(tmp_data[key], key, source=tmp_source[key])"}, {"class_start_lineno": 1, "class_end_lineno": 494, "func_start_lineno": 54, "func_end_lineno": 74, "func_code": "def _get_netcdf_dimensions(obj) -> dict:\n dimensions = {\n key: len(obj.data[key][:]) for key in (\"time\", \"range\") if key in obj.data\n }\n # RPG cloud radar\n if \"chirp_start_indices\" in obj.data:\n dimensions[\"chirp_sequence\"] = len(obj.data[\"chirp_start_indices\"][:])\n # disdrometer\n if hasattr(obj, \"n_diameter\") and hasattr(obj, \"n_velocity\"):\n dimensions[\"diameter\"] = obj.n_diameter\n dimensions[\"velocity\"] = obj.n_velocity\n dimensions[\"nv\"] = 2\n # HATPRO l1c\n if \"tb\" in obj.data:\n dimensions[\"frequency\"] = obj.data[\"tb\"][:].shape[1]\n dimensions[\"receiver_nb\"] = len(obj.data[\"receiver_nb\"][:])\n dimensions[\"band\"] = 2\n dimensions[\"t_amb_nb\"] = 2\n if \"irt\" in obj.data:\n dimensions[\"ir_channel\"] = obj.data[\"irt\"][:].shape[1]\n return dimensions"}, {"class_start_lineno": 1, "class_end_lineno": 494, "func_start_lineno": 21, "func_end_lineno": 51, "func_code": "def save_level1b(\n obj,\n output_file: PathLike | str,\n uuid: UUID | str | None = None,\n) -> str:\n \"\"\"Saves Cloudnet Level 1b file.\"\"\"\n dimensions = _get_netcdf_dimensions(obj)\n with init_file(output_file, dimensions, obj.data, uuid) as nc:\n file_uuid = nc.file_uuid\n fix_attribute_name(nc)\n location = obj.site_meta[\"name\"]\n nc.cloudnet_file_type = obj.instrument.domain\n nc.title = get_l1b_title(obj.instrument, location)\n if isinstance(obj.date, list):\n nc.year, nc.month, nc.day = obj.date\n elif isinstance(obj.date, datetime.date):\n nc.year = str(obj.date.year)\n nc.month = str(obj.date.month).zfill(2)\n nc.day = str(obj.date.day).zfill(2)\n else:\n raise TypeError\n nc.location = location\n nc.history = get_l1b_history(obj.instrument)\n nc.source = get_l1b_source(obj.instrument)\n if hasattr(obj, \"serial_number\") and obj.serial_number is not None:\n nc.serial_number = obj.serial_number\n if hasattr(obj, \"software\"):\n for software, version in obj.software.items():\n nc.setncattr(f\"{software}_version\", version)\n nc.references = get_references()\n return file_uuid"}], "type": ["function_empty", "TDD"], "node": ["cloudnetpy.utils._parse_global_attribute_numeral", "cloudnetpy.utils.add_site_geolocation", "cloudnetpy.output._get_netcdf_dimensions", "cloudnetpy.output.save_level1b"], "language": "Python", "toolfunc_count": 1, "func_count": 4, "pytest_info": {"total_num": 31, "base_passed_num": 0}} {"id": ["cloudnetpy.cloudnetpy.utils.rebin_1d", "cloudnetpy.cloudnetpy.cloudnetarray.CloudnetArray::rebin_data", "cloudnetpy.cloudnetpy.utils.binvec"], "project": "cloudnetpy", "origin_file": ["cloudnetpy/utils.py", "cloudnetpy/cloudnetarray.py", "cloudnetpy/categorize/mwr.py", "cloudnetpy/utils.py"], "test_list": ["tests/unit/test_mwr.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 1151, "func_start_lineno": 195, "func_end_lineno": 231, "func_code": "def rebin_1d(\n x_in: np.ndarray,\n array: np.ndarray | ma.MaskedArray,\n x_new: np.ndarray,\n statistic: str = \"mean\",\n *,\n mask_zeros: bool = True,\n) -> ma.MaskedArray:\n \"\"\"Rebins 1D array.\n\n Args:\n x_in: 1-D array with shape (n,).\n array: 1-D input data with shape (m,).\n x_new: 1-D target vector (center points) with shape (N,).\n statistic: Statistic to be calculated. Possible statistics are 'mean', 'std'.\n Default is 'mean'.\n mask_zeros: Whether to mask 0 values in the returned array. Default is True.\n\n Returns:\n Re-binned data with shape (N,).\n\n \"\"\"\n edges = binvec(x_new)\n result = np.zeros(len(x_new))\n array_screened = ma.masked_invalid(array, copy=True) # data may contain nan-values\n mask = ~array_screened.mask\n if ma.any(array_screened[mask]):\n result, _, _ = stats.binned_statistic(\n x_in[mask],\n array_screened[mask],\n statistic=statistic,\n bins=edges,\n )\n result[~np.isfinite(result)] = 0\n if mask_zeros:\n return ma.masked_equal(result, 0)\n return ma.array(result)"}, {"class_start_lineno": 14, "class_end_lineno": 211, "func_start_lineno": 61, "func_end_lineno": 84, "func_code": " def rebin_data(\n self, time: np.ndarray, time_new: np.ndarray, *, mask_zeros: bool = True\n ) -> list:\n \"\"\"Rebins `data` in time.\n\n Args:\n time: 1D time array.\n time_new: 1D new time array.\n mask_zeros: Whether to mask 0 values in the returned array. Default is True.\n\n Returns:\n Time indices without data.\n\n \"\"\"\n if self.data.ndim == 1:\n self.data = utils.rebin_1d(time, self.data, time_new, mask_zeros=mask_zeros)\n bad_indices = list(np.where(self.data == ma.masked)[0])\n else:\n if not isinstance(self.data, ma.MaskedArray):\n self.data = ma.masked_array(self.data)\n self.data, bad_indices = utils.rebin_2d(\n time, self.data, time_new, mask_zeros=mask_zeros\n )\n return bad_indices"}, {"class_start_lineno": 11, "class_end_lineno": 50, "func_start_lineno": 24, "func_end_lineno": 32, "func_code": " def rebin_to_grid(self, time_grid: np.ndarray) -> None:\n \"\"\"Approximates lwp and its error in a grid using mean.\n\n Args:\n time_grid: 1D target time grid.\n\n \"\"\"\n for array in self.data.values():\n array.rebin_data(self.time, time_grid)"}, {"class_start_lineno": 1, "class_end_lineno": 1151, "func_start_lineno": 124, "func_end_lineno": 140, "func_code": "def binvec(x: np.ndarray | list) -> np.ndarray:\n \"\"\"Converts 1-D center points to bins with even spacing.\n\n Args:\n x: 1-D array of N real values.\n\n Returns:\n ndarray: N + 1 edge values.\n\n Examples:\n >>> binvec([1, 2, 3])\n [0.5, 1.5, 2.5, 3.5]\n\n \"\"\"\n edge1 = x[0] - (x[1] - x[0]) / 2\n edge2 = x[-1] + (x[-1] - x[-2]) / 2\n return np.linspace(edge1, edge2, len(x) + 1)"}], "type": ["function_empty", "TDD"], "node": ["cloudnetpy.utils.rebin_1d", "cloudnetpy.cloudnetarray.CloudnetArray.rebin_data", "cloudnetpy.categorize.mwr.Mwr.rebin_to_grid", "cloudnetpy.utils.binvec"], "language": "Python", "toolfunc_count": 2, "func_count": 3, "pytest_info": {"total_num": 4, "base_passed_num": 3}} {"id": ["cloudnetpy.cloudnetpy.utils.get_sorted_filenames", "cloudnetpy.cloudnetpy.instruments.rpg.rpg2nc", "cloudnetpy.cloudnetpy.output._get_netcdf_dimensions", "cloudnetpy.cloudnetpy.output.save_level1b"], "project": "cloudnetpy", "origin_file": ["cloudnetpy/utils.py", "cloudnetpy/instruments/rpg.py", "cloudnetpy/output.py", "cloudnetpy/output.py"], "test_list": ["tests/unit/test_rpg.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 1151, "func_start_lineno": 802, "func_end_lineno": 810, "func_code": "def get_sorted_filenames(file_path: str, extension: str) -> list:\n \"\"\"Returns full paths of files with some extension, sorted by filename.\"\"\"\n extension = extension.lower()\n all_files = os.listdir(file_path)\n files = [\n f\"{file_path}/{file}\" for file in all_files if file.lower().endswith(extension)\n ]\n files.sort()\n return files"}, {"class_start_lineno": 1, "class_end_lineno": 524, "func_start_lineno": 25, "func_end_lineno": 85, "func_code": "def rpg2nc(\n path_to_l1_files: str,\n output_file: str,\n site_meta: dict,\n uuid: str | None = None,\n date: str | None = None,\n) -> tuple[str, list]:\n \"\"\"Converts RPG-FMCW-94 cloud radar data into Cloudnet Level 1b netCDF file.\n\n This function reads one day of RPG Level 1 cloud radar binary files,\n concatenates the data and writes a netCDF file.\n\n Args:\n path_to_l1_files: Folder containing one day of RPG LV1 files.\n output_file: Output file name.\n site_meta: Dictionary containing information about the\n site. Required key value pairs are `altitude` (metres above mean\n sea level) and `name`.\n uuid: Set specific UUID for the file.\n date: Expected date in the input files. If not set,\n all files will be used. This might cause unexpected behavior if\n there are files from several days. If date is set as 'YYYY-MM-DD',\n only files that match the date will be used.\n\n Returns:\n 2-element tuple containing\n\n - UUID of the generated file.\n - Files used in the processing.\n\n Raises:\n ValidTimeStampError: No valid timestamps found.\n\n Examples:\n >>> from cloudnetpy.instruments import rpg2nc\n >>> site_meta = {'name': 'Hyytiala', 'altitude': 174}\n >>> rpg2nc('/path/to/files/', 'test.nc', site_meta)\n\n \"\"\"\n l1_files = utils.get_sorted_filenames(path_to_l1_files, \".LV1\")\n fmcw94_objects, valid_files = _get_fmcw94_objects(l1_files, date)\n one_day_of_data = create_one_day_data_record(fmcw94_objects)\n if not valid_files:\n return \"\", []\n print_info(one_day_of_data)\n fmcw = Fmcw(one_day_of_data, site_meta)\n fmcw.convert_time_to_fraction_hour()\n fmcw.mask_invalid_ldr()\n fmcw.mask_invalid_width()\n fmcw.sort_timestamps()\n fmcw.remove_duplicate_timestamps()\n fmcw.linear_to_db((\"Zh\", \"antenna_gain\"))\n fmcw.convert_units()\n fmcw.add_site_geolocation()\n valid_ind = fmcw.add_zenith_angle()\n fmcw.screen_time_indices(valid_ind)\n fmcw.add_height()\n attributes = output.add_time_attribute(RPG_ATTRIBUTES, fmcw.date)\n output.update_attributes(fmcw.data, attributes)\n uuid = output.save_level1b(fmcw, output_file, uuid)\n return uuid, valid_files"}, {"class_start_lineno": 1, "class_end_lineno": 494, "func_start_lineno": 54, "func_end_lineno": 74, "func_code": "def _get_netcdf_dimensions(obj) -> dict:\n dimensions = {\n key: len(obj.data[key][:]) for key in (\"time\", \"range\") if key in obj.data\n }\n # RPG cloud radar\n if \"chirp_start_indices\" in obj.data:\n dimensions[\"chirp_sequence\"] = len(obj.data[\"chirp_start_indices\"][:])\n # disdrometer\n if hasattr(obj, \"n_diameter\") and hasattr(obj, \"n_velocity\"):\n dimensions[\"diameter\"] = obj.n_diameter\n dimensions[\"velocity\"] = obj.n_velocity\n dimensions[\"nv\"] = 2\n # HATPRO l1c\n if \"tb\" in obj.data:\n dimensions[\"frequency\"] = obj.data[\"tb\"][:].shape[1]\n dimensions[\"receiver_nb\"] = len(obj.data[\"receiver_nb\"][:])\n dimensions[\"band\"] = 2\n dimensions[\"t_amb_nb\"] = 2\n if \"irt\" in obj.data:\n dimensions[\"ir_channel\"] = obj.data[\"irt\"][:].shape[1]\n return dimensions"}, {"class_start_lineno": 1, "class_end_lineno": 494, "func_start_lineno": 21, "func_end_lineno": 51, "func_code": "def save_level1b(\n obj,\n output_file: PathLike | str,\n uuid: UUID | str | None = None,\n) -> str:\n \"\"\"Saves Cloudnet Level 1b file.\"\"\"\n dimensions = _get_netcdf_dimensions(obj)\n with init_file(output_file, dimensions, obj.data, uuid) as nc:\n file_uuid = nc.file_uuid\n fix_attribute_name(nc)\n location = obj.site_meta[\"name\"]\n nc.cloudnet_file_type = obj.instrument.domain\n nc.title = get_l1b_title(obj.instrument, location)\n if isinstance(obj.date, list):\n nc.year, nc.month, nc.day = obj.date\n elif isinstance(obj.date, datetime.date):\n nc.year = str(obj.date.year)\n nc.month = str(obj.date.month).zfill(2)\n nc.day = str(obj.date.day).zfill(2)\n else:\n raise TypeError\n nc.location = location\n nc.history = get_l1b_history(obj.instrument)\n nc.source = get_l1b_source(obj.instrument)\n if hasattr(obj, \"serial_number\") and obj.serial_number is not None:\n nc.serial_number = obj.serial_number\n if hasattr(obj, \"software\"):\n for software, version in obj.software.items():\n nc.setncattr(f\"{software}_version\", version)\n nc.references = get_references()\n return file_uuid"}], "type": ["function_empty", "TDD"], "node": ["cloudnetpy.utils.get_sorted_filenames", "cloudnetpy.instruments.rpg.rpg2nc", "cloudnetpy.output._get_netcdf_dimensions", "cloudnetpy.output.save_level1b"], "language": "Python", "toolfunc_count": 2, "func_count": 4, "pytest_info": {"total_num": 34, "base_passed_num": 0}} {"id": ["cloudnetpy.cloudnetpy.utils.binvec", "cloudnetpy.cloudnetpy.utils.rebin_2d", "cloudnetpy.cloudnetpy.utils.rebin_1d"], "project": "cloudnetpy", "origin_file": ["cloudnetpy/utils.py", "cloudnetpy/utils.py", "cloudnetpy/utils.py"], "test_list": ["tests/unit/test_utils.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 1151, "func_start_lineno": 124, "func_end_lineno": 140, "func_code": "def binvec(x: np.ndarray | list) -> np.ndarray:\n \"\"\"Converts 1-D center points to bins with even spacing.\n\n Args:\n x: 1-D array of N real values.\n\n Returns:\n ndarray: N + 1 edge values.\n\n Examples:\n >>> binvec([1, 2, 3])\n [0.5, 1.5, 2.5, 3.5]\n\n \"\"\"\n edge1 = x[0] - (x[1] - x[0]) / 2\n edge2 = x[-1] + (x[-1] - x[-2]) / 2\n return np.linspace(edge1, edge2, len(x) + 1)"}, {"class_start_lineno": 1, "class_end_lineno": 1151, "func_start_lineno": 143, "func_end_lineno": 192, "func_code": "def rebin_2d(\n x_in: np.ndarray,\n array: ma.MaskedArray,\n x_new: np.ndarray,\n statistic: Literal[\"mean\", \"std\"] = \"mean\",\n n_min: int = 1,\n *,\n mask_zeros: bool = True,\n) -> tuple[ma.MaskedArray, list]:\n \"\"\"Rebins 2-D data in one dimension.\n\n Args:\n x_in: 1-D array with shape (n,).\n array: 2-D input data with shape (n, m).\n x_new: 1-D target vector (center points) with shape (N,).\n statistic: Statistic to be calculated. Possible statistics are 'mean', 'std'.\n Default is 'mean'.\n n_min: Minimum number of points to have good statistics in a bin. Default is 1.\n mask_zeros: Whether to mask 0 values in the returned array. Default is True.\n\n Returns:\n tuple: Rebinned data with shape (N, m) and indices of bins without enough data.\n \"\"\"\n edges = binvec(x_new)\n result = np.zeros((len(x_new), array.shape[1]))\n array_screened = ma.masked_invalid(array, copy=True) # data may contain nan-values\n for ind, values in enumerate(array_screened.T):\n mask = ~values.mask\n if ma.any(values[mask]):\n result[:, ind], _, _ = stats.binned_statistic(\n x_in[mask],\n values[mask],\n statistic=statistic,\n bins=edges,\n )\n result[~np.isfinite(result)] = 0\n if mask_zeros is True:\n masked_result = ma.masked_equal(result, 0)\n else:\n masked_result = ma.array(result)\n\n # Fill bins with not enough profiles\n x_hist, _ = np.histogram(x_in, bins=edges)\n empty_mask = x_hist < n_min\n masked_result[empty_mask, :] = ma.masked\n empty_indices = list(np.nonzero(empty_mask)[0])\n if len(empty_indices) > 0:\n logging.debug(\"No data in %s bins\", len(empty_indices))\n\n return masked_result, empty_indices"}, {"class_start_lineno": 1, "class_end_lineno": 1151, "func_start_lineno": 195, "func_end_lineno": 231, "func_code": "def rebin_1d(\n x_in: np.ndarray,\n array: np.ndarray | ma.MaskedArray,\n x_new: np.ndarray,\n statistic: str = \"mean\",\n *,\n mask_zeros: bool = True,\n) -> ma.MaskedArray:\n \"\"\"Rebins 1D array.\n\n Args:\n x_in: 1-D array with shape (n,).\n array: 1-D input data with shape (m,).\n x_new: 1-D target vector (center points) with shape (N,).\n statistic: Statistic to be calculated. Possible statistics are 'mean', 'std'.\n Default is 'mean'.\n mask_zeros: Whether to mask 0 values in the returned array. Default is True.\n\n Returns:\n Re-binned data with shape (N,).\n\n \"\"\"\n edges = binvec(x_new)\n result = np.zeros(len(x_new))\n array_screened = ma.masked_invalid(array, copy=True) # data may contain nan-values\n mask = ~array_screened.mask\n if ma.any(array_screened[mask]):\n result, _, _ = stats.binned_statistic(\n x_in[mask],\n array_screened[mask],\n statistic=statistic,\n bins=edges,\n )\n result[~np.isfinite(result)] = 0\n if mask_zeros:\n return ma.masked_equal(result, 0)\n return ma.array(result)"}], "type": ["function_empty", "TDD"], "node": ["cloudnetpy.utils.binvec", "cloudnetpy.utils.rebin_2d", "cloudnetpy.utils.rebin_1d"], "language": "Python", "toolfunc_count": 1, "func_count": 3, "pytest_info": {"total_num": 160, "base_passed_num": 151}} {"id": ["datachain.src.datachain.asyn.AsyncMapper::shutdown_producer", "datachain.src.datachain.asyn.AsyncMapper::iterate"], "project": "datachain", "origin_file": ["datachain/asyn.py", "datachain/asyn.py"], "test_list": ["tests/unit/test_asyn.py"], "prob_info": [{"class_start_lineno": 26, "class_end_lineno": 197, "func_start_lineno": 84, "func_end_lineno": 98, "func_code": " def shutdown_producer(self) -> None:\n \"\"\"\n Signal the producer to stop and drain any remaining items from the work_queue.\n\n This method sets an internal event, `_shutdown_producer`, which tells the\n producer that it should stop adding items to the queue. To ensure that the\n producer notices this signal promptly, we also attempt to drain any items\n currently in the queue, clearing it so that the event can be checked without\n delay.\n \"\"\"\n self._shutdown_producer.set()\n q = self.work_queue\n while not q.empty():\n q.get_nowait()\n q.task_done()"}, {"class_start_lineno": 26, "class_end_lineno": 197, "func_start_lineno": 174, "func_end_lineno": 191, "func_code": " def iterate(self, timeout=None) -> Generator[ResultT, None, None]:\n init = asyncio.run_coroutine_threadsafe(self.init(), self.loop)\n init.result(timeout=1)\n async_run = asyncio.run_coroutine_threadsafe(self.run(), self.loop)\n try:\n while True:\n if (result := self.next_result(timeout)) is not None:\n yield result\n else:\n break\n if exc := async_run.exception():\n raise exc\n finally:\n self.shutdown_producer()\n if not async_run.done():\n async_run.cancel()\n wait([async_run])\n self._producer_is_shutdown.wait()"}], "type": ["TDD"], "node": ["datachain.asyn.AsyncMapper.shutdown_producer", "datachain.asyn.AsyncMapper.iterate"], "language": "Python", "toolfunc_count": 0, "func_count": 2, "pytest_info": {"total_num": 19, "base_passed_num": 3}} {"id": ["datachain.src.datachain.catalog.loader.get_metastore", "datachain.src.datachain.catalog.loader.get_catalog"], "project": "datachain", "origin_file": ["datachain/catalog/loader.py", "datachain/catalog/loader.py"], "test_list": ["tests/unit/test_catalog_loader.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 141, "func_start_lineno": 29, "func_end_lineno": 61, "func_code": "def get_metastore(in_memory: bool = False) -> \"AbstractMetastore\":\n metastore_serialized = os.environ.get(METASTORE_SERIALIZED)\n if metastore_serialized:\n metastore_obj = deserialize(metastore_serialized)\n if not isinstance(metastore_obj, AbstractMetastore):\n raise RuntimeError(\n \"Deserialized Metastore is not an instance of AbstractMetastore: \"\n f\"{metastore_obj}\"\n )\n return metastore_obj\n\n metastore_import_path = os.environ.get(METASTORE_IMPORT_PATH)\n metastore_arg_envs = get_envs_by_prefix(METASTORE_ARG_PREFIX)\n # Convert env variable names to keyword argument names by lowercasing them\n metastore_args: dict[str, Any] = {\n k.lower(): v for k, v in metastore_arg_envs.items()\n }\n\n if not metastore_import_path:\n metastore_args[\"in_memory\"] = in_memory\n return SQLiteMetastore(**metastore_args)\n if in_memory:\n raise RuntimeError(IN_MEMORY_ERROR_MESSAGE)\n # Metastore paths are specified as (for example):\n # datachain.data_storage.SQLiteMetastore\n if \".\" not in metastore_import_path:\n raise RuntimeError(\n f\"Invalid {METASTORE_IMPORT_PATH} import path: {metastore_import_path}\"\n )\n module_name, _, class_name = metastore_import_path.rpartition(\".\")\n metastore = import_module(module_name)\n metastore_class = getattr(metastore, class_name)\n return metastore_class(**metastore_args)"}, {"class_start_lineno": 1, "class_end_lineno": 141, "func_start_lineno": 122, "func_end_lineno": 141, "func_code": "def get_catalog(\n client_config: Optional[dict[str, Any]] = None, in_memory: bool = False\n) -> Catalog:\n \"\"\"\n Function that creates Catalog instance with appropriate metastore\n and warehouse classes. Metastore class can be provided with env variable\n DATACHAIN_METASTORE and if not provided, default one is used. Warehouse class\n can be provided with env variable DATACHAIN_WAREHOUSE and if not provided,\n\n If classes expects some kwargs, they can be provided via env variables\n by adding them with prefix (DATACHAIN_METASTORE_ARG_ and DATACHAIN_WAREHOUSE_ARG_)\n and name of variable after, e.g. if it accepts team_id as kwargs\n we can provide DATACHAIN_METASTORE_ARG_TEAM_ID=12345 env variable.\n \"\"\"\n return Catalog(\n metastore=get_metastore(in_memory=in_memory),\n warehouse=get_warehouse(in_memory=in_memory),\n client_config=client_config,\n in_memory=in_memory,\n )"}], "type": ["function_empty", "TDD"], "node": ["datachain.catalog.loader.get_metastore", "datachain.catalog.loader.get_catalog"], "language": "Python", "toolfunc_count": 1, "func_count": 2, "pytest_info": {"total_num": 6, "base_passed_num": 3}} {"id": ["datachain.src.datachain.func.func.Func::_db_cols", "datachain.src.datachain.func.func.Func::_db_col_type", "datachain.src.datachain.func.func.Func::get_result_type", "datachain.src.datachain.lib.convert.python_to_sql.python_to_sql", "datachain.src.datachain.func.func.Func::get_column"], "project": "datachain", "origin_file": ["datachain/func/func.py", "datachain/func/func.py", "datachain/func/func.py", "datachain/lib/convert/python_to_sql.py", "datachain/func/func.py"], "test_list": ["tests/unit/test_func.py"], "prob_info": [{"class_start_lineno": 29, "class_end_lineno": 422, "func_start_lineno": 77, "func_end_lineno": 89, "func_code": " def _db_cols(self) -> Sequence[ColT]:\n return (\n [\n col\n if isinstance(col, (Func, BindParameter, Case, Comparator, tuple))\n else ColumnMeta.to_db_name(\n col.name if isinstance(col, ColumnElement) else col\n )\n for col in self.cols\n ]\n if self.cols\n else []\n )"}, {"class_start_lineno": 29, "class_end_lineno": 422, "func_start_lineno": 91, "func_end_lineno": 103, "func_code": " def _db_col_type(self, signals_schema: \"SignalSchema\") -> Optional[\"DataType\"]:\n if not self._db_cols:\n return None\n\n col_type: type = get_db_col_type(signals_schema, self._db_cols[0])\n for col in self._db_cols[1:]:\n if get_db_col_type(signals_schema, col) != col_type:\n raise DataChainColumnError(\n str(self),\n \"Columns must have the same type to infer result type\",\n )\n\n return list[col_type] if self.is_array else col_type # type: ignore[valid-type]"}, {"class_start_lineno": 29, "class_end_lineno": 422, "func_start_lineno": 361, "func_end_lineno": 373, "func_code": " def get_result_type(\n self, signals_schema: Optional[\"SignalSchema\"] = None\n ) -> \"DataType\":\n if self.result_type:\n return self.result_type\n\n if signals_schema and (col_type := self._db_col_type(signals_schema)):\n return col_type\n\n raise DataChainColumnError(\n str(self),\n \"Column name is required to infer result type\",\n )"}, {"class_start_lineno": 1, "class_end_lineno": 117, "func_start_lineno": 37, "func_end_lineno": 82, "func_code": "def python_to_sql(typ): # noqa: PLR0911\n if inspect.isclass(typ):\n if issubclass(typ, SQLType):\n return typ\n if issubclass(typ, Enum):\n return str\n\n res = PYTHON_TO_SQL.get(typ)\n if res:\n return res\n\n orig = get_origin(typ)\n\n if orig in (Literal, LiteralEx):\n return String\n\n args = get_args(typ)\n if inspect.isclass(orig) and (issubclass(list, orig) or issubclass(tuple, orig)):\n if args is None:\n raise TypeError(f\"Cannot resolve type '{typ}' for flattening features\")\n\n args0 = args[0]\n if ModelStore.is_pydantic(args0):\n return Array(JSON())\n\n list_type = list_of_args_to_type(args)\n return Array(list_type)\n\n if orig is Annotated:\n # Ignoring annotations\n return python_to_sql(args[0])\n\n if inspect.isclass(orig) and issubclass(dict, orig):\n return JSON\n\n if orig == Union:\n if len(args) == 2 and (type(None) in args):\n return python_to_sql(args[0])\n\n if _is_union_str_literal(orig, args):\n return String\n\n if _is_json_inside_union(orig, args):\n return JSON\n\n raise TypeError(f\"Cannot recognize type {typ}\")"}, {"class_start_lineno": 29, "class_end_lineno": 422, "func_start_lineno": 375, "func_end_lineno": 422, "func_code": " def get_column(\n self,\n signals_schema: Optional[\"SignalSchema\"] = None,\n label: Optional[str] = None,\n table: Optional[\"TableClause\"] = None,\n ) -> Column:\n col_type = self.get_result_type(signals_schema)\n sql_type = python_to_sql(col_type)\n\n def get_col(col: ColT, string_as_literal=False) -> ColT:\n # string_as_literal is used only for conditionals like `case()` where\n # literals are nested inside ColT as we have tuples of condition - values\n # and if user wants to set some case value as column, explicit `C(\"col\")`\n # syntax must be used to distinguish from literals\n if isinstance(col, tuple):\n return tuple(get_col(x, string_as_literal=True) for x in col)\n if isinstance(col, Func):\n return col.get_column(signals_schema, table=table)\n if isinstance(col, str) and not string_as_literal:\n column = Column(col, sql_type)\n column.table = table\n return column\n return col\n\n cols = [get_col(col) for col in self._db_cols]\n kwargs = {k: get_col(v, string_as_literal=True) for k, v in self.kwargs.items()}\n func_col = self.inner(*cols, *self.args, **kwargs)\n\n if self.is_window:\n if not self.window:\n raise DataChainParamsError(\n f\"Window function {self} requires over() clause with a window spec\",\n )\n func_col = func_col.over(\n partition_by=self.window.partition_by,\n order_by=(\n desc(self.window.order_by)\n if self.window.desc\n else self.window.order_by\n ),\n )\n\n func_col.type = sql_type() if inspect.isclass(sql_type) else sql_type\n\n if col_name := self.get_col_name(label):\n func_col = func_col.label(col_name)\n\n return func_col"}], "type": ["TDD"], "node": ["datachain.func.func.Func._db_cols", "datachain.func.func.Func._db_col_type", "datachain.func.func.Func.get_result_type", "datachain.lib.convert.python_to_sql.python_to_sql", "datachain.func.func.Func.get_column"], "language": "Python", "toolfunc_count": 0, "func_count": 5, "pytest_info": {"total_num": 94, "base_passed_num": 0}} {"id": ["datachain.src.datachain.lib.signal_schema.SignalSchema::_get_flat_tree", "datachain.src.datachain.lib.convert.python_to_sql.python_to_sql", "datachain.src.datachain.lib.signal_schema.SignalSchema::db_signals"], "project": "datachain", "origin_file": ["datachain/lib/signal_schema.py", "datachain/lib/signal_schema.py", "datachain/lib/convert/python_to_sql.py", "datachain/lib/signal_schema.py"], "test_list": ["tests/unit/lib/test_arrow.py"], "prob_info": [{"class_start_lineno": 135, "class_end_lineno": 751, "func_start_lineno": 630, "func_end_lineno": 639, "func_code": " def _get_flat_tree(\n self, tree: dict, prefix: list[str], depth: int\n ) -> Iterator[tuple[list[str], DataType, bool, int]]:\n for name, (type_, substree) in tree.items():\n suffix = name.split(\".\")\n new_prefix = prefix + suffix\n has_subtree = substree is not None\n yield new_prefix, type_, has_subtree, depth\n if substree is not None:\n yield from self._get_flat_tree(substree, new_prefix, depth + 1)"}, {"class_start_lineno": 135, "class_end_lineno": 751, "func_start_lineno": 627, "func_end_lineno": 628, "func_code": " def get_flat_tree(self) -> Iterator[tuple[list[str], DataType, bool, int]]:\n yield from self._get_flat_tree(self.tree, [], 0)"}, {"class_start_lineno": 1, "class_end_lineno": 117, "func_start_lineno": 37, "func_end_lineno": 82, "func_code": "def python_to_sql(typ): # noqa: PLR0911\n if inspect.isclass(typ):\n if issubclass(typ, SQLType):\n return typ\n if issubclass(typ, Enum):\n return str\n\n res = PYTHON_TO_SQL.get(typ)\n if res:\n return res\n\n orig = get_origin(typ)\n\n if orig in (Literal, LiteralEx):\n return String\n\n args = get_args(typ)\n if inspect.isclass(orig) and (issubclass(list, orig) or issubclass(tuple, orig)):\n if args is None:\n raise TypeError(f\"Cannot resolve type '{typ}' for flattening features\")\n\n args0 = args[0]\n if ModelStore.is_pydantic(args0):\n return Array(JSON())\n\n list_type = list_of_args_to_type(args)\n return Array(list_type)\n\n if orig is Annotated:\n # Ignoring annotations\n return python_to_sql(args[0])\n\n if inspect.isclass(orig) and issubclass(dict, orig):\n return JSON\n\n if orig == Union:\n if len(args) == 2 and (type(None) in args):\n return python_to_sql(args[0])\n\n if _is_union_str_literal(orig, args):\n return String\n\n if _is_json_inside_union(orig, args):\n return JSON\n\n raise TypeError(f\"Cannot recognize type {typ}\")"}, {"class_start_lineno": 135, "class_end_lineno": 751, "func_start_lineno": 481, "func_end_lineno": 503, "func_code": " def db_signals(\n self, name: Optional[str] = None, as_columns=False\n ) -> Union[list[str], list[Column]]:\n \"\"\"\n Returns DB columns as strings or Column objects with proper types\n Optionally, it can filter results by specific object, returning only his signals\n \"\"\"\n signals = [\n DEFAULT_DELIMITER.join(path)\n if not as_columns\n else Column(DEFAULT_DELIMITER.join(path), python_to_sql(_type))\n for path, _type, has_subtree, _ in self.get_flat_tree()\n if not has_subtree\n ]\n\n if name:\n signals = [\n s\n for s in signals\n if str(s) == name or str(s).startswith(f\"{name}{DEFAULT_DELIMITER}\")\n ]\n\n return signals # type: ignore[return-value]"}], "type": ["function_empty", "TDD"], "node": ["datachain.lib.signal_schema.SignalSchema._get_flat_tree", "datachain.lib.signal_schema.SignalSchema.get_flat_tree", "datachain.lib.convert.python_to_sql.python_to_sql", "datachain.lib.signal_schema.SignalSchema.db_signals"], "language": "Python", "toolfunc_count": 1, "func_count": 3, "pytest_info": {"total_num": 32, "base_passed_num": 31}} {"id": ["datachain.src.datachain.lib.image.convert_image", "datachain.src.datachain.lib.image.convert_images"], "project": "datachain", "origin_file": ["datachain/lib/image.py", "datachain/lib/image.py"], "test_list": ["tests/unit/lib/test_clip.py", "tests/unit/lib/test_image.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 81, "func_start_lineno": 7, "func_end_lineno": 46, "func_code": "def convert_image(\n img: Image.Image,\n mode: str = \"RGB\",\n size: Optional[tuple[int, int]] = None,\n transform: Optional[Callable] = None,\n encoder: Optional[Callable] = None,\n device: Optional[Union[str, torch.device]] = None,\n) -> Union[Image.Image, torch.Tensor]:\n \"\"\"\n Resize, transform, and otherwise convert an image.\n\n Args:\n img (Image): PIL.Image object.\n mode (str): PIL.Image mode.\n size (tuple[int, int]): Size in (width, height) pixels for resizing.\n transform (Callable): Torchvision transform or huggingface processor to apply.\n encoder (Callable): Encode image using model.\n device (str or torch.device): Device to use.\n \"\"\"\n if mode:\n img = img.convert(mode)\n if size:\n img = img.resize(size)\n if transform:\n img = transform(img)\n\n try:\n from transformers.image_processing_utils import BaseImageProcessor\n\n if isinstance(transform, BaseImageProcessor):\n img = torch.as_tensor(img.pixel_values[0]).clone().detach() # type: ignore[assignment,attr-defined]\n except ImportError:\n pass\n if device:\n img = img.to(device) # type: ignore[attr-defined]\n if encoder:\n img = img.unsqueeze(0) # type: ignore[attr-defined]\n if encoder:\n img = encoder(img)\n return img"}, {"class_start_lineno": 1, "class_end_lineno": 81, "func_start_lineno": 49, "func_end_lineno": 81, "func_code": "def convert_images(\n images: Union[Image.Image, list[Image.Image]],\n mode: str = \"RGB\",\n size: Optional[tuple[int, int]] = None,\n transform: Optional[Callable] = None,\n encoder: Optional[Callable] = None,\n device: Optional[Union[str, torch.device]] = None,\n) -> Union[list[Image.Image], torch.Tensor]:\n \"\"\"\n Resize, transform, and otherwise convert one or more images.\n\n Args:\n images (Image, list[Image]): PIL.Image object or list of objects.\n mode (str): PIL.Image mode.\n size (tuple[int, int]): Size in (width, height) pixels for resizing.\n transform (Callable): Torchvision transform or huggingface processor to apply.\n encoder (Callable): Encode image using model.\n device (str or torch.device): Device to use.\n \"\"\"\n if isinstance(images, Image.Image):\n images = [images]\n\n converted = [\n convert_image(img, mode, size, transform, device=device) for img in images\n ]\n\n if isinstance(converted[0], torch.Tensor):\n converted = torch.stack(converted) # type: ignore[assignment,arg-type]\n\n if encoder:\n converted = encoder(converted)\n\n return converted # type: ignore[return-value]"}], "type": ["function_empty", "TDD"], "node": ["datachain.lib.image.convert_image", "datachain.lib.image.convert_images"], "language": "Python", "toolfunc_count": 1, "func_count": 2, "pytest_info": {"total_num": 41, "base_passed_num": 13}} {"id": ["datachain.src.datachain.lib.file.File::get_destination_path", "datachain.src.datachain.lib.file.File::export"], "project": "datachain", "origin_file": ["datachain/lib/file.py", "datachain/lib/file.py"], "test_list": ["tests/unit/lib/test_file.py"], "prob_info": [{"class_start_lineno": 125, "class_end_lineno": 468, "func_start_lineno": 396, "func_end_lineno": 414, "func_code": " def get_destination_path(self, output: str, placement: ExportPlacement) -> str:\n \"\"\"\n Returns full destination path of a file for exporting to some output\n based on export placement\n \"\"\"\n if placement == \"filename\":\n path = unquote(self.name)\n elif placement == \"etag\":\n path = f\"{self.etag}{self.get_file_suffix()}\"\n elif placement == \"fullpath\":\n path = unquote(self.get_full_name())\n source = urlparse(self.source)\n if source.scheme and source.scheme != \"file\":\n path = posixpath.join(source.netloc, path)\n elif placement == \"checksum\":\n raise NotImplementedError(\"Checksum placement not implemented yet\")\n else:\n raise ValueError(f\"Unsupported file export placement: {placement}\")\n return posixpath.join(output, path) # type: ignore[union-attr]"}, {"class_start_lineno": 125, "class_end_lineno": 468, "func_start_lineno": 297, "func_end_lineno": 319, "func_code": " def export(\n self,\n output: str,\n placement: ExportPlacement = \"fullpath\",\n use_cache: bool = True,\n link_type: Literal[\"copy\", \"symlink\"] = \"copy\",\n ) -> None:\n \"\"\"Export file to new location.\"\"\"\n if use_cache:\n self._caching_enabled = use_cache\n dst = self.get_destination_path(output, placement)\n dst_dir = os.path.dirname(dst)\n client: Client = self._catalog.get_client(dst_dir)\n client.fs.makedirs(dst_dir, exist_ok=True)\n\n if link_type == \"symlink\":\n try:\n return self._symlink_to(dst)\n except OSError as exc:\n if exc.errno not in (errno.ENOTSUP, errno.EXDEV, errno.ENOSYS):\n raise\n\n self.save(dst)"}], "type": ["function_empty"], "node": ["datachain.lib.file.File.get_destination_path", "datachain.lib.file.File.export"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 33, "base_passed_num": 25}} {"id": ["datachain.src.datachain.lib.signal_schema.SignalSchema::_get_flat_tree", "datachain.src.datachain.lib.convert.python_to_sql.python_to_sql", "datachain.src.datachain.lib.signal_schema.SignalSchema::to_udf_spec", "datachain.src.datachain.lib.signal_schema.SignalSchema::db_signals"], "project": "datachain", "origin_file": ["datachain/lib/signal_schema.py", "datachain/lib/signal_schema.py", "datachain/lib/convert/python_to_sql.py", "datachain/lib/signal_schema.py", "datachain/lib/signal_schema.py"], "test_list": ["tests/unit/lib/test_signal_schema.py"], "prob_info": [{"class_start_lineno": 135, "class_end_lineno": 751, "func_start_lineno": 630, "func_end_lineno": 639, "func_code": " def _get_flat_tree(\n self, tree: dict, prefix: list[str], depth: int\n ) -> Iterator[tuple[list[str], DataType, bool, int]]:\n for name, (type_, substree) in tree.items():\n suffix = name.split(\".\")\n new_prefix = prefix + suffix\n has_subtree = substree is not None\n yield new_prefix, type_, has_subtree, depth\n if substree is not None:\n yield from self._get_flat_tree(substree, new_prefix, depth + 1)"}, {"class_start_lineno": 135, "class_end_lineno": 751, "func_start_lineno": 627, "func_end_lineno": 628, "func_code": " def get_flat_tree(self) -> Iterator[tuple[list[str], DataType, bool, int]]:\n yield from self._get_flat_tree(self.tree, [], 0)"}, {"class_start_lineno": 1, "class_end_lineno": 117, "func_start_lineno": 37, "func_end_lineno": 82, "func_code": "def python_to_sql(typ): # noqa: PLR0911\n if inspect.isclass(typ):\n if issubclass(typ, SQLType):\n return typ\n if issubclass(typ, Enum):\n return str\n\n res = PYTHON_TO_SQL.get(typ)\n if res:\n return res\n\n orig = get_origin(typ)\n\n if orig in (Literal, LiteralEx):\n return String\n\n args = get_args(typ)\n if inspect.isclass(orig) and (issubclass(list, orig) or issubclass(tuple, orig)):\n if args is None:\n raise TypeError(f\"Cannot resolve type '{typ}' for flattening features\")\n\n args0 = args[0]\n if ModelStore.is_pydantic(args0):\n return Array(JSON())\n\n list_type = list_of_args_to_type(args)\n return Array(list_type)\n\n if orig is Annotated:\n # Ignoring annotations\n return python_to_sql(args[0])\n\n if inspect.isclass(orig) and issubclass(dict, orig):\n return JSON\n\n if orig == Union:\n if len(args) == 2 and (type(None) in args):\n return python_to_sql(args[0])\n\n if _is_union_str_literal(orig, args):\n return String\n\n if _is_json_inside_union(orig, args):\n return JSON\n\n raise TypeError(f\"Cannot recognize type {typ}\")"}, {"class_start_lineno": 135, "class_end_lineno": 751, "func_start_lineno": 387, "func_end_lineno": 395, "func_code": " def to_udf_spec(self) -> dict[str, type]:\n res = {}\n for path, type_, has_subtree, _ in self.get_flat_tree():\n if path[0] in self.setup_func:\n continue\n if not has_subtree:\n db_name = DEFAULT_DELIMITER.join(path)\n res[db_name] = python_to_sql(type_)\n return res"}, {"class_start_lineno": 135, "class_end_lineno": 751, "func_start_lineno": 481, "func_end_lineno": 503, "func_code": " def db_signals(\n self, name: Optional[str] = None, as_columns=False\n ) -> Union[list[str], list[Column]]:\n \"\"\"\n Returns DB columns as strings or Column objects with proper types\n Optionally, it can filter results by specific object, returning only his signals\n \"\"\"\n signals = [\n DEFAULT_DELIMITER.join(path)\n if not as_columns\n else Column(DEFAULT_DELIMITER.join(path), python_to_sql(_type))\n for path, _type, has_subtree, _ in self.get_flat_tree()\n if not has_subtree\n ]\n\n if name:\n signals = [\n s\n for s in signals\n if str(s) == name or str(s).startswith(f\"{name}{DEFAULT_DELIMITER}\")\n ]\n\n return signals # type: ignore[return-value]"}], "type": ["function_empty", "TDD"], "node": ["datachain.lib.signal_schema.SignalSchema._get_flat_tree", "datachain.lib.signal_schema.SignalSchema.get_flat_tree", "datachain.lib.convert.python_to_sql.python_to_sql", "datachain.lib.signal_schema.SignalSchema.to_udf_spec", "datachain.lib.signal_schema.SignalSchema.db_signals"], "language": "Python", "toolfunc_count": 1, "func_count": 4, "pytest_info": {"total_num": 58, "base_passed_num": 47}} {"id": ["datachain.src.datachain.func.func.Func::get_result_type", "datachain.src.datachain.lib.convert.python_to_sql.python_to_sql", "datachain.src.datachain.func.func.Func::get_column"], "project": "datachain", "origin_file": ["datachain/func/func.py", "datachain/lib/convert/python_to_sql.py", "datachain/func/func.py", "datachain/sql/selectable.py"], "test_list": ["tests/unit/sql/test_array.py"], "prob_info": [{"class_start_lineno": 29, "class_end_lineno": 422, "func_start_lineno": 361, "func_end_lineno": 373, "func_code": " def get_result_type(\n self, signals_schema: Optional[\"SignalSchema\"] = None\n ) -> \"DataType\":\n if self.result_type:\n return self.result_type\n\n if signals_schema and (col_type := self._db_col_type(signals_schema)):\n return col_type\n\n raise DataChainColumnError(\n str(self),\n \"Column name is required to infer result type\",\n )"}, {"class_start_lineno": 1, "class_end_lineno": 117, "func_start_lineno": 37, "func_end_lineno": 82, "func_code": "def python_to_sql(typ): # noqa: PLR0911\n if inspect.isclass(typ):\n if issubclass(typ, SQLType):\n return typ\n if issubclass(typ, Enum):\n return str\n\n res = PYTHON_TO_SQL.get(typ)\n if res:\n return res\n\n orig = get_origin(typ)\n\n if orig in (Literal, LiteralEx):\n return String\n\n args = get_args(typ)\n if inspect.isclass(orig) and (issubclass(list, orig) or issubclass(tuple, orig)):\n if args is None:\n raise TypeError(f\"Cannot resolve type '{typ}' for flattening features\")\n\n args0 = args[0]\n if ModelStore.is_pydantic(args0):\n return Array(JSON())\n\n list_type = list_of_args_to_type(args)\n return Array(list_type)\n\n if orig is Annotated:\n # Ignoring annotations\n return python_to_sql(args[0])\n\n if inspect.isclass(orig) and issubclass(dict, orig):\n return JSON\n\n if orig == Union:\n if len(args) == 2 and (type(None) in args):\n return python_to_sql(args[0])\n\n if _is_union_str_literal(orig, args):\n return String\n\n if _is_json_inside_union(orig, args):\n return JSON\n\n raise TypeError(f\"Cannot recognize type {typ}\")"}, {"class_start_lineno": 29, "class_end_lineno": 422, "func_start_lineno": 375, "func_end_lineno": 422, "func_code": " def get_column(\n self,\n signals_schema: Optional[\"SignalSchema\"] = None,\n label: Optional[str] = None,\n table: Optional[\"TableClause\"] = None,\n ) -> Column:\n col_type = self.get_result_type(signals_schema)\n sql_type = python_to_sql(col_type)\n\n def get_col(col: ColT, string_as_literal=False) -> ColT:\n # string_as_literal is used only for conditionals like `case()` where\n # literals are nested inside ColT as we have tuples of condition - values\n # and if user wants to set some case value as column, explicit `C(\"col\")`\n # syntax must be used to distinguish from literals\n if isinstance(col, tuple):\n return tuple(get_col(x, string_as_literal=True) for x in col)\n if isinstance(col, Func):\n return col.get_column(signals_schema, table=table)\n if isinstance(col, str) and not string_as_literal:\n column = Column(col, sql_type)\n column.table = table\n return column\n return col\n\n cols = [get_col(col) for col in self._db_cols]\n kwargs = {k: get_col(v, string_as_literal=True) for k, v in self.kwargs.items()}\n func_col = self.inner(*cols, *self.args, **kwargs)\n\n if self.is_window:\n if not self.window:\n raise DataChainParamsError(\n f\"Window function {self} requires over() clause with a window spec\",\n )\n func_col = func_col.over(\n partition_by=self.window.partition_by,\n order_by=(\n desc(self.window.order_by)\n if self.window.desc\n else self.window.order_by\n ),\n )\n\n func_col.type = sql_type() if inspect.isclass(sql_type) else sql_type\n\n if col_name := self.get_col_name(label):\n func_col = func_col.label(col_name)\n\n return func_col"}, {"class_start_lineno": 1, "class_end_lineno": 56, "func_start_lineno": 24, "func_end_lineno": 29, "func_code": "def process_column_expression(col):\n if hasattr(col, \"get_column\"):\n return col.get_column()\n if isinstance(col, str):\n return expression.column(col)\n return col"}], "type": ["TDD"], "node": ["datachain.func.func.Func.get_result_type", "datachain.lib.convert.python_to_sql.python_to_sql", "datachain.func.func.Func.get_column", "datachain.sql.selectable.process_column_expression"], "language": "Python", "toolfunc_count": 0, "func_count": 3, "pytest_info": {"total_num": 12, "base_passed_num": 0}} {"id": ["datachain.src.datachain.func.func.Func::get_result_type", "datachain.src.datachain.lib.convert.python_to_sql.python_to_sql", "datachain.src.datachain.func.func.Func::get_column", "datachain.src.datachain.func.conditional.case", "datachain.src.datachain.func.conditional.ifelse"], "project": "datachain", "origin_file": ["datachain/func/func.py", "datachain/lib/convert/python_to_sql.py", "datachain/func/func.py", "datachain/sql/selectable.py", "datachain/func/conditional.py", "datachain/func/conditional.py"], "test_list": ["tests/unit/sql/test_conditional.py"], "prob_info": [{"class_start_lineno": 29, "class_end_lineno": 422, "func_start_lineno": 361, "func_end_lineno": 373, "func_code": " def get_result_type(\n self, signals_schema: Optional[\"SignalSchema\"] = None\n ) -> \"DataType\":\n if self.result_type:\n return self.result_type\n\n if signals_schema and (col_type := self._db_col_type(signals_schema)):\n return col_type\n\n raise DataChainColumnError(\n str(self),\n \"Column name is required to infer result type\",\n )"}, {"class_start_lineno": 1, "class_end_lineno": 117, "func_start_lineno": 37, "func_end_lineno": 82, "func_code": "def python_to_sql(typ): # noqa: PLR0911\n if inspect.isclass(typ):\n if issubclass(typ, SQLType):\n return typ\n if issubclass(typ, Enum):\n return str\n\n res = PYTHON_TO_SQL.get(typ)\n if res:\n return res\n\n orig = get_origin(typ)\n\n if orig in (Literal, LiteralEx):\n return String\n\n args = get_args(typ)\n if inspect.isclass(orig) and (issubclass(list, orig) or issubclass(tuple, orig)):\n if args is None:\n raise TypeError(f\"Cannot resolve type '{typ}' for flattening features\")\n\n args0 = args[0]\n if ModelStore.is_pydantic(args0):\n return Array(JSON())\n\n list_type = list_of_args_to_type(args)\n return Array(list_type)\n\n if orig is Annotated:\n # Ignoring annotations\n return python_to_sql(args[0])\n\n if inspect.isclass(orig) and issubclass(dict, orig):\n return JSON\n\n if orig == Union:\n if len(args) == 2 and (type(None) in args):\n return python_to_sql(args[0])\n\n if _is_union_str_literal(orig, args):\n return String\n\n if _is_json_inside_union(orig, args):\n return JSON\n\n raise TypeError(f\"Cannot recognize type {typ}\")"}, {"class_start_lineno": 29, "class_end_lineno": 422, "func_start_lineno": 375, "func_end_lineno": 422, "func_code": " def get_column(\n self,\n signals_schema: Optional[\"SignalSchema\"] = None,\n label: Optional[str] = None,\n table: Optional[\"TableClause\"] = None,\n ) -> Column:\n col_type = self.get_result_type(signals_schema)\n sql_type = python_to_sql(col_type)\n\n def get_col(col: ColT, string_as_literal=False) -> ColT:\n # string_as_literal is used only for conditionals like `case()` where\n # literals are nested inside ColT as we have tuples of condition - values\n # and if user wants to set some case value as column, explicit `C(\"col\")`\n # syntax must be used to distinguish from literals\n if isinstance(col, tuple):\n return tuple(get_col(x, string_as_literal=True) for x in col)\n if isinstance(col, Func):\n return col.get_column(signals_schema, table=table)\n if isinstance(col, str) and not string_as_literal:\n column = Column(col, sql_type)\n column.table = table\n return column\n return col\n\n cols = [get_col(col) for col in self._db_cols]\n kwargs = {k: get_col(v, string_as_literal=True) for k, v in self.kwargs.items()}\n func_col = self.inner(*cols, *self.args, **kwargs)\n\n if self.is_window:\n if not self.window:\n raise DataChainParamsError(\n f\"Window function {self} requires over() clause with a window spec\",\n )\n func_col = func_col.over(\n partition_by=self.window.partition_by,\n order_by=(\n desc(self.window.order_by)\n if self.window.desc\n else self.window.order_by\n ),\n )\n\n func_col.type = sql_type() if inspect.isclass(sql_type) else sql_type\n\n if col_name := self.get_col_name(label):\n func_col = func_col.label(col_name)\n\n return func_col"}, {"class_start_lineno": 1, "class_end_lineno": 56, "func_start_lineno": 24, "func_end_lineno": 29, "func_code": "def process_column_expression(col):\n if hasattr(col, \"get_column\"):\n return col.get_column()\n if isinstance(col, str):\n return expression.column(col)\n return col"}, {"class_start_lineno": 1, "class_end_lineno": 270, "func_start_lineno": 93, "func_end_lineno": 158, "func_code": "def case(\n *args: tuple[Union[ColumnElement, Func, bool], CaseT], else_: Optional[CaseT] = None\n) -> Func:\n \"\"\"\n Returns the case function that produces case expression which has a list of\n conditions and corresponding results. Results can be python primitives like string,\n numbers or booleans but can also be other nested functions (including case function)\n or columns.\n Result type is inferred from condition results.\n\n Args:\n args tuple((ColumnElement | Func | bool),(str | int | float | complex | bool, Func, ColumnElement)):\n Tuple of condition and values pair.\n else_ (str | int | float | complex | bool, Func): optional else value in case\n expression. If omitted, and no case conditions are satisfied, the result\n will be None (NULL in DB).\n\n Returns:\n Func: A Func object that represents the case function.\n\n Example:\n ```py\n dc.mutate(\n res=func.case((C(\"num\") > 0, \"P\"), (C(\"num\") < 0, \"N\"), else_=\"Z\"),\n )\n ```\n \"\"\" # noqa: E501\n supported_types = [int, float, complex, str, bool]\n\n def _get_type(val):\n from enum import Enum\n\n if isinstance(val, Func):\n # nested functions\n return val.result_type\n if isinstance(val, Column):\n # at this point we cannot know what is the type of a column\n return None\n if isinstance(val, Enum):\n return type(val.value)\n return type(val)\n\n if not args:\n raise DataChainParamsError(\"Missing statements\")\n\n type_ = _get_type(else_) if else_ is not None else None\n\n for arg in args:\n arg_type = _get_type(arg[1])\n if arg_type is None:\n # we couldn't figure out the type of case value\n continue\n if type_ and arg_type != type_:\n raise DataChainParamsError(\n f\"Statement values must be of the same type, got {type_} and {arg_type}\"\n )\n type_ = arg_type\n\n if type_ is not None and type_ not in supported_types:\n raise DataChainParamsError(\n f\"Only python literals ({supported_types}) are supported for values\"\n )\n\n kwargs = {\"else_\": else_}\n\n return Func(\"case\", inner=sql_case, cols=args, kwargs=kwargs, result_type=type_)"}, {"class_start_lineno": 1, "class_end_lineno": 270, "func_start_lineno": 161, "func_end_lineno": 187, "func_code": "def ifelse(\n condition: Union[ColumnElement, Func], if_val: CaseT, else_val: CaseT\n) -> Func:\n \"\"\"\n Returns the ifelse function that produces if expression which has a condition\n and values for true and false outcome. Results can be one of python primitives\n like string, numbers or booleans, but can also be nested functions or columns.\n Result type is inferred from the values.\n\n Args:\n condition (ColumnElement, Func): Condition which is evaluated.\n if_val (str | int | float | complex | bool, Func, ColumnElement): Value for true\n condition outcome.\n else_val (str | int | float | complex | bool, Func, ColumnElement): Value for\n false condition outcome.\n\n Returns:\n Func: A Func object that represents the ifelse function.\n\n Example:\n ```py\n dc.mutate(\n res=func.ifelse(isnone(\"col\"), \"EMPTY\", \"NOT_EMPTY\")\n )\n ```\n \"\"\"\n return case((condition, if_val), else_=else_val)"}], "type": ["function_empty", "TDD"], "node": ["datachain.func.func.Func.get_result_type", "datachain.lib.convert.python_to_sql.python_to_sql", "datachain.func.func.Func.get_column", "datachain.sql.selectable.process_column_expression", "datachain.func.conditional.case", "datachain.func.conditional.ifelse"], "language": "Python", "toolfunc_count": 1, "func_count": 5, "pytest_info": {"total_num": 34, "base_passed_num": 0}} {"id": ["haystack.haystack.dataclasses.chat_message.ChatMessage::__getattribute__", "haystack.haystack.components.builders.answer_builder.AnswerBuilder::run"], "project": "haystack", "origin_file": ["haystack/dataclasses/chat_message.py", "haystack/components/builders/answer_builder.py", "haystack/dataclasses/chat_message.py", "haystack/dataclasses/chat_message.py", "haystack/dataclasses/chat_message.py"], "test_list": ["test/components/builders/test_answer_builder.py"], "prob_info": [{"class_start_lineno": 88, "class_end_lineno": 481, "func_start_lineno": 127, "func_end_lineno": 140, "func_code": " def __getattribute__(self, name):\n \"\"\"\n This method is reimplemented to make the `content` attribute removal more visible.\n \"\"\"\n\n if name == \"content\":\n msg = (\n \"The `content` attribute of `ChatMessage` has been removed. \"\n \"Use the `text` property to access the textual value. \"\n \"For more information about the new API and how to migrate, see the documentation: \"\n \"https://docs.haystack.deepset.ai/docs/chatmessage\"\n )\n raise AttributeError(msg)\n return object.__getattribute__(self, name)"}, {"class_start_lineno": 15, "class_end_lineno": 184, "func_start_lineno": 61, "func_end_lineno": 147, "func_code": " def run( # pylint: disable=too-many-positional-arguments\n self,\n query: str,\n replies: Union[List[str], List[ChatMessage]],\n meta: Optional[List[Dict[str, Any]]] = None,\n documents: Optional[List[Document]] = None,\n pattern: Optional[str] = None,\n reference_pattern: Optional[str] = None,\n ):\n \"\"\"\n Turns the output of a Generator into `GeneratedAnswer` objects using regular expressions.\n\n :param query:\n The input query used as the Generator prompt.\n :param replies:\n The output of the Generator. Can be a list of strings or a list of `ChatMessage` objects.\n :param meta:\n The metadata returned by the Generator. If not specified, the generated answer will contain no metadata.\n :param documents:\n The documents used as the Generator inputs. If specified, they are added to\n the`GeneratedAnswer` objects.\n If both `documents` and `reference_pattern` are specified, the documents referenced in the\n Generator output are extracted from the input documents and added to the `GeneratedAnswer` objects.\n :param pattern:\n The regular expression pattern to extract the answer text from the Generator.\n If not specified, the entire response is used as the answer.\n The regular expression can have one capture group at most.\n If present, the capture group text\n is used as the answer. If no capture group is present, the whole match is used as the answer.\n Examples:\n `[^\\\\n]+$` finds \"this is an answer\" in a string \"this is an argument.\\\\nthis is an answer\".\n `Answer: (.*)` finds \"this is an answer\" in a string\n \"this is an argument. Answer: this is an answer\".\n :param reference_pattern:\n The regular expression pattern used for parsing the document references.\n If not specified, no parsing is done, and all documents are referenced.\n References need to be specified as indices of the input documents and start at [1].\n Example: `\\\\[(\\\\d+)\\\\]` finds \"1\" in a string \"this is an answer[1]\".\n\n :returns: A dictionary with the following keys:\n - `answers`: The answers received from the output of the Generator.\n \"\"\"\n if not meta:\n meta = [{}] * len(replies)\n elif len(replies) != len(meta):\n raise ValueError(f\"Number of replies ({len(replies)}), and metadata ({len(meta)}) must match.\")\n\n if pattern:\n AnswerBuilder._check_num_groups_in_regex(pattern)\n\n pattern = pattern or self.pattern\n reference_pattern = reference_pattern or self.reference_pattern\n all_answers = []\n for reply, given_metadata in zip(replies, meta):\n # Extract content from ChatMessage objects if reply is a ChatMessages, else use the string as is\n if isinstance(reply, ChatMessage):\n if reply.text is None:\n raise ValueError(f\"The provided ChatMessage has no text. ChatMessage: {reply}\")\n extracted_reply = reply.text\n else:\n extracted_reply = str(reply)\n extracted_metadata = reply.meta if isinstance(reply, ChatMessage) else {}\n\n extracted_metadata = {**extracted_metadata, **given_metadata}\n\n referenced_docs = []\n if documents:\n if reference_pattern:\n reference_idxs = AnswerBuilder._extract_reference_idxs(extracted_reply, reference_pattern)\n else:\n reference_idxs = [doc_idx for doc_idx, _ in enumerate(documents)]\n\n for idx in reference_idxs:\n try:\n referenced_docs.append(documents[idx])\n except IndexError:\n logger.warning(\n \"Document index '{index}' referenced in Generator output is out of range. \", index=idx + 1\n )\n\n answer_string = AnswerBuilder._extract_answer_string(extracted_reply, pattern)\n answer = GeneratedAnswer(\n data=answer_string, query=query, documents=referenced_docs, meta=extracted_metadata\n )\n all_answers.append(answer)\n\n return {\"answers\": all_answers}"}, {"class_start_lineno": 88, "class_end_lineno": 481, "func_start_lineno": 167, "func_end_lineno": 171, "func_code": " def texts(self) -> List[str]:\n \"\"\"\n Returns the list of all texts contained in the message.\n \"\"\"\n return [content.text for content in self._content if isinstance(content, TextContent)]"}, {"class_start_lineno": 88, "class_end_lineno": 481, "func_start_lineno": 174, "func_end_lineno": 180, "func_code": " def text(self) -> Optional[str]:\n \"\"\"\n Returns the first text contained in the message.\n \"\"\"\n if texts := self.texts:\n return texts[0]\n return None"}, {"class_start_lineno": 88, "class_end_lineno": 481, "func_start_lineno": 153, "func_end_lineno": 157, "func_code": " def meta(self) -> Dict[str, Any]:\n \"\"\"\n Returns the metadata associated with the message.\n \"\"\"\n return self._meta"}], "type": ["function_empty", "TDD"], "node": ["haystack.dataclasses.chat_message.ChatMessage.__getattribute__", "haystack.components.builders.answer_builder.AnswerBuilder.run", "haystack.dataclasses.chat_message.ChatMessage.texts", "haystack.dataclasses.chat_message.ChatMessage.text", "haystack.dataclasses.chat_message.ChatMessage.meta"], "language": "Python", "toolfunc_count": 1, "func_count": 2, "pytest_info": {"total_num": 19, "base_passed_num": 1}} {"id": ["haystack.haystack.dataclasses.chat_message.ChatMessage::__getattribute__", "haystack.haystack.core.type_utils._strict_types_are_compatible", "haystack.haystack.core.type_utils._types_are_compatible", "haystack.haystack.core.type_utils._type_name", "haystack.haystack.core.pipeline.base._connections_status"], "project": "haystack", "origin_file": ["haystack/dataclasses/chat_message.py", "haystack/dataclasses/chat_message.py", "haystack/dataclasses/chat_message.py", "haystack/dataclasses/chat_message.py", "haystack/core/type_utils.py", "haystack/core/type_utils.py", "haystack/core/type_utils.py", "haystack/core/pipeline/base.py"], "test_list": ["test/components/builders/test_chat_prompt_builder.py"], "prob_info": [{"class_start_lineno": 88, "class_end_lineno": 481, "func_start_lineno": 127, "func_end_lineno": 140, "func_code": " def __getattribute__(self, name):\n \"\"\"\n This method is reimplemented to make the `content` attribute removal more visible.\n \"\"\"\n\n if name == \"content\":\n msg = (\n \"The `content` attribute of `ChatMessage` has been removed. \"\n \"Use the `text` property to access the textual value. \"\n \"For more information about the new API and how to migrate, see the documentation: \"\n \"https://docs.haystack.deepset.ai/docs/chatmessage\"\n )\n raise AttributeError(msg)\n return object.__getattribute__(self, name)"}, {"class_start_lineno": 88, "class_end_lineno": 481, "func_start_lineno": 167, "func_end_lineno": 171, "func_code": " def texts(self) -> List[str]:\n \"\"\"\n Returns the list of all texts contained in the message.\n \"\"\"\n return [content.text for content in self._content if isinstance(content, TextContent)]"}, {"class_start_lineno": 88, "class_end_lineno": 481, "func_start_lineno": 174, "func_end_lineno": 180, "func_code": " def text(self) -> Optional[str]:\n \"\"\"\n Returns the first text contained in the message.\n \"\"\"\n if texts := self.texts:\n return texts[0]\n return None"}, {"class_start_lineno": 88, "class_end_lineno": 481, "func_start_lineno": 153, "func_end_lineno": 157, "func_code": " def meta(self) -> Dict[str, Any]:\n \"\"\"\n Returns the metadata associated with the message.\n \"\"\"\n return self._meta"}, {"class_start_lineno": 1, "class_end_lineno": 105, "func_start_lineno": 29, "func_end_lineno": 76, "func_code": "def _strict_types_are_compatible(sender, receiver): # pylint: disable=too-many-return-statements\n \"\"\"\n Checks whether the sender type is equal to or a subtype of the receiver type under strict validation.\n\n Note: this method has no pretense to perform proper type matching. It especially does not deal with aliasing of\n typing classes such as `List` or `Dict` to their runtime counterparts `list` and `dict`. It also does not deal well\n with \"bare\" types, so `List` is treated differently from `List[Any]`, even though they should be the same.\n Consider simplifying the typing of your components if you observe unexpected errors during component connection.\n\n :param sender: The sender type.\n :param receiver: The receiver type.\n :return: True if the sender type is strictly compatible with the receiver type, False otherwise.\n \"\"\"\n if sender == receiver or receiver is Any:\n return True\n\n if sender is Any:\n return False\n\n try:\n if issubclass(sender, receiver):\n return True\n except TypeError: # typing classes can't be used with issubclass, so we deal with them below\n pass\n\n sender_origin = get_origin(sender)\n receiver_origin = get_origin(receiver)\n\n if sender_origin is not Union and receiver_origin is Union:\n return any(_strict_types_are_compatible(sender, union_arg) for union_arg in get_args(receiver))\n\n # Both must have origins and they must be equal\n if not (sender_origin and receiver_origin and sender_origin == receiver_origin):\n return False\n\n # Compare generic type arguments\n sender_args = get_args(sender)\n receiver_args = get_args(receiver)\n\n # Handle bare types\n if not sender_args and sender_origin:\n sender_args = (Any,)\n if not receiver_args and receiver_origin:\n receiver_args = (Any,) * (len(sender_args) if sender_args else 1)\n if len(sender_args) > len(receiver_args):\n return False\n\n return all(_strict_types_are_compatible(*args) for args in zip(sender_args, receiver_args))"}, {"class_start_lineno": 1, "class_end_lineno": 105, "func_start_lineno": 14, "func_end_lineno": 26, "func_code": "def _types_are_compatible(sender, receiver, type_validation: bool = True) -> bool:\n \"\"\"\n Determines if two types are compatible based on the specified validation mode.\n\n :param sender: The sender type.\n :param receiver: The receiver type.\n :param type_validation: Whether to perform strict type validation.\n :return: True if the types are compatible, False otherwise.\n \"\"\"\n if type_validation:\n return _strict_types_are_compatible(sender, receiver)\n else:\n return True"}, {"class_start_lineno": 1, "class_end_lineno": 105, "func_start_lineno": 79, "func_end_lineno": 105, "func_code": "def _type_name(type_):\n \"\"\"\n Util methods to get a nice readable representation of a type.\n\n Handles Optional and Literal in a special way to make it more readable.\n \"\"\"\n # Literal args are strings, so we wrap them in quotes to make it clear\n if isinstance(type_, str):\n return f\"'{type_}'\"\n\n name = getattr(type_, \"__name__\", str(type_))\n\n if name.startswith(\"typing.\"):\n name = name[7:]\n if \"[\" in name:\n name = name.split(\"[\")[0]\n args = get_args(type_)\n if name == \"Union\" and type(None) in args and len(args) == 2:\n # Optional is technically a Union of type and None\n # but we want to display it as Optional\n name = \"Optional\"\n\n if args:\n args = \", \".join([_type_name(a) for a in args if a is not type(None)])\n return f\"{name}[{args}]\"\n\n return f\"{name}\""}, {"class_start_lineno": 1, "class_end_lineno": 1261, "func_start_lineno": 1207, "func_end_lineno": 1229, "func_code": "def _connections_status(\n sender_node: str, receiver_node: str, sender_sockets: List[OutputSocket], receiver_sockets: List[InputSocket]\n) -> str:\n \"\"\"\n Lists the status of the sockets, for error messages.\n \"\"\"\n sender_sockets_entries = []\n for sender_socket in sender_sockets:\n sender_sockets_entries.append(f\" - {sender_socket.name}: {_type_name(sender_socket.type)}\")\n sender_sockets_list = \"\\n\".join(sender_sockets_entries)\n\n receiver_sockets_entries = []\n for receiver_socket in receiver_sockets:\n if receiver_socket.senders:\n sender_status = f\"sent by {','.join(receiver_socket.senders)}\"\n else:\n sender_status = \"available\"\n receiver_sockets_entries.append(\n f\" - {receiver_socket.name}: {_type_name(receiver_socket.type)} ({sender_status})\"\n )\n receiver_sockets_list = \"\\n\".join(receiver_sockets_entries)\n\n return f\"'{sender_node}':\\n{sender_sockets_list}\\n'{receiver_node}':\\n{receiver_sockets_list}\""}], "type": ["function_empty", "TDD"], "node": ["haystack.dataclasses.chat_message.ChatMessage.__getattribute__", "haystack.dataclasses.chat_message.ChatMessage.texts", "haystack.dataclasses.chat_message.ChatMessage.text", "haystack.dataclasses.chat_message.ChatMessage.meta", "haystack.core.type_utils._strict_types_are_compatible", "haystack.core.type_utils._types_are_compatible", "haystack.core.type_utils._type_name", "haystack.core.pipeline.base._connections_status"], "language": "Python", "toolfunc_count": 4, "func_count": 5, "pytest_info": {"total_num": 35, "base_passed_num": 7}} {"id": ["haystack.haystack.components.builders.prompt_builder.PromptBuilder::_validate_variables", "haystack.haystack.components.builders.prompt_builder.PromptBuilder::run", "haystack.haystack.core.type_utils._strict_types_are_compatible", "haystack.haystack.core.type_utils._types_are_compatible"], "project": "haystack", "origin_file": ["haystack/components/builders/prompt_builder.py", "haystack/components/builders/prompt_builder.py", "haystack/core/type_utils.py", "haystack/core/type_utils.py"], "test_list": ["test/components/builders/test_prompt_builder.py"], "prob_info": [{"class_start_lineno": 17, "class_end_lineno": 266, "func_start_lineno": 247, "func_end_lineno": 266, "func_code": " def _validate_variables(self, provided_variables: Set[str]):\n \"\"\"\n Checks if all the required template variables are provided.\n\n :param provided_variables:\n A set of provided template variables.\n :raises ValueError:\n If any of the required template variables is not provided.\n \"\"\"\n if self.required_variables == \"*\":\n required_variables = sorted(self.variables)\n else:\n required_variables = self.required_variables\n missing_variables = [var for var in required_variables if var not in provided_variables]\n if missing_variables:\n missing_vars_str = \", \".join(missing_variables)\n raise ValueError(\n f\"Missing required input variables in PromptBuilder: {missing_vars_str}. \"\n f\"Required variables: {required_variables}. Provided variables: {provided_variables}.\"\n )"}, {"class_start_lineno": 17, "class_end_lineno": 266, "func_start_lineno": 213, "func_end_lineno": 245, "func_code": " def run(self, template: Optional[str] = None, template_variables: Optional[Dict[str, Any]] = None, **kwargs):\n \"\"\"\n Renders the prompt template with the provided variables.\n\n It applies the template variables to render the final prompt. You can provide variables via pipeline kwargs.\n In order to overwrite the default template, you can set the `template` parameter.\n In order to overwrite pipeline kwargs, you can set the `template_variables` parameter.\n\n :param template:\n An optional string template to overwrite PromptBuilder's default template. If None, the default template\n provided at initialization is used.\n :param template_variables:\n An optional dictionary of template variables to overwrite the pipeline variables.\n :param kwargs:\n Pipeline variables used for rendering the prompt.\n\n :returns: A dictionary with the following keys:\n - `prompt`: The updated prompt text after rendering the prompt template.\n\n :raises ValueError:\n If any of the required template variables is not provided.\n \"\"\"\n kwargs = kwargs or {}\n template_variables = template_variables or {}\n template_variables_combined = {**kwargs, **template_variables}\n self._validate_variables(set(template_variables_combined.keys()))\n\n compiled_template = self.template\n if template is not None:\n compiled_template = self._env.from_string(template)\n\n result = compiled_template.render(template_variables_combined)\n return {\"prompt\": result}"}, {"class_start_lineno": 1, "class_end_lineno": 105, "func_start_lineno": 29, "func_end_lineno": 76, "func_code": "def _strict_types_are_compatible(sender, receiver): # pylint: disable=too-many-return-statements\n \"\"\"\n Checks whether the sender type is equal to or a subtype of the receiver type under strict validation.\n\n Note: this method has no pretense to perform proper type matching. It especially does not deal with aliasing of\n typing classes such as `List` or `Dict` to their runtime counterparts `list` and `dict`. It also does not deal well\n with \"bare\" types, so `List` is treated differently from `List[Any]`, even though they should be the same.\n Consider simplifying the typing of your components if you observe unexpected errors during component connection.\n\n :param sender: The sender type.\n :param receiver: The receiver type.\n :return: True if the sender type is strictly compatible with the receiver type, False otherwise.\n \"\"\"\n if sender == receiver or receiver is Any:\n return True\n\n if sender is Any:\n return False\n\n try:\n if issubclass(sender, receiver):\n return True\n except TypeError: # typing classes can't be used with issubclass, so we deal with them below\n pass\n\n sender_origin = get_origin(sender)\n receiver_origin = get_origin(receiver)\n\n if sender_origin is not Union and receiver_origin is Union:\n return any(_strict_types_are_compatible(sender, union_arg) for union_arg in get_args(receiver))\n\n # Both must have origins and they must be equal\n if not (sender_origin and receiver_origin and sender_origin == receiver_origin):\n return False\n\n # Compare generic type arguments\n sender_args = get_args(sender)\n receiver_args = get_args(receiver)\n\n # Handle bare types\n if not sender_args and sender_origin:\n sender_args = (Any,)\n if not receiver_args and receiver_origin:\n receiver_args = (Any,) * (len(sender_args) if sender_args else 1)\n if len(sender_args) > len(receiver_args):\n return False\n\n return all(_strict_types_are_compatible(*args) for args in zip(sender_args, receiver_args))"}, {"class_start_lineno": 1, "class_end_lineno": 105, "func_start_lineno": 14, "func_end_lineno": 26, "func_code": "def _types_are_compatible(sender, receiver, type_validation: bool = True) -> bool:\n \"\"\"\n Determines if two types are compatible based on the specified validation mode.\n\n :param sender: The sender type.\n :param receiver: The receiver type.\n :param type_validation: Whether to perform strict type validation.\n :return: True if the types are compatible, False otherwise.\n \"\"\"\n if type_validation:\n return _strict_types_are_compatible(sender, receiver)\n else:\n return True"}], "type": ["function_empty"], "node": ["haystack.components.builders.prompt_builder.PromptBuilder._validate_variables", "haystack.components.builders.prompt_builder.PromptBuilder.run", "haystack.core.type_utils._strict_types_are_compatible", "haystack.core.type_utils._types_are_compatible"], "language": "Python", "toolfunc_count": 4, "func_count": 4, "pytest_info": {"total_num": 29, "base_passed_num": 7}} {"id": ["haystack.haystack.core.type_utils._strict_types_are_compatible", "haystack.haystack.core.type_utils._types_are_compatible", "haystack.haystack.core.type_utils._type_name", "haystack.haystack.core.pipeline.base._connections_status"], "project": "haystack", "origin_file": ["haystack/core/type_utils.py", "haystack/core/type_utils.py", "haystack/core/type_utils.py", "haystack/core/pipeline/base.py"], "test_list": ["test/components/classifiers/test_zero_shot_document_classifier.py", "test/components/joiners/test_list_joiner.py", "test/core/pipeline/test_pipeline.py", "test/tools/test_component_tool.py", "test/tracing/test_logging_tracer.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 105, "func_start_lineno": 29, "func_end_lineno": 76, "func_code": "def _strict_types_are_compatible(sender, receiver): # pylint: disable=too-many-return-statements\n \"\"\"\n Checks whether the sender type is equal to or a subtype of the receiver type under strict validation.\n\n Note: this method has no pretense to perform proper type matching. It especially does not deal with aliasing of\n typing classes such as `List` or `Dict` to their runtime counterparts `list` and `dict`. It also does not deal well\n with \"bare\" types, so `List` is treated differently from `List[Any]`, even though they should be the same.\n Consider simplifying the typing of your components if you observe unexpected errors during component connection.\n\n :param sender: The sender type.\n :param receiver: The receiver type.\n :return: True if the sender type is strictly compatible with the receiver type, False otherwise.\n \"\"\"\n if sender == receiver or receiver is Any:\n return True\n\n if sender is Any:\n return False\n\n try:\n if issubclass(sender, receiver):\n return True\n except TypeError: # typing classes can't be used with issubclass, so we deal with them below\n pass\n\n sender_origin = get_origin(sender)\n receiver_origin = get_origin(receiver)\n\n if sender_origin is not Union and receiver_origin is Union:\n return any(_strict_types_are_compatible(sender, union_arg) for union_arg in get_args(receiver))\n\n # Both must have origins and they must be equal\n if not (sender_origin and receiver_origin and sender_origin == receiver_origin):\n return False\n\n # Compare generic type arguments\n sender_args = get_args(sender)\n receiver_args = get_args(receiver)\n\n # Handle bare types\n if not sender_args and sender_origin:\n sender_args = (Any,)\n if not receiver_args and receiver_origin:\n receiver_args = (Any,) * (len(sender_args) if sender_args else 1)\n if len(sender_args) > len(receiver_args):\n return False\n\n return all(_strict_types_are_compatible(*args) for args in zip(sender_args, receiver_args))"}, {"class_start_lineno": 1, "class_end_lineno": 105, "func_start_lineno": 14, "func_end_lineno": 26, "func_code": "def _types_are_compatible(sender, receiver, type_validation: bool = True) -> bool:\n \"\"\"\n Determines if two types are compatible based on the specified validation mode.\n\n :param sender: The sender type.\n :param receiver: The receiver type.\n :param type_validation: Whether to perform strict type validation.\n :return: True if the types are compatible, False otherwise.\n \"\"\"\n if type_validation:\n return _strict_types_are_compatible(sender, receiver)\n else:\n return True"}, {"class_start_lineno": 1, "class_end_lineno": 105, "func_start_lineno": 79, "func_end_lineno": 105, "func_code": "def _type_name(type_):\n \"\"\"\n Util methods to get a nice readable representation of a type.\n\n Handles Optional and Literal in a special way to make it more readable.\n \"\"\"\n # Literal args are strings, so we wrap them in quotes to make it clear\n if isinstance(type_, str):\n return f\"'{type_}'\"\n\n name = getattr(type_, \"__name__\", str(type_))\n\n if name.startswith(\"typing.\"):\n name = name[7:]\n if \"[\" in name:\n name = name.split(\"[\")[0]\n args = get_args(type_)\n if name == \"Union\" and type(None) in args and len(args) == 2:\n # Optional is technically a Union of type and None\n # but we want to display it as Optional\n name = \"Optional\"\n\n if args:\n args = \", \".join([_type_name(a) for a in args if a is not type(None)])\n return f\"{name}[{args}]\"\n\n return f\"{name}\""}, {"class_start_lineno": 1, "class_end_lineno": 1261, "func_start_lineno": 1207, "func_end_lineno": 1229, "func_code": "def _connections_status(\n sender_node: str, receiver_node: str, sender_sockets: List[OutputSocket], receiver_sockets: List[InputSocket]\n) -> str:\n \"\"\"\n Lists the status of the sockets, for error messages.\n \"\"\"\n sender_sockets_entries = []\n for sender_socket in sender_sockets:\n sender_sockets_entries.append(f\" - {sender_socket.name}: {_type_name(sender_socket.type)}\")\n sender_sockets_list = \"\\n\".join(sender_sockets_entries)\n\n receiver_sockets_entries = []\n for receiver_socket in receiver_sockets:\n if receiver_socket.senders:\n sender_status = f\"sent by {','.join(receiver_socket.senders)}\"\n else:\n sender_status = \"available\"\n receiver_sockets_entries.append(\n f\" - {receiver_socket.name}: {_type_name(receiver_socket.type)} ({sender_status})\"\n )\n receiver_sockets_list = \"\\n\".join(receiver_sockets_entries)\n\n return f\"'{sender_node}':\\n{sender_sockets_list}\\n'{receiver_node}':\\n{receiver_sockets_list}\""}], "type": ["function_empty"], "node": ["haystack.core.type_utils._strict_types_are_compatible", "haystack.core.type_utils._types_are_compatible", "haystack.core.type_utils._type_name", "haystack.core.pipeline.base._connections_status"], "language": "Python", "toolfunc_count": 4, "func_count": 4, "pytest_info": {"total_num": 48, "base_passed_num": 41}} {"id": ["haystack.haystack.dataclasses.chat_message.ChatMessage::__getattribute__", "haystack.haystack.components.connectors.openapi_service.OpenAPIServiceConnector::run", "haystack.haystack.core.serialization.default_to_dict", "haystack.haystack.core.serialization.component_to_dict"], "project": "haystack", "origin_file": ["haystack/dataclasses/chat_message.py", "haystack/components/connectors/openapi_service.py", "haystack/dataclasses/chat_message.py", "haystack/dataclasses/chat_message.py", "haystack/dataclasses/chat_message.py", "haystack/core/serialization.py", "haystack/components/connectors/openapi_service.py", "haystack/core/serialization.py"], "test_list": ["test/components/connectors/test_openapi_service.py"], "prob_info": [{"class_start_lineno": 88, "class_end_lineno": 481, "func_start_lineno": 127, "func_end_lineno": 140, "func_code": " def __getattribute__(self, name):\n \"\"\"\n This method is reimplemented to make the `content` attribute removal more visible.\n \"\"\"\n\n if name == \"content\":\n msg = (\n \"The `content` attribute of `ChatMessage` has been removed. \"\n \"Use the `text` property to access the textual value. \"\n \"For more information about the new API and how to migrate, see the documentation: \"\n \"https://docs.haystack.deepset.ai/docs/chatmessage\"\n )\n raise AttributeError(msg)\n return object.__getattribute__(self, name)"}, {"class_start_lineno": 149, "class_end_lineno": 399, "func_start_lineno": 211, "func_end_lineno": 263, "func_code": " def run(\n self,\n messages: List[ChatMessage],\n service_openapi_spec: Dict[str, Any],\n service_credentials: Optional[Union[dict, str]] = None,\n ) -> Dict[str, List[ChatMessage]]:\n \"\"\"\n Processes a list of chat messages to invoke a method on an OpenAPI service.\n\n It parses the last message in the list, expecting it to contain tool calls.\n\n :param messages: A list of `ChatMessage` objects containing the messages to be processed. The last message\n should contain the tool calls.\n :param service_openapi_spec: The OpenAPI JSON specification object of the service to be invoked. All the refs\n should already be resolved.\n :param service_credentials: The credentials to be used for authentication with the service.\n Currently, only the http and apiKey OpenAPI security schemes are supported.\n\n :return: A dictionary with the following keys:\n - `service_response`: a list of `ChatMessage` objects, each containing the response from the service. The\n response is in JSON format, and the `content` attribute of the `ChatMessage` contains\n the JSON string.\n\n :raises ValueError: If the last message is not from the assistant or if it does not contain tool calls.\n \"\"\"\n\n last_message = messages[-1]\n if not last_message.is_from(ChatRole.ASSISTANT):\n raise ValueError(f\"{last_message} is not from the assistant.\")\n\n tool_calls = last_message.tool_calls\n if not tool_calls:\n raise ValueError(f\"The provided ChatMessage has no tool calls.\\nChatMessage: {last_message}\")\n\n function_payloads = []\n for tool_call in tool_calls:\n function_payloads.append({\"arguments\": tool_call.arguments, \"name\": tool_call.tool_name})\n\n # instantiate the OpenAPI service for the given specification\n openapi_service = OpenAPI(service_openapi_spec, ssl_verify=self.ssl_verify)\n self._authenticate_service(openapi_service, service_credentials)\n\n response_messages = []\n for method_invocation_descriptor in function_payloads:\n service_response = self._invoke_method(openapi_service, method_invocation_descriptor)\n # openapi3 parses the JSON service response into a model object, which is not our focus at the moment.\n # Instead, we require direct access to the raw JSON data of the response, rather than the model objects\n # provided by the openapi3 library. This approach helps us avoid issues related to (de)serialization.\n # By accessing the raw JSON response through `service_response._raw_data`, we can serialize this data\n # into a string. Finally, we use this string to create a ChatMessage object.\n response_messages.append(ChatMessage.from_user(json.dumps(service_response)))\n\n return {\"service_response\": response_messages}"}, {"class_start_lineno": 88, "class_end_lineno": 481, "func_start_lineno": 183, "func_end_lineno": 187, "func_code": " def tool_calls(self) -> List[ToolCall]:\n \"\"\"\n Returns the list of all Tool calls contained in the message.\n \"\"\"\n return [content for content in self._content if isinstance(content, ToolCall)]"}, {"class_start_lineno": 88, "class_end_lineno": 481, "func_start_lineno": 167, "func_end_lineno": 171, "func_code": " def texts(self) -> List[str]:\n \"\"\"\n Returns the list of all texts contained in the message.\n \"\"\"\n return [content.text for content in self._content if isinstance(content, TextContent)]"}, {"class_start_lineno": 88, "class_end_lineno": 481, "func_start_lineno": 174, "func_end_lineno": 180, "func_code": " def text(self) -> Optional[str]:\n \"\"\"\n Returns the first text contained in the message.\n \"\"\"\n if texts := self.texts:\n return texts[0]\n return None"}, {"class_start_lineno": 1, "class_end_lineno": 264, "func_start_lineno": 172, "func_end_lineno": 210, "func_code": "def default_to_dict(obj: Any, **init_parameters) -> Dict[str, Any]:\n \"\"\"\n Utility function to serialize an object to a dictionary.\n\n This is mostly necessary for components but can be used by any object.\n `init_parameters` are parameters passed to the object class `__init__`.\n They must be defined explicitly as they'll be used when creating a new\n instance of `obj` with `from_dict`. Omitting them might cause deserialisation\n errors or unexpected behaviours later, when calling `from_dict`.\n\n An example usage:\n\n ```python\n class MyClass:\n def __init__(self, my_param: int = 10):\n self.my_param = my_param\n\n def to_dict(self):\n return default_to_dict(self, my_param=self.my_param)\n\n\n obj = MyClass(my_param=1000)\n data = obj.to_dict()\n assert data == {\n \"type\": \"MyClass\",\n \"init_parameters\": {\n \"my_param\": 1000,\n },\n }\n ```\n\n :param obj:\n The object to be serialized.\n :param init_parameters:\n The parameters used to create a new instance of the class.\n :returns:\n A dictionary representation of the instance.\n \"\"\"\n return {\"type\": generate_qualified_class_name(type(obj)), \"init_parameters\": init_parameters}"}, {"class_start_lineno": 149, "class_end_lineno": 399, "func_start_lineno": 265, "func_end_lineno": 272, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serializes the component to a dictionary.\n\n :returns:\n Dictionary with serialized data.\n \"\"\"\n return default_to_dict(self, ssl_verify=self.ssl_verify)"}, {"class_start_lineno": 1, "class_end_lineno": 264, "func_start_lineno": 36, "func_end_lineno": 82, "func_code": "def component_to_dict(obj: Any, name: str) -> Dict[str, Any]:\n \"\"\"\n Converts a component instance into a dictionary.\n\n If a `to_dict` method is present in the component instance, that will be used instead of the default method.\n\n :param obj:\n The component to be serialized.\n :param name:\n The name of the component.\n :returns:\n A dictionary representation of the component.\n\n :raises SerializationError:\n If the component doesn't have a `to_dict` method.\n If the values of the init parameters can't be determined.\n If a non-basic Python type is used in the serialized data.\n \"\"\"\n if hasattr(obj, \"to_dict\"):\n data = obj.to_dict()\n else:\n init_parameters = {}\n for param_name, param in inspect.signature(obj.__init__).parameters.items():\n # Ignore `args` and `kwargs`, used by the default constructor\n if param_name in (\"args\", \"kwargs\"):\n continue\n try:\n # This only works if the Component constructor assigns the init\n # parameter to an instance variable or property with the same name\n param_value = getattr(obj, param_name)\n except AttributeError as e:\n # If the parameter doesn't have a default value, raise an error\n if param.default is param.empty:\n raise SerializationError(\n f\"Cannot determine the value of the init parameter '{param_name}' \"\n f\"for the class {obj.__class__.__name__}.\"\n f\"You can fix this error by assigning 'self.{param_name} = {param_name}' or adding a \"\n f\"custom serialization method 'to_dict' to the class.\"\n ) from e\n # In case the init parameter was not assigned, we use the default value\n param_value = param.default\n init_parameters[param_name] = param_value\n\n data = default_to_dict(obj, **init_parameters)\n\n _validate_component_to_dict_output(obj, name, data)\n return data"}], "type": ["function_empty", "TDD"], "node": ["haystack.dataclasses.chat_message.ChatMessage.__getattribute__", "haystack.components.connectors.openapi_service.OpenAPIServiceConnector.run", "haystack.dataclasses.chat_message.ChatMessage.tool_calls", "haystack.dataclasses.chat_message.ChatMessage.texts", "haystack.dataclasses.chat_message.ChatMessage.text", "haystack.core.serialization.default_to_dict", "haystack.components.connectors.openapi_service.OpenAPIServiceConnector.to_dict", "haystack.core.serialization.component_to_dict"], "language": "Python", "toolfunc_count": 3, "func_count": 4, "pytest_info": {"total_num": 12, "base_passed_num": 4}} {"id": ["haystack.haystack.core.serialization.default_to_dict", "haystack.haystack.components.converters.json.JSONConverter::to_dict", "haystack.haystack.components.converters.utils.normalize_metadata", "haystack.haystack.components.converters.utils.get_bytestream_from_source", "haystack.haystack.components.converters.json.JSONConverter::run"], "project": "haystack", "origin_file": ["haystack/core/serialization.py", "haystack/components/converters/json.py", "haystack/components/converters/utils.py", "haystack/components/converters/utils.py", "haystack/components/converters/json.py"], "test_list": ["test/components/converters/test_json.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 264, "func_start_lineno": 172, "func_end_lineno": 210, "func_code": "def default_to_dict(obj: Any, **init_parameters) -> Dict[str, Any]:\n \"\"\"\n Utility function to serialize an object to a dictionary.\n\n This is mostly necessary for components but can be used by any object.\n `init_parameters` are parameters passed to the object class `__init__`.\n They must be defined explicitly as they'll be used when creating a new\n instance of `obj` with `from_dict`. Omitting them might cause deserialisation\n errors or unexpected behaviours later, when calling `from_dict`.\n\n An example usage:\n\n ```python\n class MyClass:\n def __init__(self, my_param: int = 10):\n self.my_param = my_param\n\n def to_dict(self):\n return default_to_dict(self, my_param=self.my_param)\n\n\n obj = MyClass(my_param=1000)\n data = obj.to_dict()\n assert data == {\n \"type\": \"MyClass\",\n \"init_parameters\": {\n \"my_param\": 1000,\n },\n }\n ```\n\n :param obj:\n The object to be serialized.\n :param init_parameters:\n The parameters used to create a new instance of the class.\n :returns:\n A dictionary representation of the instance.\n \"\"\"\n return {\"type\": generate_qualified_class_name(type(obj)), \"init_parameters\": init_parameters}"}, {"class_start_lineno": 22, "class_end_lineno": 291, "func_start_lineno": 152, "func_end_lineno": 165, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serializes the component to a dictionary.\n\n :returns:\n Dictionary with serialized data.\n \"\"\"\n return default_to_dict(\n self,\n jq_schema=self._jq_schema,\n content_key=self._content_key,\n extra_meta_fields=self._meta_fields,\n store_full_path=self._store_full_path,\n )"}, {"class_start_lineno": 1, "class_end_lineno": 51, "func_start_lineno": 30, "func_end_lineno": 51, "func_code": "def normalize_metadata(\n meta: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]], sources_count: int\n) -> List[Dict[str, Any]]:\n \"\"\"\n Normalize the metadata input for a converter.\n\n Given all the possible value of the meta input for a converter (None, dictionary or list of dicts),\n makes sure to return a list of dictionaries of the correct length for the converter to use.\n\n :param meta: the meta input of the converter, as-is\n :param sources_count: the number of sources the converter received\n :returns: a list of dictionaries of the make length as the sources list\n \"\"\"\n if meta is None:\n return [{}] * sources_count\n if isinstance(meta, dict):\n return [meta] * sources_count\n if isinstance(meta, list):\n if sources_count != len(meta):\n raise ValueError(\"The length of the metadata list must match the number of sources.\")\n return meta\n raise ValueError(\"meta must be either None, a dictionary or a list of dictionaries.\")"}, {"class_start_lineno": 1, "class_end_lineno": 51, "func_start_lineno": 11, "func_end_lineno": 27, "func_code": "def get_bytestream_from_source(source: Union[str, Path, ByteStream]) -> ByteStream:\n \"\"\"\n Creates a ByteStream object from a source.\n\n :param source:\n A source to convert to a ByteStream. Can be a string (path to a file), a Path object, or a ByteStream.\n :return:\n A ByteStream object.\n \"\"\"\n\n if isinstance(source, ByteStream):\n return source\n if isinstance(source, (str, Path)):\n bs = ByteStream.from_file_path(Path(source))\n bs.meta[\"file_path\"] = str(source)\n return bs\n raise ValueError(f\"Unsupported source type {type(source)}\")"}, {"class_start_lineno": 22, "class_end_lineno": 291, "func_start_lineno": 250, "func_end_lineno": 291, "func_code": " def run(\n self,\n sources: List[Union[str, Path, ByteStream]],\n meta: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None,\n ):\n \"\"\"\n Converts a list of JSON files to documents.\n\n :param sources:\n A list of file paths or ByteStream objects.\n :param meta:\n Optional metadata to attach to the documents.\n This value can be either a list of dictionaries or a single dictionary.\n If it's a single dictionary, its content is added to the metadata of all produced documents.\n If it's a list, the length of the list must match the number of sources.\n If `sources` contain ByteStream objects, their `meta` will be added to the output documents.\n\n :returns:\n A dictionary with the following keys:\n - `documents`: A list of created documents.\n \"\"\"\n documents = []\n meta_list = normalize_metadata(meta=meta, sources_count=len(sources))\n\n for source, metadata in zip(sources, meta_list):\n try:\n bytestream = get_bytestream_from_source(source)\n except Exception as exc:\n logger.warning(\"Could not read {source}. Skipping it. Error: {error}\", source=source, error=exc)\n continue\n\n data = self._get_content_and_meta(bytestream)\n\n for text, extra_meta in data:\n merged_metadata = {**bytestream.meta, **metadata, **extra_meta}\n\n if not self._store_full_path and (file_path := bytestream.meta.get(\"file_path\")):\n merged_metadata[\"file_path\"] = os.path.basename(file_path)\n document = Document(content=text, meta=merged_metadata)\n documents.append(document)\n\n return {\"documents\": documents}"}], "type": ["function_empty"], "node": ["haystack.core.serialization.default_to_dict", "haystack.components.converters.json.JSONConverter.to_dict", "haystack.components.converters.utils.normalize_metadata", "haystack.components.converters.utils.get_bytestream_from_source", "haystack.components.converters.json.JSONConverter.run"], "language": "Python", "toolfunc_count": 5, "func_count": 5, "pytest_info": {"total_num": 19, "base_passed_num": 5}} {"id": ["haystack.haystack.components.converters.openapi_functions.OpenAPIServiceToFunctions::_parse_openapi_spec", "haystack.haystack.components.converters.openapi_functions.OpenAPIServiceToFunctions::run", "haystack.haystack.components.converters.openapi_functions.OpenAPIServiceToFunctions::_parse_property_attributes", "haystack.haystack.components.converters.openapi_functions.OpenAPIServiceToFunctions::_openapi_to_functions"], "project": "haystack", "origin_file": ["haystack/components/converters/openapi_functions.py", "haystack/components/converters/openapi_functions.py", "haystack/components/converters/openapi_functions.py", "haystack/components/converters/openapi_functions.py", "haystack/components/converters/openapi_functions.py"], "test_list": ["test/components/converters/test_openapi_functions.py"], "prob_info": [{"class_start_lineno": 23, "class_end_lineno": 257, "func_start_lineno": 232, "func_end_lineno": 257, "func_code": " def _parse_openapi_spec(self, content: str) -> Dict[str, Any]:\n \"\"\"\n Parses OpenAPI specification content, supporting both JSON and YAML formats.\n\n :param content: The content of the OpenAPI specification.\n :return: The parsed OpenAPI specification.\n \"\"\"\n open_api_spec_content = None\n try:\n open_api_spec_content = json.loads(content)\n return jsonref.replace_refs(open_api_spec_content)\n except json.JSONDecodeError as json_error:\n # heuristic to confirm that the content is likely malformed JSON\n if content.strip().startswith((\"{\", \"[\")):\n raise json_error\n\n try:\n open_api_spec_content = yaml.safe_load(content)\n except yaml.YAMLError:\n error_message = (\n \"Failed to parse the OpenAPI specification. The content does not appear to be valid JSON or YAML.\\n\\n\"\n )\n raise RuntimeError(error_message, content)\n\n # Replace references in the object with their resolved values, if any\n return jsonref.replace_refs(open_api_spec_content)"}, {"class_start_lineno": 23, "class_end_lineno": 257, "func_start_lineno": 56, "func_end_lineno": 115, "func_code": " def run(self, sources: List[Union[str, Path, ByteStream]]) -> Dict[str, Any]:\n \"\"\"\n Converts OpenAPI definitions in OpenAI function calling format.\n\n :param sources:\n File paths or ByteStream objects of OpenAPI definitions (in JSON or YAML format).\n\n :returns:\n A dictionary with the following keys:\n - functions: Function definitions in JSON object format\n - openapi_specs: OpenAPI specs in JSON/YAML object format with resolved references\n\n :raises RuntimeError:\n If the OpenAPI definitions cannot be downloaded or processed.\n :raises ValueError:\n If the source type is not recognized or no functions are found in the OpenAPI definitions.\n \"\"\"\n all_extracted_fc_definitions: List[Dict[str, Any]] = []\n all_openapi_specs = []\n for source in sources:\n openapi_spec_content = None\n if isinstance(source, (str, Path)):\n if os.path.exists(source):\n try:\n with open(source, \"r\") as f:\n openapi_spec_content = f.read()\n except IOError as e:\n logger.warning(\n \"IO error reading OpenAPI specification file: {source}. Error: {e}\", source=source, e=e\n )\n else:\n logger.warning(f\"OpenAPI specification file not found: {source}\")\n elif isinstance(source, ByteStream):\n openapi_spec_content = source.data.decode(\"utf-8\")\n if not openapi_spec_content:\n logger.warning(\n \"Invalid OpenAPI specification content provided: {openapi_spec_content}\",\n openapi_spec_content=openapi_spec_content,\n )\n else:\n logger.warning(\n \"Invalid source type {source}. Only str, Path, and ByteStream are supported.\", source=type(source)\n )\n continue\n\n if openapi_spec_content:\n try:\n service_openapi_spec = self._parse_openapi_spec(openapi_spec_content)\n functions: List[Dict[str, Any]] = self._openapi_to_functions(service_openapi_spec)\n all_extracted_fc_definitions.extend(functions)\n all_openapi_specs.append(service_openapi_spec)\n except Exception as e:\n logger.error(\n \"Error processing OpenAPI specification from source {source}: {error}\", source=source, error=e\n )\n\n if not all_extracted_fc_definitions:\n logger.warning(\"No OpenAI function definitions extracted from the provided OpenAPI specification sources.\")\n\n return {\"functions\": all_extracted_fc_definitions, \"openapi_specs\": all_openapi_specs}"}, {"class_start_lineno": 23, "class_end_lineno": 257, "func_start_lineno": 193, "func_end_lineno": 230, "func_code": " def _parse_property_attributes(\n self, property_schema: Dict[str, Any], include_attributes: Optional[List[str]] = None\n ) -> Dict[str, Any]:\n \"\"\"\n Parses the attributes of a property schema.\n\n Recursively parses the attributes of a property schema, including nested objects and arrays,\n and includes specified attributes like description, pattern, etc.\n\n :param property_schema: The schema of the property to parse.\n :param include_attributes: The list of attributes to include in the parsed schema.\n :return: The parsed schema of the property including the specified attributes.\n \"\"\"\n include_attributes = include_attributes or [\"description\", \"pattern\", \"enum\"]\n\n schema_type = property_schema.get(\"type\")\n\n parsed_schema = {\"type\": schema_type} if schema_type else {}\n for attr in include_attributes:\n if attr in property_schema:\n parsed_schema[attr] = property_schema[attr]\n\n if schema_type == \"object\":\n properties = property_schema.get(\"properties\", {})\n parsed_properties = {\n prop_name: self._parse_property_attributes(prop, include_attributes)\n for prop_name, prop in properties.items()\n }\n parsed_schema[\"properties\"] = parsed_properties\n\n if \"required\" in property_schema:\n parsed_schema[\"required\"] = property_schema[\"required\"]\n\n elif schema_type == \"array\":\n items = property_schema.get(\"items\", {})\n parsed_schema[\"items\"] = self._parse_property_attributes(items, include_attributes)\n\n return parsed_schema"}, {"class_start_lineno": 23, "class_end_lineno": 257, "func_start_lineno": 153, "func_end_lineno": 191, "func_code": " def _parse_endpoint_spec(self, resolved_spec: Dict[str, Any]) -> Optional[Dict[str, Any]]:\n if not isinstance(resolved_spec, dict):\n logger.warning(\"Invalid OpenAPI spec format provided. Could not extract function.\")\n return {}\n\n function_name = resolved_spec.get(\"operationId\")\n description = resolved_spec.get(\"description\") or resolved_spec.get(\"summary\", \"\")\n\n schema: Dict[str, Any] = {\"type\": \"object\", \"properties\": {}}\n\n # requestBody section\n req_body_schema = (\n resolved_spec.get(\"requestBody\", {}).get(\"content\", {}).get(\"application/json\", {}).get(\"schema\", {})\n )\n if \"properties\" in req_body_schema:\n for prop_name, prop_schema in req_body_schema[\"properties\"].items():\n schema[\"properties\"][prop_name] = self._parse_property_attributes(prop_schema)\n\n if \"required\" in req_body_schema:\n schema.setdefault(\"required\", []).extend(req_body_schema[\"required\"])\n\n # parameters section\n for param in resolved_spec.get(\"parameters\", []):\n if \"schema\" in param:\n schema_dict = self._parse_property_attributes(param[\"schema\"])\n # these attributes are not in param[schema] level but on param level\n useful_attributes = [\"description\", \"pattern\", \"enum\"]\n schema_dict.update({key: param[key] for key in useful_attributes if param.get(key)})\n schema[\"properties\"][param[\"name\"]] = schema_dict\n if param.get(\"required\", False):\n schema.setdefault(\"required\", []).append(param[\"name\"])\n\n if function_name and description and schema[\"properties\"]:\n return {\"name\": function_name, \"description\": description, \"parameters\": schema}\n else:\n logger.warning(\n \"Invalid OpenAPI spec format provided. Could not extract function from {spec}\", spec=resolved_spec\n )\n return {}"}, {"class_start_lineno": 23, "class_end_lineno": 257, "func_start_lineno": 117, "func_end_lineno": 151, "func_code": " def _openapi_to_functions(self, service_openapi_spec: Dict[str, Any]) -> List[Dict[str, Any]]:\n \"\"\"\n OpenAPI to OpenAI function conversion.\n\n Extracts functions from the OpenAPI specification of the service and converts them into a format\n suitable for OpenAI function calling.\n\n :param service_openapi_spec: The OpenAPI specification from which functions are to be extracted.\n :type service_openapi_spec: Dict[str, Any]\n :return: A list of dictionaries, each representing a function. Each dictionary includes the function's\n name, description, and a schema of its parameters.\n :rtype: List[Dict[str, Any]]\n \"\"\"\n\n # Doesn't enforce rigid spec validation because that would require a lot of dependencies\n # We check the version and require minimal fields to be present, so we can extract functions\n spec_version = service_openapi_spec.get(\"openapi\")\n if not spec_version:\n raise ValueError(f\"Invalid OpenAPI spec provided. Could not extract version from {service_openapi_spec}\")\n service_openapi_spec_version = int(spec_version.split(\".\")[0])\n\n # Compare the versions\n if service_openapi_spec_version < OpenAPIServiceToFunctions.MIN_REQUIRED_OPENAPI_SPEC_VERSION:\n raise ValueError(\n f\"Invalid OpenAPI spec version {service_openapi_spec_version}. Must be \"\n f\"at least {OpenAPIServiceToFunctions.MIN_REQUIRED_OPENAPI_SPEC_VERSION}.\"\n )\n\n functions: List[Dict[str, Any]] = []\n for paths in service_openapi_spec[\"paths\"].values():\n for path_spec in paths.values():\n function_dict = self._parse_endpoint_spec(path_spec)\n if function_dict:\n functions.append(function_dict)\n return functions"}], "type": ["function_empty"], "node": ["haystack.components.converters.openapi_functions.OpenAPIServiceToFunctions._parse_openapi_spec", "haystack.components.converters.openapi_functions.OpenAPIServiceToFunctions.run", "haystack.components.converters.openapi_functions.OpenAPIServiceToFunctions._parse_property_attributes", "haystack.components.converters.openapi_functions.OpenAPIServiceToFunctions._parse_endpoint_spec", "haystack.components.converters.openapi_functions.OpenAPIServiceToFunctions._openapi_to_functions"], "language": "Python", "toolfunc_count": 4, "func_count": 4, "pytest_info": {"total_num": 8, "base_passed_num": 0}} {"id": ["haystack.haystack.utils.callable_serialization.serialize_callable", "haystack.haystack.components.converters.output_adapter.OutputAdapter::to_dict", "haystack.haystack.utils.type_serialization.thread_safe_import", "haystack.haystack.utils.callable_serialization.deserialize_callable"], "project": "haystack", "origin_file": ["haystack/utils/callable_serialization.py", "haystack/components/converters/output_adapter.py", "haystack/utils/type_serialization.py", "haystack/utils/callable_serialization.py"], "test_list": ["test/components/converters/test_output_adapter.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 80, "func_start_lineno": 12, "func_end_lineno": 42, "func_code": "def serialize_callable(callable_handle: Callable) -> str:\n \"\"\"\n Serializes a callable to its full path.\n\n :param callable_handle: The callable to serialize\n :return: The full path of the callable\n \"\"\"\n try:\n full_arg_spec = inspect.getfullargspec(callable_handle)\n is_instance_method = bool(full_arg_spec.args and full_arg_spec.args[0] == \"self\")\n except TypeError:\n is_instance_method = False\n if is_instance_method:\n raise SerializationError(\"Serialization of instance methods is not supported.\")\n\n # __qualname__ contains the fully qualified path we need for classmethods and staticmethods\n qualname = getattr(callable_handle, \"__qualname__\", \"\")\n if \"\" in qualname:\n raise SerializationError(\"Serialization of lambdas is not supported.\")\n if \"\" in qualname:\n raise SerializationError(\"Serialization of nested functions is not supported.\")\n\n name = qualname or callable_handle.__name__\n\n # Get the full package path of the function\n module = inspect.getmodule(callable_handle)\n if module is not None:\n full_path = f\"{module.__name__}.{name}\"\n else:\n full_path = name\n return full_path"}, {"class_start_lineno": 25, "class_end_lineno": 184, "func_start_lineno": 139, "func_end_lineno": 153, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serializes the component to a dictionary.\n\n :returns:\n Dictionary with serialized data.\n \"\"\"\n se_filters = {name: serialize_callable(filter_func) for name, filter_func in self.custom_filters.items()}\n return default_to_dict(\n self,\n template=self.template,\n output_type=serialize_type(self.output_type),\n custom_filters=se_filters,\n unsafe=self._unsafe,\n )"}, {"class_start_lineno": 1, "class_end_lineno": 170, "func_start_lineno": 159, "func_end_lineno": 170, "func_code": "def thread_safe_import(module_name: str) -> ModuleType:\n \"\"\"\n Import a module in a thread-safe manner.\n\n Importing modules in a multi-threaded environment can lead to race conditions.\n This function ensures that the module is imported in a thread-safe manner without having impact\n on the performance of the import for single-threaded environments.\n\n :param module_name: the module to import\n \"\"\"\n with _import_lock:\n return importlib.import_module(module_name)"}, {"class_start_lineno": 1, "class_end_lineno": 80, "func_start_lineno": 45, "func_end_lineno": 80, "func_code": "def deserialize_callable(callable_handle: str) -> Callable:\n \"\"\"\n Deserializes a callable given its full import path as a string.\n\n :param callable_handle: The full path of the callable_handle\n :return: The callable\n :raises DeserializationError: If the callable cannot be found\n \"\"\"\n parts = callable_handle.split(\".\")\n\n for i in range(len(parts), 0, -1):\n module_name = \".\".join(parts[:i])\n try:\n mod: Any = thread_safe_import(module_name)\n except Exception:\n # keep reducing i until we find a valid module import\n continue\n\n attr_value = mod\n for part in parts[i:]:\n try:\n attr_value = getattr(attr_value, part)\n except AttributeError as e:\n raise DeserializationError(f\"Could not find attribute '{part}' in {attr_value.__name__}\") from e\n\n # when the attribute is a classmethod, we need the underlying function\n if isinstance(attr_value, (classmethod, staticmethod)):\n attr_value = attr_value.__func__\n\n if not callable(attr_value):\n raise DeserializationError(f\"The final attribute is not callable: {attr_value}\")\n\n return attr_value\n\n # Fallback if we never find anything\n raise DeserializationError(f\"Could not import '{callable_handle}' as a module or callable.\")"}], "type": ["function_empty", "TDD"], "node": ["haystack.utils.callable_serialization.serialize_callable", "haystack.components.converters.output_adapter.OutputAdapter.to_dict", "haystack.utils.type_serialization.thread_safe_import", "haystack.utils.callable_serialization.deserialize_callable"], "language": "Python", "toolfunc_count": 3, "func_count": 4, "pytest_info": {"total_num": 14, "base_passed_num": 10}} {"id": ["haystack.haystack.utils.callable_serialization.serialize_callable", "haystack.haystack.components.embedders.azure_document_embedder.AzureOpenAIDocumentEmbedder::to_dict", "haystack.haystack.utils.type_serialization.thread_safe_import", "haystack.haystack.utils.callable_serialization.deserialize_callable"], "project": "haystack", "origin_file": ["haystack/utils/callable_serialization.py", "haystack/components/embedders/azure_document_embedder.py", "haystack/utils/type_serialization.py", "haystack/utils/callable_serialization.py"], "test_list": ["test/components/embedders/test_azure_document_embedder.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 80, "func_start_lineno": 12, "func_end_lineno": 42, "func_code": "def serialize_callable(callable_handle: Callable) -> str:\n \"\"\"\n Serializes a callable to its full path.\n\n :param callable_handle: The callable to serialize\n :return: The full path of the callable\n \"\"\"\n try:\n full_arg_spec = inspect.getfullargspec(callable_handle)\n is_instance_method = bool(full_arg_spec.args and full_arg_spec.args[0] == \"self\")\n except TypeError:\n is_instance_method = False\n if is_instance_method:\n raise SerializationError(\"Serialization of instance methods is not supported.\")\n\n # __qualname__ contains the fully qualified path we need for classmethods and staticmethods\n qualname = getattr(callable_handle, \"__qualname__\", \"\")\n if \"\" in qualname:\n raise SerializationError(\"Serialization of lambdas is not supported.\")\n if \"\" in qualname:\n raise SerializationError(\"Serialization of nested functions is not supported.\")\n\n name = qualname or callable_handle.__name__\n\n # Get the full package path of the function\n module = inspect.getmodule(callable_handle)\n if module is not None:\n full_path = f\"{module.__name__}.{name}\"\n else:\n full_path = name\n return full_path"}, {"class_start_lineno": 20, "class_end_lineno": 281, "func_start_lineno": 154, "func_end_lineno": 183, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serializes the component to a dictionary.\n\n :returns:\n Dictionary with serialized data.\n \"\"\"\n azure_ad_token_provider_name = None\n if self.azure_ad_token_provider:\n azure_ad_token_provider_name = serialize_callable(self.azure_ad_token_provider)\n return default_to_dict(\n self,\n azure_endpoint=self.azure_endpoint,\n azure_deployment=self.azure_deployment,\n dimensions=self.dimensions,\n organization=self.organization,\n api_version=self.api_version,\n prefix=self.prefix,\n suffix=self.suffix,\n batch_size=self.batch_size,\n progress_bar=self.progress_bar,\n meta_fields_to_embed=self.meta_fields_to_embed,\n embedding_separator=self.embedding_separator,\n api_key=self.api_key.to_dict() if self.api_key is not None else None,\n azure_ad_token=self.azure_ad_token.to_dict() if self.azure_ad_token is not None else None,\n timeout=self.timeout,\n max_retries=self.max_retries,\n default_headers=self.default_headers,\n azure_ad_token_provider=azure_ad_token_provider_name,\n )"}, {"class_start_lineno": 1, "class_end_lineno": 170, "func_start_lineno": 159, "func_end_lineno": 170, "func_code": "def thread_safe_import(module_name: str) -> ModuleType:\n \"\"\"\n Import a module in a thread-safe manner.\n\n Importing modules in a multi-threaded environment can lead to race conditions.\n This function ensures that the module is imported in a thread-safe manner without having impact\n on the performance of the import for single-threaded environments.\n\n :param module_name: the module to import\n \"\"\"\n with _import_lock:\n return importlib.import_module(module_name)"}, {"class_start_lineno": 1, "class_end_lineno": 80, "func_start_lineno": 45, "func_end_lineno": 80, "func_code": "def deserialize_callable(callable_handle: str) -> Callable:\n \"\"\"\n Deserializes a callable given its full import path as a string.\n\n :param callable_handle: The full path of the callable_handle\n :return: The callable\n :raises DeserializationError: If the callable cannot be found\n \"\"\"\n parts = callable_handle.split(\".\")\n\n for i in range(len(parts), 0, -1):\n module_name = \".\".join(parts[:i])\n try:\n mod: Any = thread_safe_import(module_name)\n except Exception:\n # keep reducing i until we find a valid module import\n continue\n\n attr_value = mod\n for part in parts[i:]:\n try:\n attr_value = getattr(attr_value, part)\n except AttributeError as e:\n raise DeserializationError(f\"Could not find attribute '{part}' in {attr_value.__name__}\") from e\n\n # when the attribute is a classmethod, we need the underlying function\n if isinstance(attr_value, (classmethod, staticmethod)):\n attr_value = attr_value.__func__\n\n if not callable(attr_value):\n raise DeserializationError(f\"The final attribute is not callable: {attr_value}\")\n\n return attr_value\n\n # Fallback if we never find anything\n raise DeserializationError(f\"Could not import '{callable_handle}' as a module or callable.\")"}], "type": ["function_empty", "TDD"], "node": ["haystack.utils.callable_serialization.serialize_callable", "haystack.components.embedders.azure_document_embedder.AzureOpenAIDocumentEmbedder.to_dict", "haystack.utils.type_serialization.thread_safe_import", "haystack.utils.callable_serialization.deserialize_callable"], "language": "Python", "toolfunc_count": 3, "func_count": 4, "pytest_info": {"total_num": 6, "base_passed_num": 3}} {"id": ["haystack.haystack.utils.callable_serialization.serialize_callable", "haystack.haystack.components.embedders.azure_text_embedder.AzureOpenAITextEmbedder::to_dict", "haystack.haystack.utils.type_serialization.thread_safe_import", "haystack.haystack.utils.callable_serialization.deserialize_callable"], "project": "haystack", "origin_file": ["haystack/utils/callable_serialization.py", "haystack/components/embedders/azure_text_embedder.py", "haystack/utils/type_serialization.py", "haystack/utils/callable_serialization.py"], "test_list": ["test/components/embedders/test_azure_text_embedder.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 80, "func_start_lineno": 12, "func_end_lineno": 42, "func_code": "def serialize_callable(callable_handle: Callable) -> str:\n \"\"\"\n Serializes a callable to its full path.\n\n :param callable_handle: The callable to serialize\n :return: The full path of the callable\n \"\"\"\n try:\n full_arg_spec = inspect.getfullargspec(callable_handle)\n is_instance_method = bool(full_arg_spec.args and full_arg_spec.args[0] == \"self\")\n except TypeError:\n is_instance_method = False\n if is_instance_method:\n raise SerializationError(\"Serialization of instance methods is not supported.\")\n\n # __qualname__ contains the fully qualified path we need for classmethods and staticmethods\n qualname = getattr(callable_handle, \"__qualname__\", \"\")\n if \"\" in qualname:\n raise SerializationError(\"Serialization of lambdas is not supported.\")\n if \"\" in qualname:\n raise SerializationError(\"Serialization of nested functions is not supported.\")\n\n name = qualname or callable_handle.__name__\n\n # Get the full package path of the function\n module = inspect.getmodule(callable_handle)\n if module is not None:\n full_path = f\"{module.__name__}.{name}\"\n else:\n full_path = name\n return full_path"}, {"class_start_lineno": 15, "class_end_lineno": 216, "func_start_lineno": 136, "func_end_lineno": 161, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serializes the component to a dictionary.\n\n :returns:\n Dictionary with serialized data.\n \"\"\"\n azure_ad_token_provider_name = None\n if self.azure_ad_token_provider:\n azure_ad_token_provider_name = serialize_callable(self.azure_ad_token_provider)\n return default_to_dict(\n self,\n azure_endpoint=self.azure_endpoint,\n azure_deployment=self.azure_deployment,\n dimensions=self.dimensions,\n organization=self.organization,\n api_version=self.api_version,\n prefix=self.prefix,\n suffix=self.suffix,\n api_key=self.api_key.to_dict() if self.api_key is not None else None,\n azure_ad_token=self.azure_ad_token.to_dict() if self.azure_ad_token is not None else None,\n timeout=self.timeout,\n max_retries=self.max_retries,\n default_headers=self.default_headers,\n azure_ad_token_provider=azure_ad_token_provider_name,\n )"}, {"class_start_lineno": 1, "class_end_lineno": 170, "func_start_lineno": 159, "func_end_lineno": 170, "func_code": "def thread_safe_import(module_name: str) -> ModuleType:\n \"\"\"\n Import a module in a thread-safe manner.\n\n Importing modules in a multi-threaded environment can lead to race conditions.\n This function ensures that the module is imported in a thread-safe manner without having impact\n on the performance of the import for single-threaded environments.\n\n :param module_name: the module to import\n \"\"\"\n with _import_lock:\n return importlib.import_module(module_name)"}, {"class_start_lineno": 1, "class_end_lineno": 80, "func_start_lineno": 45, "func_end_lineno": 80, "func_code": "def deserialize_callable(callable_handle: str) -> Callable:\n \"\"\"\n Deserializes a callable given its full import path as a string.\n\n :param callable_handle: The full path of the callable_handle\n :return: The callable\n :raises DeserializationError: If the callable cannot be found\n \"\"\"\n parts = callable_handle.split(\".\")\n\n for i in range(len(parts), 0, -1):\n module_name = \".\".join(parts[:i])\n try:\n mod: Any = thread_safe_import(module_name)\n except Exception:\n # keep reducing i until we find a valid module import\n continue\n\n attr_value = mod\n for part in parts[i:]:\n try:\n attr_value = getattr(attr_value, part)\n except AttributeError as e:\n raise DeserializationError(f\"Could not find attribute '{part}' in {attr_value.__name__}\") from e\n\n # when the attribute is a classmethod, we need the underlying function\n if isinstance(attr_value, (classmethod, staticmethod)):\n attr_value = attr_value.__func__\n\n if not callable(attr_value):\n raise DeserializationError(f\"The final attribute is not callable: {attr_value}\")\n\n return attr_value\n\n # Fallback if we never find anything\n raise DeserializationError(f\"Could not import '{callable_handle}' as a module or callable.\")"}], "type": ["function_empty", "TDD"], "node": ["haystack.utils.callable_serialization.serialize_callable", "haystack.components.embedders.azure_text_embedder.AzureOpenAITextEmbedder.to_dict", "haystack.utils.type_serialization.thread_safe_import", "haystack.utils.callable_serialization.deserialize_callable"], "language": "Python", "toolfunc_count": 3, "func_count": 4, "pytest_info": {"total_num": 5, "base_passed_num": 2}} {"id": ["haystack.haystack.components.embedders.hugging_face_api_document_embedder.HuggingFaceAPIDocumentEmbedder::_prepare_texts_to_embed", "haystack.haystack.components.embedders.hugging_face_api_document_embedder.HuggingFaceAPIDocumentEmbedder::run"], "project": "haystack", "origin_file": ["haystack/components/embedders/hugging_face_api_document_embedder.py", "haystack/components/embedders/hugging_face_api_document_embedder.py"], "test_list": ["test/components/embedders/test_hugging_face_api_document_embedder.py"], "prob_info": [{"class_start_lineno": 24, "class_end_lineno": 298, "func_start_lineno": 219, "func_end_lineno": 234, "func_code": " def _prepare_texts_to_embed(self, documents: List[Document]) -> List[str]:\n \"\"\"\n Prepare the texts to embed by concatenating the Document text with the metadata fields to embed.\n \"\"\"\n texts_to_embed = []\n for doc in documents:\n meta_values_to_embed = [\n str(doc.meta[key]) for key in self.meta_fields_to_embed if key in doc.meta and doc.meta[key] is not None\n ]\n\n text_to_embed = (\n self.prefix + self.embedding_separator.join(meta_values_to_embed + [doc.content or \"\"]) + self.suffix\n )\n\n texts_to_embed.append(text_to_embed)\n return texts_to_embed"}, {"class_start_lineno": 24, "class_end_lineno": 298, "func_start_lineno": 274, "func_end_lineno": 298, "func_code": " def run(self, documents: List[Document]):\n \"\"\"\n Embeds a list of documents.\n\n :param documents:\n Documents to embed.\n\n :returns:\n A dictionary with the following keys:\n - `documents`: A list of documents with embeddings.\n \"\"\"\n if not isinstance(documents, list) or documents and not isinstance(documents[0], Document):\n raise TypeError(\n \"HuggingFaceAPIDocumentEmbedder expects a list of Documents as input.\"\n \" In case you want to embed a string, please use the HuggingFaceAPITextEmbedder.\"\n )\n\n texts_to_embed = self._prepare_texts_to_embed(documents=documents)\n\n embeddings = self._embed_batch(texts_to_embed=texts_to_embed, batch_size=self.batch_size)\n\n for doc, emb in zip(documents, embeddings):\n doc.embedding = emb\n\n return {\"documents\": documents}"}], "type": ["function_empty"], "node": ["haystack.components.embedders.hugging_face_api_document_embedder.HuggingFaceAPIDocumentEmbedder._prepare_texts_to_embed", "haystack.components.embedders.hugging_face_api_document_embedder.HuggingFaceAPIDocumentEmbedder.run"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 17, "base_passed_num": 12}} {"id": ["haystack.haystack.components.embedders.openai_document_embedder.OpenAIDocumentEmbedder::_prepare_texts_to_embed", "haystack.haystack.components.embedders.openai_document_embedder.OpenAIDocumentEmbedder::run"], "project": "haystack", "origin_file": ["haystack/components/embedders/openai_document_embedder.py", "haystack/components/embedders/openai_document_embedder.py"], "test_list": ["test/components/embedders/test_openai_document_embedder.py"], "prob_info": [{"class_start_lineno": 19, "class_end_lineno": 245, "func_start_lineno": 164, "func_end_lineno": 181, "func_code": " def _prepare_texts_to_embed(self, documents: List[Document]) -> Dict[str, str]:\n \"\"\"\n Prepare the texts to embed by concatenating the Document text with the metadata fields to embed.\n \"\"\"\n texts_to_embed = {}\n for doc in documents:\n meta_values_to_embed = [\n str(doc.meta[key]) for key in self.meta_fields_to_embed if key in doc.meta and doc.meta[key] is not None\n ]\n\n text_to_embed = (\n self.prefix + self.embedding_separator.join(meta_values_to_embed + [doc.content or \"\"]) + self.suffix\n )\n\n # copied from OpenAI embedding_utils (https://github.com/openai/openai-python/blob/main/openai/embeddings_utils.py)\n # replace newlines, which can negatively affect performance.\n texts_to_embed[doc.id] = text_to_embed.replace(\"\\n\", \" \")\n return texts_to_embed"}, {"class_start_lineno": 19, "class_end_lineno": 245, "func_start_lineno": 220, "func_end_lineno": 245, "func_code": " def run(self, documents: List[Document]):\n \"\"\"\n Embeds a list of documents.\n\n :param documents:\n A list of documents to embed.\n\n :returns:\n A dictionary with the following keys:\n - `documents`: A list of documents with embeddings.\n - `meta`: Information about the usage of the model.\n \"\"\"\n if not isinstance(documents, list) or documents and not isinstance(documents[0], Document):\n raise TypeError(\n \"OpenAIDocumentEmbedder expects a list of Documents as input.\"\n \"In case you want to embed a string, please use the OpenAITextEmbedder.\"\n )\n\n texts_to_embed = self._prepare_texts_to_embed(documents=documents)\n\n embeddings, meta = self._embed_batch(texts_to_embed=texts_to_embed, batch_size=self.batch_size)\n\n for doc, emb in zip(documents, embeddings):\n doc.embedding = emb\n\n return {\"documents\": documents, \"meta\": meta}"}], "type": ["function_empty"], "node": ["haystack.components.embedders.openai_document_embedder.OpenAIDocumentEmbedder._prepare_texts_to_embed", "haystack.components.embedders.openai_document_embedder.OpenAIDocumentEmbedder.run"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 11, "base_passed_num": 7}} {"id": ["haystack.haystack.utils.device.ComponentDevice::to_dict", "haystack.haystack.components.embedders.sentence_transformers_document_embedder.SentenceTransformersDocumentEmbedder::to_dict"], "project": "haystack", "origin_file": ["haystack/utils/device.py", "haystack/components/embedders/sentence_transformers_document_embedder.py"], "test_list": ["test/components/embedders/test_sentence_transformers_document_embedder.py"], "prob_info": [{"class_start_lineno": 240, "class_end_lineno": 480, "func_start_lineno": 450, "func_end_lineno": 463, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Convert the component device representation to a JSON-serializable dictionary.\n\n :returns:\n The dictionary representation.\n \"\"\"\n if self._single_device is not None:\n return {\"type\": \"single\", \"device\": str(self._single_device)}\n elif self._multiple_devices is not None:\n return {\"type\": \"multiple\", \"device_map\": self._multiple_devices.to_dict()}\n else:\n # Unreachable\n assert False"}, {"class_start_lineno": 16, "class_end_lineno": 256, "func_start_lineno": 145, "func_end_lineno": 175, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serializes the component to a dictionary.\n\n :returns:\n Dictionary with serialized data.\n \"\"\"\n serialization_dict = default_to_dict(\n self,\n model=self.model,\n device=self.device.to_dict(),\n token=self.token.to_dict() if self.token else None,\n prefix=self.prefix,\n suffix=self.suffix,\n batch_size=self.batch_size,\n progress_bar=self.progress_bar,\n normalize_embeddings=self.normalize_embeddings,\n meta_fields_to_embed=self.meta_fields_to_embed,\n embedding_separator=self.embedding_separator,\n trust_remote_code=self.trust_remote_code,\n truncate_dim=self.truncate_dim,\n model_kwargs=self.model_kwargs,\n tokenizer_kwargs=self.tokenizer_kwargs,\n config_kwargs=self.config_kwargs,\n precision=self.precision,\n encode_kwargs=self.encode_kwargs,\n backend=self.backend,\n )\n if serialization_dict[\"init_parameters\"].get(\"model_kwargs\") is not None:\n serialize_hf_model_kwargs(serialization_dict[\"init_parameters\"][\"model_kwargs\"])\n return serialization_dict"}], "type": ["function_empty"], "node": ["haystack.utils.device.ComponentDevice.to_dict", "haystack.components.embedders.sentence_transformers_document_embedder.SentenceTransformersDocumentEmbedder.to_dict"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 18, "base_passed_num": 15}} {"id": ["haystack.haystack.utils.device.ComponentDevice::to_dict", "haystack.haystack.components.embedders.sentence_transformers_text_embedder.SentenceTransformersTextEmbedder::to_dict"], "project": "haystack", "origin_file": ["haystack/utils/device.py", "haystack/components/embedders/sentence_transformers_text_embedder.py"], "test_list": ["test/components/embedders/test_sentence_transformers_text_embedder.py"], "prob_info": [{"class_start_lineno": 240, "class_end_lineno": 480, "func_start_lineno": 450, "func_end_lineno": 463, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Convert the component device representation to a JSON-serializable dictionary.\n\n :returns:\n The dictionary representation.\n \"\"\"\n if self._single_device is not None:\n return {\"type\": \"single\", \"device\": str(self._single_device)}\n elif self._multiple_devices is not None:\n return {\"type\": \"multiple\", \"device_map\": self._multiple_devices.to_dict()}\n else:\n # Unreachable\n assert False"}, {"class_start_lineno": 16, "class_end_lineno": 229, "func_start_lineno": 133, "func_end_lineno": 161, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serializes the component to a dictionary.\n\n :returns:\n Dictionary with serialized data.\n \"\"\"\n serialization_dict = default_to_dict(\n self,\n model=self.model,\n device=self.device.to_dict(),\n token=self.token.to_dict() if self.token else None,\n prefix=self.prefix,\n suffix=self.suffix,\n batch_size=self.batch_size,\n progress_bar=self.progress_bar,\n normalize_embeddings=self.normalize_embeddings,\n trust_remote_code=self.trust_remote_code,\n truncate_dim=self.truncate_dim,\n model_kwargs=self.model_kwargs,\n tokenizer_kwargs=self.tokenizer_kwargs,\n config_kwargs=self.config_kwargs,\n precision=self.precision,\n encode_kwargs=self.encode_kwargs,\n backend=self.backend,\n )\n if serialization_dict[\"init_parameters\"].get(\"model_kwargs\") is not None:\n serialize_hf_model_kwargs(serialization_dict[\"init_parameters\"][\"model_kwargs\"])\n return serialization_dict"}], "type": ["function_empty"], "node": ["haystack.utils.device.ComponentDevice.to_dict", "haystack.components.embedders.sentence_transformers_text_embedder.SentenceTransformersTextEmbedder.to_dict"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 19, "base_passed_num": 16}} {"id": ["haystack.haystack.utils.type_serialization.serialize_type", "haystack.haystack.components.evaluators.llm_evaluator.LLMEvaluator::to_dict", "haystack.haystack.core.serialization.component_to_dict", "haystack.haystack.utils.type_serialization.deserialize_type", "haystack.haystack.core.serialization.component_from_dict"], "project": "haystack", "origin_file": ["haystack/utils/type_serialization.py", "haystack/components/evaluators/llm_evaluator.py", "haystack/core/serialization.py", "haystack/utils/type_serialization.py", "haystack/core/serialization.py"], "test_list": ["test/components/evaluators/test_llm_evaluator.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 170, "func_start_lineno": 19, "func_end_lineno": 52, "func_code": "def serialize_type(target: Any) -> str:\n \"\"\"\n Serializes a type or an instance to its string representation, including the module name.\n\n This function handles types, instances of types, and special typing objects.\n It assumes that non-typing objects will have a '__name__' attribute.\n\n :param target:\n The object to serialize, can be an instance or a type.\n :return:\n The string representation of the type.\n \"\"\"\n name = getattr(target, \"__name__\", str(target))\n\n # Remove the 'typing.' prefix when using python <3.9\n if name.startswith(\"typing.\"):\n name = name[7:]\n # Remove the arguments from the name when using python <3.9\n if \"[\" in name:\n name = name.split(\"[\")[0]\n\n # Get module name\n module = inspect.getmodule(target)\n module_name = \"\"\n # We omit the module name for builtins to not clutter the output\n if module and hasattr(module, \"__name__\") and module.__name__ != \"builtins\":\n module_name = f\"{module.__name__}\"\n\n args = get_args(target)\n if args:\n args_str = \", \".join([serialize_type(a) for a in args if a is not type(None)])\n return f\"{module_name}.{name}[{args_str}]\" if module_name else f\"{name}[{args_str}]\"\n\n return f\"{module_name}.{name}\" if module_name else f\"{name}\""}, {"class_start_lineno": 18, "class_end_lineno": 387, "func_start_lineno": 278, "func_end_lineno": 297, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serialize this component to a dictionary.\n\n :returns:\n The serialized component as a dictionary.\n \"\"\"\n # Since we cannot currently serialize tuples, convert the inputs to a list.\n inputs = [[name, serialize_type(type_)] for name, type_ in self.inputs]\n return default_to_dict(\n self,\n instructions=self.instructions,\n inputs=inputs,\n outputs=self.outputs,\n examples=self.examples,\n api=self.api,\n api_key=self.api_key and self.api_key.to_dict(),\n api_params=self.api_params,\n progress_bar=self.progress_bar,\n )"}, {"class_start_lineno": 1, "class_end_lineno": 264, "func_start_lineno": 36, "func_end_lineno": 82, "func_code": "def component_to_dict(obj: Any, name: str) -> Dict[str, Any]:\n \"\"\"\n Converts a component instance into a dictionary.\n\n If a `to_dict` method is present in the component instance, that will be used instead of the default method.\n\n :param obj:\n The component to be serialized.\n :param name:\n The name of the component.\n :returns:\n A dictionary representation of the component.\n\n :raises SerializationError:\n If the component doesn't have a `to_dict` method.\n If the values of the init parameters can't be determined.\n If a non-basic Python type is used in the serialized data.\n \"\"\"\n if hasattr(obj, \"to_dict\"):\n data = obj.to_dict()\n else:\n init_parameters = {}\n for param_name, param in inspect.signature(obj.__init__).parameters.items():\n # Ignore `args` and `kwargs`, used by the default constructor\n if param_name in (\"args\", \"kwargs\"):\n continue\n try:\n # This only works if the Component constructor assigns the init\n # parameter to an instance variable or property with the same name\n param_value = getattr(obj, param_name)\n except AttributeError as e:\n # If the parameter doesn't have a default value, raise an error\n if param.default is param.empty:\n raise SerializationError(\n f\"Cannot determine the value of the init parameter '{param_name}' \"\n f\"for the class {obj.__class__.__name__}.\"\n f\"You can fix this error by assigning 'self.{param_name} = {param_name}' or adding a \"\n f\"custom serialization method 'to_dict' to the class.\"\n ) from e\n # In case the init parameter was not assigned, we use the default value\n param_value = param.default\n init_parameters[param_name] = param_value\n\n data = default_to_dict(obj, **init_parameters)\n\n _validate_component_to_dict_output(obj, name, data)\n return data"}, {"class_start_lineno": 1, "class_end_lineno": 170, "func_start_lineno": 78, "func_end_lineno": 156, "func_code": "def deserialize_type(type_str: str) -> Any: # pylint: disable=too-many-return-statements\n \"\"\"\n Deserializes a type given its full import path as a string, including nested generic types.\n\n This function will dynamically import the module if it's not already imported\n and then retrieve the type object from it. It also handles nested generic types like\n `typing.List[typing.Dict[int, str]]`.\n\n :param type_str:\n The string representation of the type's full import path.\n :returns:\n The deserialized type object.\n :raises DeserializationError:\n If the type cannot be deserialized due to missing module or type.\n \"\"\"\n\n type_mapping = {\n list: typing.List,\n dict: typing.Dict,\n set: typing.Set,\n tuple: typing.Tuple,\n frozenset: typing.FrozenSet,\n }\n\n # Handle generics\n if \"[\" in type_str and type_str.endswith(\"]\"):\n main_type_str, generics_str = type_str.split(\"[\", 1)\n generics_str = generics_str[:-1]\n\n main_type = deserialize_type(main_type_str)\n generic_args = [deserialize_type(arg) for arg in _parse_generic_args(generics_str)]\n\n # Reconstruct\n try:\n if sys.version_info >= (3, 9) or repr(main_type).startswith(\"typing.\"):\n return main_type[tuple(generic_args) if len(generic_args) > 1 else generic_args[0]]\n else:\n return type_mapping[main_type][tuple(generic_args) if len(generic_args) > 1 else generic_args[0]]\n except (TypeError, AttributeError) as e:\n raise DeserializationError(f\"Could not apply arguments {generic_args} to type {main_type}\") from e\n\n # Handle non-generic types\n # First, check if there's a module prefix\n if \".\" in type_str:\n parts = type_str.split(\".\")\n module_name = \".\".join(parts[:-1])\n type_name = parts[-1]\n\n module = sys.modules.get(module_name)\n if module is None:\n try:\n module = thread_safe_import(module_name)\n except ImportError as e:\n raise DeserializationError(f\"Could not import the module: {module_name}\") from e\n\n # Get the class from the module\n if hasattr(module, type_name):\n return getattr(module, type_name)\n\n raise DeserializationError(f\"Could not locate the type: {type_name} in the module: {module_name}\")\n\n # No module prefix, check builtins and typing\n # First check builtins\n if hasattr(builtins, type_str):\n return getattr(builtins, type_str)\n\n # Then check typing\n if hasattr(typing, type_str):\n return getattr(typing, type_str)\n\n # Special case for NoneType\n if type_str == \"NoneType\":\n return type(None)\n\n # Special case for None\n if type_str == \"None\":\n return None\n\n raise DeserializationError(f\"Could not deserialize type: {type_str}\")"}, {"class_start_lineno": 1, "class_end_lineno": 264, "func_start_lineno": 134, "func_end_lineno": 169, "func_code": "def component_from_dict(\n cls: Type[object], data: Dict[str, Any], name: str, callbacks: Optional[DeserializationCallbacks] = None\n) -> Any:\n \"\"\"\n Creates a component instance from a dictionary.\n\n If a `from_dict` method is present in the component class, that will be used instead of the default method.\n\n :param cls:\n The class to be used for deserialization.\n :param data:\n The serialized data.\n :param name:\n The name of the component.\n :param callbacks:\n Callbacks to invoke during deserialization.\n :returns:\n The deserialized component.\n \"\"\"\n\n def component_pre_init_callback(component_cls, init_params):\n assert callbacks is not None\n assert callbacks.component_pre_init is not None\n callbacks.component_pre_init(name, component_cls, init_params)\n\n def do_from_dict():\n if hasattr(cls, \"from_dict\"):\n return cls.from_dict(data)\n\n return default_from_dict(cls, data)\n\n if callbacks is None or callbacks.component_pre_init is None:\n return do_from_dict()\n\n with _hook_component_init(component_pre_init_callback):\n return do_from_dict()"}], "type": ["function_empty"], "node": ["haystack.utils.type_serialization.serialize_type", "haystack.components.evaluators.llm_evaluator.LLMEvaluator.to_dict", "haystack.core.serialization.component_to_dict", "haystack.utils.type_serialization.deserialize_type", "haystack.core.serialization.component_from_dict"], "language": "Python", "toolfunc_count": 5, "func_count": 5, "pytest_info": {"total_num": 17, "base_passed_num": 13}} {"id": ["haystack.haystack.utils.device.ComponentDevice::to_dict", "haystack.haystack.components.evaluators.sas_evaluator.SASEvaluator::to_dict"], "project": "haystack", "origin_file": ["haystack/utils/device.py", "haystack/components/evaluators/sas_evaluator.py"], "test_list": ["test/components/evaluators/test_sas_evaluator.py"], "prob_info": [{"class_start_lineno": 240, "class_end_lineno": 480, "func_start_lineno": 450, "func_end_lineno": 463, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Convert the component device representation to a JSON-serializable dictionary.\n\n :returns:\n The dictionary representation.\n \"\"\"\n if self._single_device is not None:\n return {\"type\": \"single\", \"device\": str(self._single_device)}\n elif self._multiple_devices is not None:\n return {\"type\": \"multiple\", \"device_map\": self._multiple_devices.to_dict()}\n else:\n # Unreachable\n assert False"}, {"class_start_lineno": 20, "class_end_lineno": 201, "func_start_lineno": 85, "func_end_lineno": 98, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serialize this component to a dictionary.\n\n :returns:\n The serialized component as a dictionary.\n \"\"\"\n return default_to_dict(\n self,\n model=self._model,\n batch_size=self._batch_size,\n device=self._device.to_dict() if self._device else None,\n token=self._token.to_dict() if self._token else None,\n )"}], "type": ["function_empty"], "node": ["haystack.utils.device.ComponentDevice.to_dict", "haystack.components.evaluators.sas_evaluator.SASEvaluator.to_dict"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 12, "base_passed_num": 11}} {"id": ["haystack.haystack.components.generators.chat.openai.OpenAIChatGenerator::to_dict", "haystack.haystack.components.extractors.llm_metadata_extractor.LLMMetadataExtractor::to_dict", "haystack.haystack.components.builders.prompt_builder.PromptBuilder::_validate_variables", "haystack.haystack.components.builders.prompt_builder.PromptBuilder::run"], "project": "haystack", "origin_file": ["haystack/components/generators/chat/openai.py", "haystack/components/extractors/llm_metadata_extractor.py", "haystack/components/builders/prompt_builder.py", "haystack/components/builders/prompt_builder.py", "haystack/components/extractors/llm_metadata_extractor.py"], "test_list": ["test/components/extractors/test_llm_metadata_extractor.py"], "prob_info": [{"class_start_lineno": 32, "class_end_lineno": 571, "func_start_lineno": 170, "func_end_lineno": 190, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serialize this component to a dictionary.\n\n :returns:\n The serialized component as a dictionary.\n \"\"\"\n callback_name = serialize_callable(self.streaming_callback) if self.streaming_callback else None\n return default_to_dict(\n self,\n model=self.model,\n streaming_callback=callback_name,\n api_base_url=self.api_base_url,\n organization=self.organization,\n generation_kwargs=self.generation_kwargs,\n api_key=self.api_key.to_dict(),\n timeout=self.timeout,\n max_retries=self.max_retries,\n tools=[tool.to_dict() for tool in self.tools] if self.tools else None,\n tools_strict=self.tools_strict,\n )"}, {"class_start_lineno": 61, "class_end_lineno": 442, "func_start_lineno": 239, "func_end_lineno": 258, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serializes the component to a dictionary.\n\n :returns:\n Dictionary with serialized data.\n \"\"\"\n\n llm_provider = self.llm_provider.to_dict()\n\n return default_to_dict(\n self,\n prompt=self.prompt,\n generator_api=self.generator_api.value,\n generator_api_params=llm_provider[\"init_parameters\"],\n expected_keys=self.expected_keys,\n page_range=self.expanded_range,\n raise_on_failure=self.raise_on_failure,\n max_workers=self.max_workers,\n )"}, {"class_start_lineno": 17, "class_end_lineno": 266, "func_start_lineno": 247, "func_end_lineno": 266, "func_code": " def _validate_variables(self, provided_variables: Set[str]):\n \"\"\"\n Checks if all the required template variables are provided.\n\n :param provided_variables:\n A set of provided template variables.\n :raises ValueError:\n If any of the required template variables is not provided.\n \"\"\"\n if self.required_variables == \"*\":\n required_variables = sorted(self.variables)\n else:\n required_variables = self.required_variables\n missing_variables = [var for var in required_variables if var not in provided_variables]\n if missing_variables:\n missing_vars_str = \", \".join(missing_variables)\n raise ValueError(\n f\"Missing required input variables in PromptBuilder: {missing_vars_str}. \"\n f\"Required variables: {required_variables}. Provided variables: {provided_variables}.\"\n )"}, {"class_start_lineno": 17, "class_end_lineno": 266, "func_start_lineno": 213, "func_end_lineno": 245, "func_code": " def run(self, template: Optional[str] = None, template_variables: Optional[Dict[str, Any]] = None, **kwargs):\n \"\"\"\n Renders the prompt template with the provided variables.\n\n It applies the template variables to render the final prompt. You can provide variables via pipeline kwargs.\n In order to overwrite the default template, you can set the `template` parameter.\n In order to overwrite pipeline kwargs, you can set the `template_variables` parameter.\n\n :param template:\n An optional string template to overwrite PromptBuilder's default template. If None, the default template\n provided at initialization is used.\n :param template_variables:\n An optional dictionary of template variables to overwrite the pipeline variables.\n :param kwargs:\n Pipeline variables used for rendering the prompt.\n\n :returns: A dictionary with the following keys:\n - `prompt`: The updated prompt text after rendering the prompt template.\n\n :raises ValueError:\n If any of the required template variables is not provided.\n \"\"\"\n kwargs = kwargs or {}\n template_variables = template_variables or {}\n template_variables_combined = {**kwargs, **template_variables}\n self._validate_variables(set(template_variables_combined.keys()))\n\n compiled_template = self.template\n if template is not None:\n compiled_template = self._env.from_string(template)\n\n result = compiled_template.render(template_variables_combined)\n return {\"prompt\": result}"}, {"class_start_lineno": 61, "class_end_lineno": 442, "func_start_lineno": 332, "func_end_lineno": 359, "func_code": " def _prepare_prompts(\n self, documents: List[Document], expanded_range: Optional[List[int]] = None\n ) -> List[Union[ChatMessage, None]]:\n all_prompts: List[Union[ChatMessage, None]] = []\n for document in documents:\n if not document.content:\n logger.warning(\"Document {doc_id} has no content. Skipping metadata extraction.\", doc_id=document.id)\n all_prompts.append(None)\n continue\n\n if expanded_range:\n doc_copy = copy.deepcopy(document)\n pages = self.splitter.run(documents=[doc_copy])\n content = \"\"\n for idx, page in enumerate(pages[\"documents\"]):\n if idx + 1 in expanded_range:\n content += page.content\n doc_copy.content = content\n else:\n doc_copy = document\n\n prompt_with_doc = self.builder.run(template=self.prompt, template_variables={\"document\": doc_copy})\n\n # build a ChatMessage with the prompt\n message = ChatMessage.from_user(prompt_with_doc[\"prompt\"])\n all_prompts.append(message)\n\n return all_prompts"}], "type": ["function_empty"], "node": ["haystack.components.generators.chat.openai.OpenAIChatGenerator.to_dict", "haystack.components.extractors.llm_metadata_extractor.LLMMetadataExtractor.to_dict", "haystack.components.builders.prompt_builder.PromptBuilder._validate_variables", "haystack.components.builders.prompt_builder.PromptBuilder.run", "haystack.components.extractors.llm_metadata_extractor.LLMMetadataExtractor._prepare_prompts"], "language": "Python", "toolfunc_count": 4, "func_count": 4, "pytest_info": {"total_num": 13, "base_passed_num": 9}} {"id": ["haystack.haystack.components.extractors.named_entity_extractor.NamedEntityExtractor::to_dict", "haystack.haystack.core.serialization.component_to_dict"], "project": "haystack", "origin_file": ["haystack/components/extractors/named_entity_extractor.py", "haystack/core/serialization.py"], "test_list": ["test/components/extractors/test_named_entity_extractor.py"], "prob_info": [{"class_start_lineno": 78, "class_end_lineno": 275, "func_start_lineno": 212, "func_end_lineno": 232, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serializes the component to a dictionary.\n\n :returns:\n Dictionary with serialized data.\n \"\"\"\n serialization_dict = default_to_dict(\n self,\n backend=self._backend.type.name,\n model=self._backend.model_name,\n device=self._backend.device.to_dict(),\n pipeline_kwargs=self._backend._pipeline_kwargs,\n token=self.token.to_dict() if self.token else None,\n )\n\n hf_pipeline_kwargs = serialization_dict[\"init_parameters\"][\"pipeline_kwargs\"]\n hf_pipeline_kwargs.pop(\"token\", None)\n\n serialize_hf_model_kwargs(hf_pipeline_kwargs)\n return serialization_dict"}, {"class_start_lineno": 1, "class_end_lineno": 264, "func_start_lineno": 36, "func_end_lineno": 82, "func_code": "def component_to_dict(obj: Any, name: str) -> Dict[str, Any]:\n \"\"\"\n Converts a component instance into a dictionary.\n\n If a `to_dict` method is present in the component instance, that will be used instead of the default method.\n\n :param obj:\n The component to be serialized.\n :param name:\n The name of the component.\n :returns:\n A dictionary representation of the component.\n\n :raises SerializationError:\n If the component doesn't have a `to_dict` method.\n If the values of the init parameters can't be determined.\n If a non-basic Python type is used in the serialized data.\n \"\"\"\n if hasattr(obj, \"to_dict\"):\n data = obj.to_dict()\n else:\n init_parameters = {}\n for param_name, param in inspect.signature(obj.__init__).parameters.items():\n # Ignore `args` and `kwargs`, used by the default constructor\n if param_name in (\"args\", \"kwargs\"):\n continue\n try:\n # This only works if the Component constructor assigns the init\n # parameter to an instance variable or property with the same name\n param_value = getattr(obj, param_name)\n except AttributeError as e:\n # If the parameter doesn't have a default value, raise an error\n if param.default is param.empty:\n raise SerializationError(\n f\"Cannot determine the value of the init parameter '{param_name}' \"\n f\"for the class {obj.__class__.__name__}.\"\n f\"You can fix this error by assigning 'self.{param_name} = {param_name}' or adding a \"\n f\"custom serialization method 'to_dict' to the class.\"\n ) from e\n # In case the init parameter was not assigned, we use the default value\n param_value = param.default\n init_parameters[param_name] = param_value\n\n data = default_to_dict(obj, **init_parameters)\n\n _validate_component_to_dict_output(obj, name, data)\n return data"}], "type": ["function_empty", "TDD"], "node": ["haystack.components.extractors.named_entity_extractor.NamedEntityExtractor.to_dict", "haystack.core.serialization.component_to_dict"], "language": "Python", "toolfunc_count": 1, "func_count": 2, "pytest_info": {"total_num": 7, "base_passed_num": 2}} {"id": ["haystack.haystack.utils.callable_serialization.serialize_callable", "haystack.haystack.components.generators.azure.AzureOpenAIGenerator::to_dict", "haystack.haystack.core.serialization.component_to_dict"], "project": "haystack", "origin_file": ["haystack/utils/callable_serialization.py", "haystack/components/generators/azure.py", "haystack/core/serialization.py"], "test_list": ["test/components/generators/test_azure.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 80, "func_start_lineno": 12, "func_end_lineno": 42, "func_code": "def serialize_callable(callable_handle: Callable) -> str:\n \"\"\"\n Serializes a callable to its full path.\n\n :param callable_handle: The callable to serialize\n :return: The full path of the callable\n \"\"\"\n try:\n full_arg_spec = inspect.getfullargspec(callable_handle)\n is_instance_method = bool(full_arg_spec.args and full_arg_spec.args[0] == \"self\")\n except TypeError:\n is_instance_method = False\n if is_instance_method:\n raise SerializationError(\"Serialization of instance methods is not supported.\")\n\n # __qualname__ contains the fully qualified path we need for classmethods and staticmethods\n qualname = getattr(callable_handle, \"__qualname__\", \"\")\n if \"\" in qualname:\n raise SerializationError(\"Serialization of lambdas is not supported.\")\n if \"\" in qualname:\n raise SerializationError(\"Serialization of nested functions is not supported.\")\n\n name = qualname or callable_handle.__name__\n\n # Get the full package path of the function\n module = inspect.getmodule(callable_handle)\n if module is not None:\n full_path = f\"{module.__name__}.{name}\"\n else:\n full_path = name\n return full_path"}, {"class_start_lineno": 19, "class_end_lineno": 210, "func_start_lineno": 162, "func_end_lineno": 188, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serialize this component to a dictionary.\n\n :returns:\n The serialized component as a dictionary.\n \"\"\"\n callback_name = serialize_callable(self.streaming_callback) if self.streaming_callback else None\n azure_ad_token_provider_name = None\n if self.azure_ad_token_provider:\n azure_ad_token_provider_name = serialize_callable(self.azure_ad_token_provider)\n return default_to_dict(\n self,\n azure_endpoint=self.azure_endpoint,\n azure_deployment=self.azure_deployment,\n organization=self.organization,\n api_version=self.api_version,\n streaming_callback=callback_name,\n generation_kwargs=self.generation_kwargs,\n system_prompt=self.system_prompt,\n api_key=self.api_key.to_dict() if self.api_key is not None else None,\n azure_ad_token=self.azure_ad_token.to_dict() if self.azure_ad_token is not None else None,\n timeout=self.timeout,\n max_retries=self.max_retries,\n default_headers=self.default_headers,\n azure_ad_token_provider=azure_ad_token_provider_name,\n )"}, {"class_start_lineno": 1, "class_end_lineno": 264, "func_start_lineno": 36, "func_end_lineno": 82, "func_code": "def component_to_dict(obj: Any, name: str) -> Dict[str, Any]:\n \"\"\"\n Converts a component instance into a dictionary.\n\n If a `to_dict` method is present in the component instance, that will be used instead of the default method.\n\n :param obj:\n The component to be serialized.\n :param name:\n The name of the component.\n :returns:\n A dictionary representation of the component.\n\n :raises SerializationError:\n If the component doesn't have a `to_dict` method.\n If the values of the init parameters can't be determined.\n If a non-basic Python type is used in the serialized data.\n \"\"\"\n if hasattr(obj, \"to_dict\"):\n data = obj.to_dict()\n else:\n init_parameters = {}\n for param_name, param in inspect.signature(obj.__init__).parameters.items():\n # Ignore `args` and `kwargs`, used by the default constructor\n if param_name in (\"args\", \"kwargs\"):\n continue\n try:\n # This only works if the Component constructor assigns the init\n # parameter to an instance variable or property with the same name\n param_value = getattr(obj, param_name)\n except AttributeError as e:\n # If the parameter doesn't have a default value, raise an error\n if param.default is param.empty:\n raise SerializationError(\n f\"Cannot determine the value of the init parameter '{param_name}' \"\n f\"for the class {obj.__class__.__name__}.\"\n f\"You can fix this error by assigning 'self.{param_name} = {param_name}' or adding a \"\n f\"custom serialization method 'to_dict' to the class.\"\n ) from e\n # In case the init parameter was not assigned, we use the default value\n param_value = param.default\n init_parameters[param_name] = param_value\n\n data = default_to_dict(obj, **init_parameters)\n\n _validate_component_to_dict_output(obj, name, data)\n return data"}], "type": ["function_empty"], "node": ["haystack.utils.callable_serialization.serialize_callable", "haystack.components.generators.azure.AzureOpenAIGenerator.to_dict", "haystack.core.serialization.component_to_dict"], "language": "Python", "toolfunc_count": 3, "func_count": 3, "pytest_info": {"total_num": 7, "base_passed_num": 4}} {"id": ["haystack.haystack.utils.callable_serialization.serialize_callable", "haystack.haystack.components.generators.openai.OpenAIGenerator::to_dict", "haystack.haystack.utils.type_serialization.thread_safe_import", "haystack.haystack.utils.callable_serialization.deserialize_callable"], "project": "haystack", "origin_file": ["haystack/utils/callable_serialization.py", "haystack/components/generators/openai.py", "haystack/utils/type_serialization.py", "haystack/utils/callable_serialization.py"], "test_list": ["test/components/generators/test_openai.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 80, "func_start_lineno": 12, "func_end_lineno": 42, "func_code": "def serialize_callable(callable_handle: Callable) -> str:\n \"\"\"\n Serializes a callable to its full path.\n\n :param callable_handle: The callable to serialize\n :return: The full path of the callable\n \"\"\"\n try:\n full_arg_spec = inspect.getfullargspec(callable_handle)\n is_instance_method = bool(full_arg_spec.args and full_arg_spec.args[0] == \"self\")\n except TypeError:\n is_instance_method = False\n if is_instance_method:\n raise SerializationError(\"Serialization of instance methods is not supported.\")\n\n # __qualname__ contains the fully qualified path we need for classmethods and staticmethods\n qualname = getattr(callable_handle, \"__qualname__\", \"\")\n if \"\" in qualname:\n raise SerializationError(\"Serialization of lambdas is not supported.\")\n if \"\" in qualname:\n raise SerializationError(\"Serialization of nested functions is not supported.\")\n\n name = qualname or callable_handle.__name__\n\n # Get the full package path of the function\n module = inspect.getmodule(callable_handle)\n if module is not None:\n full_path = f\"{module.__name__}.{name}\"\n else:\n full_path = name\n return full_path"}, {"class_start_lineno": 20, "class_end_lineno": 335, "func_start_lineno": 133, "func_end_lineno": 150, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serialize this component to a dictionary.\n\n :returns:\n The serialized component as a dictionary.\n \"\"\"\n callback_name = serialize_callable(self.streaming_callback) if self.streaming_callback else None\n return default_to_dict(\n self,\n model=self.model,\n streaming_callback=callback_name,\n api_base_url=self.api_base_url,\n organization=self.organization,\n generation_kwargs=self.generation_kwargs,\n system_prompt=self.system_prompt,\n api_key=self.api_key.to_dict(),\n )"}, {"class_start_lineno": 1, "class_end_lineno": 170, "func_start_lineno": 159, "func_end_lineno": 170, "func_code": "def thread_safe_import(module_name: str) -> ModuleType:\n \"\"\"\n Import a module in a thread-safe manner.\n\n Importing modules in a multi-threaded environment can lead to race conditions.\n This function ensures that the module is imported in a thread-safe manner without having impact\n on the performance of the import for single-threaded environments.\n\n :param module_name: the module to import\n \"\"\"\n with _import_lock:\n return importlib.import_module(module_name)"}, {"class_start_lineno": 1, "class_end_lineno": 80, "func_start_lineno": 45, "func_end_lineno": 80, "func_code": "def deserialize_callable(callable_handle: str) -> Callable:\n \"\"\"\n Deserializes a callable given its full import path as a string.\n\n :param callable_handle: The full path of the callable_handle\n :return: The callable\n :raises DeserializationError: If the callable cannot be found\n \"\"\"\n parts = callable_handle.split(\".\")\n\n for i in range(len(parts), 0, -1):\n module_name = \".\".join(parts[:i])\n try:\n mod: Any = thread_safe_import(module_name)\n except Exception:\n # keep reducing i until we find a valid module import\n continue\n\n attr_value = mod\n for part in parts[i:]:\n try:\n attr_value = getattr(attr_value, part)\n except AttributeError as e:\n raise DeserializationError(f\"Could not find attribute '{part}' in {attr_value.__name__}\") from e\n\n # when the attribute is a classmethod, we need the underlying function\n if isinstance(attr_value, (classmethod, staticmethod)):\n attr_value = attr_value.__func__\n\n if not callable(attr_value):\n raise DeserializationError(f\"The final attribute is not callable: {attr_value}\")\n\n return attr_value\n\n # Fallback if we never find anything\n raise DeserializationError(f\"Could not import '{callable_handle}' as a module or callable.\")"}], "type": ["function_empty", "TDD"], "node": ["haystack.utils.callable_serialization.serialize_callable", "haystack.components.generators.openai.OpenAIGenerator.to_dict", "haystack.utils.type_serialization.thread_safe_import", "haystack.utils.callable_serialization.deserialize_callable"], "language": "Python", "toolfunc_count": 3, "func_count": 4, "pytest_info": {"total_num": 12, "base_passed_num": 9}} {"id": ["haystack.haystack.utils.callable_serialization.serialize_callable", "haystack.haystack.components.generators.chat.azure.AzureOpenAIChatGenerator::to_dict", "haystack.haystack.core.serialization.import_class_by_name", "haystack.haystack.tools.tool.deserialize_tools_inplace"], "project": "haystack", "origin_file": ["haystack/utils/callable_serialization.py", "haystack/components/generators/chat/azure.py", "haystack/core/serialization.py", "haystack/tools/tool.py"], "test_list": ["test/components/generators/chat/test_azure.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 80, "func_start_lineno": 12, "func_end_lineno": 42, "func_code": "def serialize_callable(callable_handle: Callable) -> str:\n \"\"\"\n Serializes a callable to its full path.\n\n :param callable_handle: The callable to serialize\n :return: The full path of the callable\n \"\"\"\n try:\n full_arg_spec = inspect.getfullargspec(callable_handle)\n is_instance_method = bool(full_arg_spec.args and full_arg_spec.args[0] == \"self\")\n except TypeError:\n is_instance_method = False\n if is_instance_method:\n raise SerializationError(\"Serialization of instance methods is not supported.\")\n\n # __qualname__ contains the fully qualified path we need for classmethods and staticmethods\n qualname = getattr(callable_handle, \"__qualname__\", \"\")\n if \"\" in qualname:\n raise SerializationError(\"Serialization of lambdas is not supported.\")\n if \"\" in qualname:\n raise SerializationError(\"Serialization of nested functions is not supported.\")\n\n name = qualname or callable_handle.__name__\n\n # Get the full package path of the function\n module = inspect.getmodule(callable_handle)\n if module is not None:\n full_path = f\"{module.__name__}.{name}\"\n else:\n full_path = name\n return full_path"}, {"class_start_lineno": 20, "class_end_lineno": 226, "func_start_lineno": 177, "func_end_lineno": 204, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serialize this component to a dictionary.\n\n :returns:\n The serialized component as a dictionary.\n \"\"\"\n callback_name = serialize_callable(self.streaming_callback) if self.streaming_callback else None\n azure_ad_token_provider_name = None\n if self.azure_ad_token_provider:\n azure_ad_token_provider_name = serialize_callable(self.azure_ad_token_provider)\n return default_to_dict(\n self,\n azure_endpoint=self.azure_endpoint,\n azure_deployment=self.azure_deployment,\n organization=self.organization,\n api_version=self.api_version,\n streaming_callback=callback_name,\n generation_kwargs=self.generation_kwargs,\n timeout=self.timeout,\n max_retries=self.max_retries,\n api_key=self.api_key.to_dict() if self.api_key is not None else None,\n azure_ad_token=self.azure_ad_token.to_dict() if self.azure_ad_token is not None else None,\n default_headers=self.default_headers,\n tools=[tool.to_dict() for tool in self.tools] if self.tools else None,\n tools_strict=self.tools_strict,\n azure_ad_token_provider=azure_ad_token_provider_name,\n )"}, {"class_start_lineno": 1, "class_end_lineno": 264, "func_start_lineno": 243, "func_end_lineno": 264, "func_code": "def import_class_by_name(fully_qualified_name: str) -> Type[object]:\n \"\"\"\n Utility function to import (load) a class object based on its fully qualified class name.\n\n This function dynamically imports a class based on its string name.\n It splits the name into module path and class name, imports the module,\n and returns the class object.\n\n :param fully_qualified_name: the fully qualified class name as a string\n :returns: the class object.\n :raises ImportError: If the class cannot be imported or found.\n \"\"\"\n try:\n module_path, class_name = fully_qualified_name.rsplit(\".\", 1)\n logger.debug(\n \"Attempting to import class '{cls_name}' from module '{md_path}'\", cls_name=class_name, md_path=module_path\n )\n module = thread_safe_import(module_path)\n return getattr(module, class_name)\n except (ImportError, AttributeError) as error:\n logger.error(\"Failed to import class '{full_name}'\", full_name=fully_qualified_name)\n raise ImportError(f\"Could not import class '{fully_qualified_name}'\") from error"}, {"class_start_lineno": 1, "class_end_lineno": 136, "func_start_lineno": 106, "func_end_lineno": 136, "func_code": "def deserialize_tools_inplace(data: Dict[str, Any], key: str = \"tools\"):\n \"\"\"\n Deserialize Tools in a dictionary inplace.\n\n :param data:\n The dictionary with the serialized data.\n :param key:\n The key in the dictionary where the Tools are stored.\n \"\"\"\n if key in data:\n serialized_tools = data[key]\n\n if serialized_tools is None:\n return\n\n if not isinstance(serialized_tools, list):\n raise TypeError(f\"The value of '{key}' is not a list\")\n\n deserialized_tools = []\n for tool in serialized_tools:\n if not isinstance(tool, dict):\n raise TypeError(f\"Serialized tool '{tool}' is not a dictionary\")\n\n # different classes are allowed: Tool, ComponentTool, etc.\n tool_class = import_class_by_name(tool[\"type\"])\n if not issubclass(tool_class, Tool):\n raise TypeError(f\"Class '{tool_class}' is not a subclass of Tool\")\n\n deserialized_tools.append(tool_class.from_dict(tool))\n\n data[key] = deserialized_tools"}], "type": ["function_empty"], "node": ["haystack.utils.callable_serialization.serialize_callable", "haystack.components.generators.chat.azure.AzureOpenAIChatGenerator.to_dict", "haystack.core.serialization.import_class_by_name", "haystack.tools.tool.deserialize_tools_inplace"], "language": "Python", "toolfunc_count": 4, "func_count": 4, "pytest_info": {"total_num": 8, "base_passed_num": 4}} {"id": ["haystack.haystack.utils.callable_serialization.serialize_callable", "haystack.haystack.components.generators.chat.openai.OpenAIChatGenerator::to_dict", "haystack.haystack.core.serialization.import_class_by_name", "haystack.haystack.tools.tool.deserialize_tools_inplace"], "project": "haystack", "origin_file": ["haystack/utils/callable_serialization.py", "haystack/components/generators/chat/openai.py", "haystack/core/serialization.py", "haystack/tools/tool.py"], "test_list": ["test/components/generators/chat/test_openai.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 80, "func_start_lineno": 12, "func_end_lineno": 42, "func_code": "def serialize_callable(callable_handle: Callable) -> str:\n \"\"\"\n Serializes a callable to its full path.\n\n :param callable_handle: The callable to serialize\n :return: The full path of the callable\n \"\"\"\n try:\n full_arg_spec = inspect.getfullargspec(callable_handle)\n is_instance_method = bool(full_arg_spec.args and full_arg_spec.args[0] == \"self\")\n except TypeError:\n is_instance_method = False\n if is_instance_method:\n raise SerializationError(\"Serialization of instance methods is not supported.\")\n\n # __qualname__ contains the fully qualified path we need for classmethods and staticmethods\n qualname = getattr(callable_handle, \"__qualname__\", \"\")\n if \"\" in qualname:\n raise SerializationError(\"Serialization of lambdas is not supported.\")\n if \"\" in qualname:\n raise SerializationError(\"Serialization of nested functions is not supported.\")\n\n name = qualname or callable_handle.__name__\n\n # Get the full package path of the function\n module = inspect.getmodule(callable_handle)\n if module is not None:\n full_path = f\"{module.__name__}.{name}\"\n else:\n full_path = name\n return full_path"}, {"class_start_lineno": 32, "class_end_lineno": 571, "func_start_lineno": 170, "func_end_lineno": 190, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serialize this component to a dictionary.\n\n :returns:\n The serialized component as a dictionary.\n \"\"\"\n callback_name = serialize_callable(self.streaming_callback) if self.streaming_callback else None\n return default_to_dict(\n self,\n model=self.model,\n streaming_callback=callback_name,\n api_base_url=self.api_base_url,\n organization=self.organization,\n generation_kwargs=self.generation_kwargs,\n api_key=self.api_key.to_dict(),\n timeout=self.timeout,\n max_retries=self.max_retries,\n tools=[tool.to_dict() for tool in self.tools] if self.tools else None,\n tools_strict=self.tools_strict,\n )"}, {"class_start_lineno": 1, "class_end_lineno": 264, "func_start_lineno": 243, "func_end_lineno": 264, "func_code": "def import_class_by_name(fully_qualified_name: str) -> Type[object]:\n \"\"\"\n Utility function to import (load) a class object based on its fully qualified class name.\n\n This function dynamically imports a class based on its string name.\n It splits the name into module path and class name, imports the module,\n and returns the class object.\n\n :param fully_qualified_name: the fully qualified class name as a string\n :returns: the class object.\n :raises ImportError: If the class cannot be imported or found.\n \"\"\"\n try:\n module_path, class_name = fully_qualified_name.rsplit(\".\", 1)\n logger.debug(\n \"Attempting to import class '{cls_name}' from module '{md_path}'\", cls_name=class_name, md_path=module_path\n )\n module = thread_safe_import(module_path)\n return getattr(module, class_name)\n except (ImportError, AttributeError) as error:\n logger.error(\"Failed to import class '{full_name}'\", full_name=fully_qualified_name)\n raise ImportError(f\"Could not import class '{fully_qualified_name}'\") from error"}, {"class_start_lineno": 1, "class_end_lineno": 136, "func_start_lineno": 106, "func_end_lineno": 136, "func_code": "def deserialize_tools_inplace(data: Dict[str, Any], key: str = \"tools\"):\n \"\"\"\n Deserialize Tools in a dictionary inplace.\n\n :param data:\n The dictionary with the serialized data.\n :param key:\n The key in the dictionary where the Tools are stored.\n \"\"\"\n if key in data:\n serialized_tools = data[key]\n\n if serialized_tools is None:\n return\n\n if not isinstance(serialized_tools, list):\n raise TypeError(f\"The value of '{key}' is not a list\")\n\n deserialized_tools = []\n for tool in serialized_tools:\n if not isinstance(tool, dict):\n raise TypeError(f\"Serialized tool '{tool}' is not a dictionary\")\n\n # different classes are allowed: Tool, ComponentTool, etc.\n tool_class = import_class_by_name(tool[\"type\"])\n if not issubclass(tool_class, Tool):\n raise TypeError(f\"Class '{tool_class}' is not a subclass of Tool\")\n\n deserialized_tools.append(tool_class.from_dict(tool))\n\n data[key] = deserialized_tools"}], "type": ["function_empty"], "node": ["haystack.utils.callable_serialization.serialize_callable", "haystack.components.generators.chat.openai.OpenAIChatGenerator.to_dict", "haystack.core.serialization.import_class_by_name", "haystack.tools.tool.deserialize_tools_inplace"], "language": "Python", "toolfunc_count": 4, "func_count": 4, "pytest_info": {"total_num": 19, "base_passed_num": 16}} {"id": ["haystack.haystack.components.joiners.document_joiner.DocumentJoiner::_reciprocal_rank_fusion", "haystack.haystack.components.joiners.document_joiner.DocumentJoiner::run"], "project": "haystack", "origin_file": ["haystack/components/joiners/document_joiner.py", "haystack/components/joiners/document_joiner.py"], "test_list": ["test/components/joiners/test_document_joiner.py"], "prob_info": [{"class_start_lineno": 44, "class_end_lineno": 290, "func_start_lineno": 201, "func_end_lineno": 232, "func_code": " def _reciprocal_rank_fusion(self, document_lists: List[List[Document]]) -> List[Document]:\n \"\"\"\n Merge multiple lists of Documents and assign scores based on reciprocal rank fusion.\n\n The constant k is set to 61 (60 was suggested by the original paper,\n plus 1 as python lists are 0-based and the paper used 1-based ranking).\n \"\"\"\n # This check prevents a division by zero when no documents are passed\n if not document_lists:\n return []\n\n k = 61\n\n scores_map: dict = defaultdict(int)\n documents_map = {}\n weights = self.weights if self.weights else [1 / len(document_lists)] * len(document_lists)\n\n # Calculate weighted reciprocal rank fusion score\n for documents, weight in zip(document_lists, weights):\n for rank, doc in enumerate(documents):\n scores_map[doc.id] += (weight * len(document_lists)) / (k + rank)\n documents_map[doc.id] = doc\n\n # Normalize scores. Note: len(results) / k is the maximum possible score,\n # achieved by being ranked first in all doc lists with non-zero weight.\n for _id in scores_map:\n scores_map[_id] /= len(document_lists) / k\n\n for doc in documents_map.values():\n doc.score = scores_map[doc.id]\n\n return list(documents_map.values())"}, {"class_start_lineno": 44, "class_end_lineno": 290, "func_start_lineno": 130, "func_end_lineno": 163, "func_code": " def run(self, documents: Variadic[List[Document]], top_k: Optional[int] = None):\n \"\"\"\n Joins multiple lists of Documents into a single list depending on the `join_mode` parameter.\n\n :param documents:\n List of list of documents to be merged.\n :param top_k:\n The maximum number of documents to return. Overrides the instance's `top_k` if provided.\n\n :returns:\n A dictionary with the following keys:\n - `documents`: Merged list of Documents\n \"\"\"\n output_documents = []\n\n documents = list(documents)\n output_documents = self.join_mode_function(documents)\n\n if self.sort_by_score:\n output_documents = sorted(\n output_documents, key=lambda doc: doc.score if doc.score is not None else -inf, reverse=True\n )\n if any(doc.score is None for doc in output_documents):\n logger.info(\n \"Some of the Documents DocumentJoiner got have score=None. It was configured to sort Documents by \"\n \"score, so those with score=None were sorted as if they had a score of -infinity.\"\n )\n\n if top_k:\n output_documents = output_documents[:top_k]\n elif self.top_k:\n output_documents = output_documents[: self.top_k]\n\n return {\"documents\": output_documents}"}], "type": ["function_empty"], "node": ["haystack.components.joiners.document_joiner.DocumentJoiner._reciprocal_rank_fusion", "haystack.components.joiners.document_joiner.DocumentJoiner.run"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 29, "base_passed_num": 7}} {"id": ["haystack.haystack.components.preprocessors.csv_document_splitter.CSVDocumentSplitter::_split_dataframe", "haystack.haystack.components.preprocessors.csv_document_splitter.CSVDocumentSplitter::_recursive_split"], "project": "haystack", "origin_file": ["haystack/components/preprocessors/csv_document_splitter.py", "haystack/components/preprocessors/csv_document_splitter.py"], "test_list": ["test/components/preprocessors/test_csv_document_splitter.py"], "prob_info": [{"class_start_lineno": 18, "class_end_lineno": 244, "func_start_lineno": 174, "func_end_lineno": 207, "func_code": " def _split_dataframe(\n self, df: \"pd.DataFrame\", split_threshold: int, axis: Literal[\"row\", \"column\"]\n ) -> List[\"pd.DataFrame\"]:\n \"\"\"\n Splits a DataFrame into sub-tables based on consecutive empty rows or columns exceeding `split_threshold`.\n\n :param df: DataFrame to split.\n :param split_threshold: Minimum number of consecutive empty rows or columns to trigger a split.\n :param axis: Axis along which to split. Either \"row\" or \"column\".\n :return: List of split DataFrames.\n \"\"\"\n # Find indices of consecutive empty rows or columns\n split_indices = self._find_split_indices(df=df, split_threshold=split_threshold, axis=axis)\n\n # If no split_indices are found, return the original DataFrame\n if len(split_indices) == 0:\n return [df]\n\n # Split the DataFrame at identified indices\n sub_tables = []\n table_start_idx = 0\n df_length = df.shape[0] if axis == \"row\" else df.shape[1]\n for empty_start_idx, empty_end_idx in split_indices + [(df_length, df_length)]:\n # Avoid empty splits\n if empty_start_idx - table_start_idx >= 1:\n if axis == \"row\":\n sub_table = df.iloc[table_start_idx:empty_start_idx]\n else:\n sub_table = df.iloc[:, table_start_idx:empty_start_idx]\n if not sub_table.empty:\n sub_tables.append(sub_table)\n table_start_idx = empty_end_idx + 1\n\n return sub_tables"}, {"class_start_lineno": 18, "class_end_lineno": 244, "func_start_lineno": 209, "func_end_lineno": 244, "func_code": " def _recursive_split(\n self, df: \"pd.DataFrame\", row_split_threshold: int, column_split_threshold: int\n ) -> List[\"pd.DataFrame\"]:\n \"\"\"\n Recursively splits a DataFrame.\n\n Recursively splits a DataFrame first by empty rows, then by empty columns, and repeats the process\n until no more splits are possible. Returns a list of DataFrames, each representing a fully separated sub-table.\n\n :param df: A Pandas DataFrame representing a table (or multiple tables) extracted from a CSV.\n :param row_split_threshold: The minimum number of consecutive empty rows required to trigger a split.\n :param column_split_threshold: The minimum number of consecutive empty columns to trigger a split.\n \"\"\"\n\n # Step 1: Split by rows\n new_sub_tables = self._split_dataframe(df=df, split_threshold=row_split_threshold, axis=\"row\")\n\n # Step 2: Split by columns\n final_tables = []\n for table in new_sub_tables:\n final_tables.extend(self._split_dataframe(df=table, split_threshold=column_split_threshold, axis=\"column\"))\n\n # Step 3: Recursively reapply splitting checked by whether any new empty rows appear after column split\n result = []\n for table in final_tables:\n # Check if there are consecutive rows >= row_split_threshold now present\n if len(self._find_split_indices(df=table, split_threshold=row_split_threshold, axis=\"row\")) > 0:\n result.extend(\n self._recursive_split(\n df=table, row_split_threshold=row_split_threshold, column_split_threshold=column_split_threshold\n )\n )\n else:\n result.append(table)\n\n return result"}], "type": ["function_empty"], "node": ["haystack.components.preprocessors.csv_document_splitter.CSVDocumentSplitter._split_dataframe", "haystack.components.preprocessors.csv_document_splitter.CSVDocumentSplitter._recursive_split"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 23, "base_passed_num": 15}} {"id": ["haystack.haystack.components.preprocessors.document_cleaner.DocumentCleaner::_find_and_remove_header_footer", "haystack.haystack.components.preprocessors.document_cleaner.DocumentCleaner::_find_longest_common_ngram", "haystack.haystack.components.preprocessors.document_cleaner.DocumentCleaner::_allngram", "haystack.haystack.components.preprocessors.document_cleaner.DocumentCleaner::_ascii_only", "haystack.haystack.components.preprocessors.document_cleaner.DocumentCleaner::run"], "project": "haystack", "origin_file": ["haystack/components/preprocessors/document_cleaner.py", "haystack/components/preprocessors/document_cleaner.py", "haystack/components/preprocessors/document_cleaner.py", "haystack/components/preprocessors/document_cleaner.py", "haystack/components/preprocessors/document_cleaner.py", "haystack/components/preprocessors/document_cleaner.py"], "test_list": ["test/components/preprocessors/test_document_cleaner.py"], "prob_info": [{"class_start_lineno": 18, "class_end_lineno": 325, "func_start_lineno": 231, "func_end_lineno": 267, "func_code": " def _find_and_remove_header_footer(\n self, text: str, n_chars: int, n_first_pages_to_ignore: int, n_last_pages_to_ignore: int\n ) -> str:\n \"\"\"\n Heuristic to find footers and headers across different pages by searching for the longest common string.\n\n Pages in the text need to be separated by form feed character \"\\f\".\n For headers, we only search in the first n_chars characters (for footer: last n_chars).\n Note: This heuristic uses exact matches and therefore works well for footers like \"Copyright 2019 by XXX\",\n but won't detect \"Page 3 of 4\" or similar.\n\n :param n_chars: The number of first/last characters where the header/footer shall be searched in.\n :param n_first_pages_to_ignore: The number of first pages to ignore\n (e.g. TOCs often don't contain footer/header).\n :param n_last_pages_to_ignore: The number of last pages to ignore.\n :returns: The text without the found headers and footers.\n \"\"\"\n\n pages = text.split(\"\\f\")\n\n # header\n start_of_pages = [p[:n_chars] for p in pages[n_first_pages_to_ignore:-n_last_pages_to_ignore]]\n found_header = self._find_longest_common_ngram(start_of_pages)\n if found_header:\n pages = [page.replace(found_header, \"\") for page in pages]\n\n # footer\n end_of_pages = [p[-n_chars:] for p in pages[n_first_pages_to_ignore:-n_last_pages_to_ignore]]\n found_footer = self._find_longest_common_ngram(end_of_pages)\n if found_footer:\n pages = [page.replace(found_footer, \"\") for page in pages]\n\n logger.debug(\n \"Removed header '{header}' and footer '{footer}' in document\", header=found_header, footer=found_footer\n )\n text = \"\\f\".join(pages)\n return text"}, {"class_start_lineno": 18, "class_end_lineno": 325, "func_start_lineno": 306, "func_end_lineno": 325, "func_code": " def _find_longest_common_ngram(self, sequences: List[str], min_ngram: int = 3, max_ngram: int = 30) -> str:\n \"\"\"\n Find the longest common ngram across a list of text sequences (e.g. start of pages).\n\n Considering all ngram lengths between the minimum and maximum length. Helpful for finding footers, headers etc.\n Empty sequences are ignored.\n\n :param sequences: The list of strings that shall be searched for common n_grams.\n :param max_ngram: The maximum length of ngram to consider.\n :param min_ngram: The minimum length of ngram to consider.\n :returns: The longest ngram that all sequences have in common.\n \"\"\"\n sequences = [s for s in sequences if s] # filter empty sequences\n if not sequences:\n return \"\"\n seqs_ngrams = map(partial(self._allngram, min_ngram=min_ngram, max_ngram=max_ngram), sequences)\n intersection = reduce(set.intersection, seqs_ngrams)\n\n longest = max(intersection, key=len, default=\"\")\n return longest if longest.strip() else \"\""}, {"class_start_lineno": 18, "class_end_lineno": 325, "func_start_lineno": 290, "func_end_lineno": 304, "func_code": " def _allngram(self, seq: str, min_ngram: int, max_ngram: int) -> Set[str]:\n \"\"\"\n Generates all possible ngrams from a given sequence of text.\n\n Considering all ngram lengths between the minimum and maximum length.\n\n :param seq: The sequence to generate ngrams from.\n :param min_ngram: The minimum length of ngram to consider.\n :param max_ngram: The maximum length of ngram to consider.\n :returns: A set of all ngrams from the given sequence.\n \"\"\"\n lengths = range(min_ngram, max_ngram) if max_ngram else range(min_ngram, len(seq))\n ngrams = map(partial(self._ngram, seq), lengths)\n res = set(chain.from_iterable(ngrams))\n return res"}, {"class_start_lineno": 18, "class_end_lineno": 325, "func_start_lineno": 219, "func_end_lineno": 229, "func_code": " def _remove_repeated_substrings(self, text: str) -> str:\n \"\"\"\n Remove any substrings from the text that occur repeatedly on every page. For example headers or footers.\n\n Pages in the text need to be separated by form feed character \"\\f\".\n :param text: Text to clean.\n :returns: The text without the repeated substrings.\n \"\"\"\n return self._find_and_remove_header_footer(\n text, n_chars=300, n_first_pages_to_ignore=1, n_last_pages_to_ignore=1\n )"}, {"class_start_lineno": 18, "class_end_lineno": 325, "func_start_lineno": 158, "func_end_lineno": 171, "func_code": " def _ascii_only(self, text: str) -> str:\n \"\"\"\n Convert the text to ASCII only.\n\n Will remove accents from characters and replace them with ASCII characters.\n Other non-ASCII characters will be removed.\n\n :param text: Text to convert to ASCII only.\n :returns: The text in ASCII only.\n \"\"\"\n\n # First normalize the text to NFKD to separate the characters and their diacritics\n # Then encode it to ASCII and ignore any characters that can't be encoded\n return self._normalize_unicode(text, \"NFKD\").encode(\"ascii\", \"ignore\").decode(\"utf-8\")"}, {"class_start_lineno": 18, "class_end_lineno": 325, "func_start_lineno": 93, "func_end_lineno": 145, "func_code": " def run(self, documents: List[Document]):\n \"\"\"\n Cleans up the documents.\n\n :param documents: List of Documents to clean.\n\n :returns: A dictionary with the following key:\n - `documents`: List of cleaned Documents.\n\n :raises TypeError: if documents is not a list of Documents.\n \"\"\"\n if not isinstance(documents, list) or documents and not isinstance(documents[0], Document):\n raise TypeError(\"DocumentCleaner expects a List of Documents as input.\")\n\n cleaned_docs = []\n for doc in documents:\n if doc.content is None:\n logger.warning(\n \"DocumentCleaner only cleans text documents but document.content for document ID\"\n \" %{document_id} is None.\",\n document_id=doc.id,\n )\n cleaned_docs.append(doc)\n continue\n text = doc.content\n\n if self.unicode_normalization:\n text = self._normalize_unicode(text, self.unicode_normalization)\n if self.ascii_only:\n text = self._ascii_only(text)\n if self.remove_extra_whitespaces:\n text = self._remove_extra_whitespaces(text)\n if self.remove_empty_lines:\n text = self._remove_empty_lines(text)\n if self.remove_substrings:\n text = self._remove_substrings(text, self.remove_substrings)\n if self.remove_regex:\n text = self._remove_regex(text, self.remove_regex)\n if self.remove_repeated_substrings:\n text = self._remove_repeated_substrings(text)\n\n clean_doc = Document(\n id=doc.id if self.keep_id else \"\",\n content=text,\n blob=doc.blob,\n meta=deepcopy(doc.meta),\n score=doc.score,\n embedding=doc.embedding,\n sparse_embedding=doc.sparse_embedding,\n )\n cleaned_docs.append(clean_doc)\n\n return {\"documents\": cleaned_docs}"}], "type": ["function_empty"], "node": ["haystack.components.preprocessors.document_cleaner.DocumentCleaner._find_and_remove_header_footer", "haystack.components.preprocessors.document_cleaner.DocumentCleaner._find_longest_common_ngram", "haystack.components.preprocessors.document_cleaner.DocumentCleaner._allngram", "haystack.components.preprocessors.document_cleaner.DocumentCleaner._remove_repeated_substrings", "haystack.components.preprocessors.document_cleaner.DocumentCleaner._ascii_only", "haystack.components.preprocessors.document_cleaner.DocumentCleaner.run"], "language": "Python", "toolfunc_count": 5, "func_count": 5, "pytest_info": {"total_num": 14, "base_passed_num": 1}} {"id": ["haystack.haystack.components.preprocessors.document_splitter.DocumentSplitter::_split_document", "haystack.haystack.components.preprocessors.document_splitter.DocumentSplitter::run", "haystack.haystack.components.preprocessors.document_splitter.DocumentSplitter::_concatenate_units", "haystack.haystack.components.preprocessors.sentence_tokenizer.SentenceSplitter::split_sentences"], "project": "haystack", "origin_file": ["haystack/components/preprocessors/document_splitter.py", "haystack/components/preprocessors/document_splitter.py", "haystack/components/preprocessors/document_splitter.py", "haystack/components/preprocessors/document_splitter.py", "haystack/components/preprocessors/sentence_tokenizer.py", "haystack/components/preprocessors/document_splitter.py"], "test_list": ["test/components/preprocessors/test_document_splitter.py"], "prob_info": [{"class_start_lineno": 22, "class_end_lineno": 490, "func_start_lineno": 204, "func_end_lineno": 211, "func_code": " def _split_document(self, doc: Document) -> List[Document]:\n if self.split_by == \"sentence\" or self.respect_sentence_boundary:\n return self._split_by_nltk_sentence(doc)\n\n if self.split_by == \"function\" and self.splitting_function is not None:\n return self._split_by_function(doc)\n\n return self._split_by_character(doc)"}, {"class_start_lineno": 22, "class_end_lineno": 490, "func_start_lineno": 166, "func_end_lineno": 202, "func_code": " def run(self, documents: List[Document]):\n \"\"\"\n Split documents into smaller parts.\n\n Splits documents by the unit expressed in `split_by`, with a length of `split_length`\n and an overlap of `split_overlap`.\n\n :param documents: The documents to split.\n :returns: A dictionary with the following key:\n - `documents`: List of documents with the split texts. Each document includes:\n - A metadata field `source_id` to track the original document.\n - A metadata field `page_number` to track the original page number.\n - All other metadata copied from the original document.\n\n :raises TypeError: if the input is not a list of Documents.\n :raises ValueError: if the content of a document is None.\n \"\"\"\n if self._use_sentence_splitter and self.sentence_splitter is None:\n raise RuntimeError(\n \"The component DocumentSplitter wasn't warmed up. Run 'warm_up()' before calling 'run()'.\"\n )\n\n if not isinstance(documents, list) or (documents and not isinstance(documents[0], Document)):\n raise TypeError(\"DocumentSplitter expects a List of Documents as input.\")\n\n split_docs: List[Document] = []\n for doc in documents:\n if doc.content is None:\n raise ValueError(\n f\"DocumentSplitter only works with text documents but content for document ID {doc.id} is None.\"\n )\n if doc.content == \"\":\n logger.warning(\"Document ID {doc_id} has an empty content. Skipping this document.\", doc_id=doc.id)\n continue\n\n split_docs += self._split_document(doc)\n return {\"documents\": split_docs}"}, {"class_start_lineno": 22, "class_end_lineno": 490, "func_start_lineno": 263, "func_end_lineno": 306, "func_code": " def _concatenate_units(\n self, elements: List[str], split_length: int, split_overlap: int, split_threshold: int\n ) -> Tuple[List[str], List[int], List[int]]:\n \"\"\"\n Concatenates the elements into parts of split_length units.\n\n Keeps track of the original page number that each element belongs. If the length of the current units is less\n than the pre-defined `split_threshold`, it does not create a new split. Instead, it concatenates the current\n units with the last split, preventing the creation of excessively small splits.\n \"\"\"\n\n text_splits: List[str] = []\n splits_pages: List[int] = []\n splits_start_idxs: List[int] = []\n cur_start_idx = 0\n cur_page = 1\n segments = windowed(elements, n=split_length, step=split_length - split_overlap)\n\n for seg in segments:\n current_units = [unit for unit in seg if unit is not None]\n txt = \"\".join(current_units)\n\n # check if length of current units is below split_threshold\n if len(current_units) < split_threshold and len(text_splits) > 0:\n # concatenate the last split with the current one\n text_splits[-1] += txt\n\n # NOTE: This line skips documents that have content=\"\"\n elif len(txt) > 0:\n text_splits.append(txt)\n splits_pages.append(cur_page)\n splits_start_idxs.append(cur_start_idx)\n\n processed_units = current_units[: split_length - split_overlap]\n cur_start_idx += len(\"\".join(processed_units))\n\n if self.split_by == \"page\":\n num_page_breaks = len(processed_units)\n else:\n num_page_breaks = sum(processed_unit.count(\"\\f\") for processed_unit in processed_units)\n\n cur_page += num_page_breaks\n\n return text_splits, splits_pages, splits_start_idxs"}, {"class_start_lineno": 22, "class_end_lineno": 490, "func_start_lineno": 238, "func_end_lineno": 251, "func_code": " def _split_by_character(self, doc) -> List[Document]:\n split_at = _CHARACTER_SPLIT_BY_MAPPING[self.split_by]\n units = doc.content.split(split_at)\n # Add the delimiter back to all units except the last one\n for i in range(len(units) - 1):\n units[i] += split_at\n text_splits, splits_pages, splits_start_idxs = self._concatenate_units(\n units, self.split_length, self.split_overlap, self.split_threshold\n )\n metadata = deepcopy(doc.meta)\n metadata[\"source_id\"] = doc.id\n return self._create_docs_from_splits(\n text_splits=text_splits, splits_pages=splits_pages, splits_start_idxs=splits_start_idxs, meta=metadata\n )"}, {"class_start_lineno": 116, "class_end_lineno": 238, "func_start_lineno": 147, "func_end_lineno": 159, "func_code": " def split_sentences(self, text: str) -> List[Dict[str, Any]]:\n \"\"\"\n Splits a text into sentences including references to original char positions for each split.\n\n :param text: The text to split.\n :returns: list of sentences with positions.\n \"\"\"\n sentence_spans = list(self.sentence_tokenizer.span_tokenize(text))\n if self.use_split_rules:\n sentence_spans = SentenceSplitter._apply_split_rules(text, sentence_spans)\n\n sentences = [{\"sentence\": text[start:end], \"start\": start, \"end\": end} for start, end in sentence_spans]\n return sentences"}, {"class_start_lineno": 22, "class_end_lineno": 490, "func_start_lineno": 213, "func_end_lineno": 236, "func_code": " def _split_by_nltk_sentence(self, doc: Document) -> List[Document]:\n split_docs = []\n\n result = self.sentence_splitter.split_sentences(doc.content) # type: ignore # None check is done in run()\n units = [sentence[\"sentence\"] for sentence in result]\n\n if self.respect_sentence_boundary:\n text_splits, splits_pages, splits_start_idxs = self._concatenate_sentences_based_on_word_amount(\n sentences=units, split_length=self.split_length, split_overlap=self.split_overlap\n )\n else:\n text_splits, splits_pages, splits_start_idxs = self._concatenate_units(\n elements=units,\n split_length=self.split_length,\n split_overlap=self.split_overlap,\n split_threshold=self.split_threshold,\n )\n metadata = deepcopy(doc.meta)\n metadata[\"source_id\"] = doc.id\n split_docs += self._create_docs_from_splits(\n text_splits=text_splits, splits_pages=splits_pages, splits_start_idxs=splits_start_idxs, meta=metadata\n )\n\n return split_docs"}], "type": ["function_empty", "TDD"], "node": ["haystack.components.preprocessors.document_splitter.DocumentSplitter._split_document", "haystack.components.preprocessors.document_splitter.DocumentSplitter.run", "haystack.components.preprocessors.document_splitter.DocumentSplitter._concatenate_units", "haystack.components.preprocessors.document_splitter.DocumentSplitter._split_by_character", "haystack.components.preprocessors.sentence_tokenizer.SentenceSplitter.split_sentences", "haystack.components.preprocessors.document_splitter.DocumentSplitter._split_by_nltk_sentence"], "language": "Python", "toolfunc_count": 2, "func_count": 4, "pytest_info": {"total_num": 53, "base_passed_num": 20}} {"id": ["haystack.haystack.components.preprocessors.recursive_splitter.RecursiveDocumentSplitter::_chunk_length", "haystack.haystack.components.preprocessors.recursive_splitter.RecursiveDocumentSplitter::_split_chunk", "haystack.haystack.components.preprocessors.recursive_splitter.RecursiveDocumentSplitter::_apply_overlap", "haystack.haystack.components.preprocessors.sentence_tokenizer.SentenceSplitter::split_sentences", "haystack.haystack.components.preprocessors.recursive_splitter.RecursiveDocumentSplitter::_chunk_text"], "project": "haystack", "origin_file": ["haystack/components/preprocessors/recursive_splitter.py", "haystack/components/preprocessors/recursive_splitter.py", "haystack/components/preprocessors/recursive_splitter.py", "haystack/components/preprocessors/recursive_splitter.py", "haystack/components/preprocessors/sentence_tokenizer.py", "haystack/components/preprocessors/recursive_splitter.py"], "test_list": ["test/components/preprocessors/test_recursive_splitter.py"], "prob_info": [{"class_start_lineno": 15, "class_end_lineno": 421, "func_start_lineno": 215, "func_end_lineno": 227, "func_code": " def _chunk_length(self, text: str) -> int:\n \"\"\"\n Split the text by whitespace and count non-empty elements.\n\n :param: The text to be split.\n :return: The number of words in the text.\n \"\"\"\n\n if self.split_units == \"word\":\n words = [word for word in text.split(\" \") if word]\n return len(words)\n\n return len(text)"}, {"class_start_lineno": 15, "class_end_lineno": 421, "func_start_lineno": 204, "func_end_lineno": 213, "func_code": " def _get_overlap(self, overlapped_chunks: List[str]) -> Tuple[str, str]:\n \"\"\"Get the previous overlapped chunk instead of the original chunk.\"\"\"\n prev_chunk = overlapped_chunks[-1]\n overlap_start = max(0, self._chunk_length(prev_chunk) - self.split_overlap)\n if self.split_units == \"word\":\n word_chunks = prev_chunk.split()\n overlap = \" \".join(word_chunks[overlap_start:])\n else:\n overlap = prev_chunk[overlap_start:]\n return overlap, prev_chunk"}, {"class_start_lineno": 15, "class_end_lineno": 421, "func_start_lineno": 114, "func_end_lineno": 133, "func_code": " def _split_chunk(self, current_chunk: str) -> Tuple[str, str]:\n \"\"\"\n Splits a chunk based on the split_length and split_units attribute.\n\n :param current_chunk: The current chunk to be split.\n :returns:\n A tuple containing the current chunk and the remaining words or characters.\n \"\"\"\n\n if self.split_units == \"word\":\n words = current_chunk.split()\n current_chunk = \" \".join(words[: self.split_length])\n remaining_words = words[self.split_length :]\n return current_chunk, \" \".join(remaining_words)\n\n # split by characters\n text = current_chunk\n current_chunk = text[: self.split_length]\n remaining_chars = text[self.split_length :]\n return current_chunk, remaining_chars"}, {"class_start_lineno": 15, "class_end_lineno": 421, "func_start_lineno": 135, "func_end_lineno": 202, "func_code": " def _apply_overlap(self, chunks: List[str]) -> List[str]:\n \"\"\"\n Applies an overlap between consecutive chunks if the chunk_overlap attribute is greater than zero.\n\n Works for both word- and character-level splitting. It trims the last chunk if it exceeds the split_length and\n adds the trimmed content to the next chunk. If the last chunk is still too long after trimming, it splits it\n and adds the first chunk to the list. This process continues until the last chunk is within the split_length.\n\n :param chunks: A list of text chunks.\n :returns:\n A list of text chunks with the overlap applied.\n \"\"\"\n overlapped_chunks: List[str] = []\n\n for idx, chunk in enumerate(chunks):\n if idx == 0:\n overlapped_chunks.append(chunk)\n continue\n\n # get the overlap between the current and previous chunk\n overlap, prev_chunk = self._get_overlap(overlapped_chunks)\n if overlap == prev_chunk:\n logger.warning(\n \"Overlap is the same as the previous chunk. \"\n \"Consider increasing the `split_length` parameter or decreasing the `split_overlap` parameter.\"\n )\n\n # create a new chunk starting with the overlap\n current_chunk = overlap + \" \" + chunk if self.split_units == \"word\" else overlap + chunk\n\n # if this new chunk exceeds 'split_length', trim it and move the remaining text to the next chunk\n # if this is the last chunk, another new chunk will contain the trimmed text preceded by the overlap\n # of the last chunk\n if self._chunk_length(current_chunk) > self.split_length:\n current_chunk, remaining_text = self._split_chunk(current_chunk)\n if idx < len(chunks) - 1:\n chunks[idx + 1] = remaining_text + (\" \" if self.split_units == \"word\" else \"\") + chunks[idx + 1]\n elif remaining_text:\n # create a new chunk with the trimmed text preceded by the overlap of the last chunk\n overlapped_chunks.append(current_chunk)\n chunk = remaining_text\n overlap, _ = self._get_overlap(overlapped_chunks)\n current_chunk = overlap + \" \" + chunk if self.split_units == \"word\" else overlap + chunk\n\n overlapped_chunks.append(current_chunk)\n\n # it can still be that the new last chunk exceeds the 'split_length'\n # continue splitting until the last chunk is within 'split_length'\n if idx == len(chunks) - 1 and self._chunk_length(current_chunk) > self.split_length:\n last_chunk = overlapped_chunks.pop()\n first_chunk, remaining_chunk = self._split_chunk(last_chunk)\n overlapped_chunks.append(first_chunk)\n\n while remaining_chunk:\n # combine overlap with remaining chunk\n overlap, _ = self._get_overlap(overlapped_chunks)\n current = overlap + (\" \" if self.split_units == \"word\" else \"\") + remaining_chunk\n\n # if it fits within split_length we are done\n if self._chunk_length(current) <= self.split_length:\n overlapped_chunks.append(current)\n break\n\n # otherwise split it again\n first_chunk, remaining_chunk = self._split_chunk(current)\n overlapped_chunks.append(first_chunk)\n\n return overlapped_chunks"}, {"class_start_lineno": 116, "class_end_lineno": 238, "func_start_lineno": 147, "func_end_lineno": 159, "func_code": " def split_sentences(self, text: str) -> List[Dict[str, Any]]:\n \"\"\"\n Splits a text into sentences including references to original char positions for each split.\n\n :param text: The text to split.\n :returns: list of sentences with positions.\n \"\"\"\n sentence_spans = list(self.sentence_tokenizer.span_tokenize(text))\n if self.use_split_rules:\n sentence_spans = SentenceSplitter._apply_split_rules(text, sentence_spans)\n\n sentences = [{\"sentence\": text[start:end], \"start\": start, \"end\": end} for start, end in sentence_spans]\n return sentences"}, {"class_start_lineno": 15, "class_end_lineno": 421, "func_start_lineno": 229, "func_end_lineno": 311, "func_code": " def _chunk_text(self, text: str) -> List[str]:\n \"\"\"\n Recursive chunking algorithm that divides text into smaller chunks based on a list of separator characters.\n\n It starts with a list of separator characters (e.g., [\"\\n\\n\", \"sentence\", \"\\n\", \" \"]) and attempts to divide\n the text using the first separator. If the resulting chunks are still larger than the specified chunk size,\n it moves to the next separator in the list. This process continues recursively, progressively applying each\n specific separator until the chunks meet the desired size criteria.\n\n :param text: The text to be split into chunks.\n :returns:\n A list of text chunks.\n \"\"\"\n if self._chunk_length(text) <= self.split_length:\n return [text]\n\n for curr_separator in self.separators: # type: ignore # the caller already checked that separators is not None\n if curr_separator == \"sentence\":\n # re. ignore: correct SentenceSplitter initialization is checked at the initialization of the component\n sentence_with_spans = self.nltk_tokenizer.split_sentences(text) # type: ignore\n splits = [sentence[\"sentence\"] for sentence in sentence_with_spans]\n else:\n # add escape \"\\\" to the separator and wrapped it in a group so that it's included in the splits as well\n escaped_separator = re.escape(curr_separator)\n escaped_separator = f\"({escaped_separator})\"\n\n # split the text and merge every two consecutive splits, i.e.: the text and the separator after it\n splits = re.split(escaped_separator, text)\n splits = [\n \"\".join([splits[i], splits[i + 1]]) if i < len(splits) - 1 else splits[i]\n for i in range(0, len(splits), 2)\n ]\n\n # remove last split if it's empty\n splits = splits[:-1] if splits[-1] == \"\" else splits\n\n if len(splits) == 1: # go to next separator, if current separator not found in the text\n continue\n\n chunks = []\n current_chunk: List[str] = []\n current_length = 0\n\n # check splits, if any is too long, recursively chunk it, otherwise add to current chunk\n for split in splits:\n split_text = split\n\n # if adding this split exceeds chunk_size, process current_chunk\n if current_length + self._chunk_length(split_text) > self.split_length:\n # process current_chunk\n if current_chunk: # keep the good splits\n chunks.append(\"\".join(current_chunk))\n current_chunk = []\n current_length = 0\n\n # recursively handle splits that are too large\n if self._chunk_length(split_text) > self.split_length:\n if curr_separator == self.separators[-1]:\n # tried last separator, can't split further, do a fixed-split based on word/character\n fall_back_chunks = self._fall_back_to_fixed_chunking(split_text, self.split_units)\n chunks.extend(fall_back_chunks)\n else:\n chunks.extend(self._chunk_text(split_text))\n current_length += self._chunk_length(split_text)\n\n else:\n current_chunk.append(split_text)\n current_length += self._chunk_length(split_text)\n else:\n current_chunk.append(split_text)\n current_length += self._chunk_length(split_text)\n\n if current_chunk:\n chunks.append(\"\".join(current_chunk))\n\n if self.split_overlap > 0:\n chunks = self._apply_overlap(chunks)\n\n if chunks:\n return chunks\n\n # if no separator worked, fall back to word- or character-level chunking\n return self._fall_back_to_fixed_chunking(text, self.split_units)"}], "type": ["function_empty", "TDD"], "node": ["haystack.components.preprocessors.recursive_splitter.RecursiveDocumentSplitter._chunk_length", "haystack.components.preprocessors.recursive_splitter.RecursiveDocumentSplitter._get_overlap", "haystack.components.preprocessors.recursive_splitter.RecursiveDocumentSplitter._split_chunk", "haystack.components.preprocessors.recursive_splitter.RecursiveDocumentSplitter._apply_overlap", "haystack.components.preprocessors.sentence_tokenizer.SentenceSplitter.split_sentences", "haystack.components.preprocessors.recursive_splitter.RecursiveDocumentSplitter._chunk_text"], "language": "Python", "toolfunc_count": 4, "func_count": 5, "pytest_info": {"total_num": 35, "base_passed_num": 8}} {"id": ["haystack.haystack.utils.device.ComponentDevice::to_dict", "haystack.haystack.components.rankers.sentence_transformers_diversity.SentenceTransformersDiversityRanker::to_dict", "haystack.haystack.components.rankers.sentence_transformers_diversity.SentenceTransformersDiversityRanker::_prepare_texts_to_embed", "haystack.haystack.components.rankers.sentence_transformers_diversity.SentenceTransformersDiversityRanker::_greedy_diversity_order", "haystack.haystack.components.rankers.sentence_transformers_diversity.SentenceTransformersDiversityRanker::run"], "project": "haystack", "origin_file": ["haystack/utils/device.py", "haystack/components/rankers/sentence_transformers_diversity.py", "haystack/components/rankers/sentence_transformers_diversity.py", "haystack/components/rankers/sentence_transformers_diversity.py", "haystack/components/rankers/sentence_transformers_diversity.py"], "test_list": ["test/components/rankers/test_sentence_transformers_diversity.py"], "prob_info": [{"class_start_lineno": 240, "class_end_lineno": 480, "func_start_lineno": 450, "func_end_lineno": 463, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Convert the component device representation to a JSON-serializable dictionary.\n\n :returns:\n The dictionary representation.\n \"\"\"\n if self._single_device is not None:\n return {\"type\": \"single\", \"device\": str(self._single_device)}\n elif self._multiple_devices is not None:\n return {\"type\": \"multiple\", \"device_map\": self._multiple_devices.to_dict()}\n else:\n # Unreachable\n assert False"}, {"class_start_lineno": 76, "class_end_lineno": 435, "func_start_lineno": 212, "func_end_lineno": 241, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serializes the component to a dictionary.\n\n :returns:\n Dictionary with serialized data.\n \"\"\"\n serialization_dict = default_to_dict(\n self,\n model=self.model_name_or_path,\n top_k=self.top_k,\n device=self.device.to_dict(),\n token=self.token.to_dict() if self.token else None,\n similarity=str(self.similarity),\n query_prefix=self.query_prefix,\n query_suffix=self.query_suffix,\n document_prefix=self.document_prefix,\n document_suffix=self.document_suffix,\n meta_fields_to_embed=self.meta_fields_to_embed,\n embedding_separator=self.embedding_separator,\n strategy=str(self.strategy),\n lambda_threshold=self.lambda_threshold,\n model_kwargs=self.model_kwargs,\n tokenizer_kwargs=self.tokenizer_kwargs,\n config_kwargs=self.config_kwargs,\n backend=self.backend,\n )\n if serialization_dict[\"init_parameters\"].get(\"model_kwargs\") is not None:\n serialize_hf_model_kwargs(serialization_dict[\"init_parameters\"][\"model_kwargs\"])\n return serialization_dict"}, {"class_start_lineno": 76, "class_end_lineno": 435, "func_start_lineno": 261, "func_end_lineno": 277, "func_code": " def _prepare_texts_to_embed(self, documents: List[Document]) -> List[str]:\n \"\"\"\n Prepare the texts to embed by concatenating the Document text with the metadata fields to embed.\n \"\"\"\n texts_to_embed = []\n for doc in documents:\n meta_values_to_embed = [\n str(doc.meta[key]) for key in self.meta_fields_to_embed if key in doc.meta and doc.meta[key]\n ]\n text_to_embed = (\n self.document_prefix\n + self.embedding_separator.join(meta_values_to_embed + [doc.content or \"\"])\n + self.document_suffix\n )\n texts_to_embed.append(text_to_embed)\n\n return texts_to_embed"}, {"class_start_lineno": 76, "class_end_lineno": 435, "func_start_lineno": 279, "func_end_lineno": 323, "func_code": " def _greedy_diversity_order(self, query: str, documents: List[Document]) -> List[Document]:\n \"\"\"\n Orders the given list of documents to maximize diversity.\n\n The algorithm first calculates embeddings for each document and the query. It starts by selecting the document\n that is semantically closest to the query. Then, for each remaining document, it selects the one that, on\n average, is least similar to the already selected documents. This process continues until all documents are\n selected, resulting in a list where each subsequent document contributes the most to the overall diversity of\n the selected set.\n\n :param query: The search query.\n :param documents: The list of Document objects to be ranked.\n\n :return: A list of documents ordered to maximize diversity.\n \"\"\"\n texts_to_embed = self._prepare_texts_to_embed(documents)\n\n doc_embeddings, query_embedding = self._embed_and_normalize(query, texts_to_embed)\n\n n = len(documents)\n selected: List[int] = []\n\n # Compute the similarity vector between the query and documents\n query_doc_sim = query_embedding @ doc_embeddings.T\n\n # Start with the document with the highest similarity to the query\n selected.append(int(torch.argmax(query_doc_sim).item()))\n\n selected_sum = doc_embeddings[selected[0]] / n\n\n while len(selected) < n:\n # Compute mean of dot products of all selected documents and all other documents\n similarities = selected_sum @ doc_embeddings.T\n # Mask documents that are already selected\n similarities[selected] = torch.inf\n # Select the document with the lowest total similarity score\n index_unselected = int(torch.argmin(similarities).item())\n selected.append(index_unselected)\n # It's enough just to add to the selected vectors because dot product is distributive\n # It's divided by n for numerical stability\n selected_sum += doc_embeddings[index_unselected] / n\n\n ranked_docs: List[Document] = [documents[i] for i in selected]\n\n return ranked_docs"}, {"class_start_lineno": 76, "class_end_lineno": 435, "func_start_lineno": 388, "func_end_lineno": 435, "func_code": " def run(\n self,\n query: str,\n documents: List[Document],\n top_k: Optional[int] = None,\n lambda_threshold: Optional[float] = None,\n ) -> Dict[str, List[Document]]:\n \"\"\"\n Rank the documents based on their diversity.\n\n :param query: The search query.\n :param documents: List of Document objects to be ranker.\n :param top_k: Optional. An integer to override the top_k set during initialization.\n :param lambda_threshold: Override the trade-off parameter between relevance and diversity. Only used when\n strategy is \"maximum_margin_relevance\".\n\n :returns: A dictionary with the following key:\n - `documents`: List of Document objects that have been selected based on the diversity ranking.\n\n :raises ValueError: If the top_k value is less than or equal to 0.\n :raises RuntimeError: If the component has not been warmed up.\n \"\"\"\n if self.model is None:\n error_msg = (\n \"The component SentenceTransformersDiversityRanker wasn't warmed up. \"\n \"Run 'warm_up()' before calling 'run()'.\"\n )\n raise RuntimeError(error_msg)\n\n if not documents:\n return {\"documents\": []}\n\n if top_k is None:\n top_k = self.top_k\n elif not 0 < top_k <= len(documents):\n raise ValueError(f\"top_k must be between 1 and {len(documents)}, but got {top_k}\")\n\n if self.strategy == DiversityRankingStrategy.MAXIMUM_MARGIN_RELEVANCE:\n if lambda_threshold is None:\n lambda_threshold = self.lambda_threshold\n self._check_lambda_threshold(lambda_threshold, self.strategy)\n re_ranked_docs = self._maximum_margin_relevance(\n query=query, documents=documents, lambda_threshold=lambda_threshold, top_k=top_k\n )\n else:\n re_ranked_docs = self._greedy_diversity_order(query=query, documents=documents)\n\n return {\"documents\": re_ranked_docs[:top_k]}"}], "type": ["function_empty", "TDD"], "node": ["haystack.utils.device.ComponentDevice.to_dict", "haystack.components.rankers.sentence_transformers_diversity.SentenceTransformersDiversityRanker.to_dict", "haystack.components.rankers.sentence_transformers_diversity.SentenceTransformersDiversityRanker._prepare_texts_to_embed", "haystack.components.rankers.sentence_transformers_diversity.SentenceTransformersDiversityRanker._greedy_diversity_order", "haystack.components.rankers.sentence_transformers_diversity.SentenceTransformersDiversityRanker.run"], "language": "Python", "toolfunc_count": 2, "func_count": 5, "pytest_info": {"total_num": 53, "base_passed_num": 17}} {"id": ["haystack.haystack.core.serialization.default_to_dict", "haystack.haystack.utils.hf.serialize_hf_model_kwargs", "haystack.haystack.components.rankers.transformers_similarity.TransformersSimilarityRanker::to_dict"], "project": "haystack", "origin_file": ["haystack/core/serialization.py", "haystack/utils/hf.py", "haystack/components/rankers/transformers_similarity.py"], "test_list": ["test/components/rankers/test_transformers_similarity.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 264, "func_start_lineno": 172, "func_end_lineno": 210, "func_code": "def default_to_dict(obj: Any, **init_parameters) -> Dict[str, Any]:\n \"\"\"\n Utility function to serialize an object to a dictionary.\n\n This is mostly necessary for components but can be used by any object.\n `init_parameters` are parameters passed to the object class `__init__`.\n They must be defined explicitly as they'll be used when creating a new\n instance of `obj` with `from_dict`. Omitting them might cause deserialisation\n errors or unexpected behaviours later, when calling `from_dict`.\n\n An example usage:\n\n ```python\n class MyClass:\n def __init__(self, my_param: int = 10):\n self.my_param = my_param\n\n def to_dict(self):\n return default_to_dict(self, my_param=self.my_param)\n\n\n obj = MyClass(my_param=1000)\n data = obj.to_dict()\n assert data == {\n \"type\": \"MyClass\",\n \"init_parameters\": {\n \"my_param\": 1000,\n },\n }\n ```\n\n :param obj:\n The object to be serialized.\n :param init_parameters:\n The parameters used to create a new instance of the class.\n :returns:\n A dictionary representation of the instance.\n \"\"\"\n return {\"type\": generate_qualified_class_name(type(obj)), \"init_parameters\": init_parameters}"}, {"class_start_lineno": 1, "class_end_lineno": 395, "func_start_lineno": 98, "func_end_lineno": 112, "func_code": "def serialize_hf_model_kwargs(kwargs: Dict[str, Any]):\n \"\"\"\n Recursively serialize HuggingFace specific model keyword arguments in-place to make them JSON serializable.\n\n :param kwargs: The keyword arguments to serialize\n \"\"\"\n torch_import.check()\n\n for k, v in kwargs.items():\n # torch.dtype\n if isinstance(v, torch.dtype):\n kwargs[k] = str(v)\n\n if isinstance(v, dict):\n serialize_hf_model_kwargs(v)"}, {"class_start_lineno": 24, "class_end_lineno": 309, "func_start_lineno": 157, "func_end_lineno": 182, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serializes the component to a dictionary.\n\n :returns:\n Dictionary with serialized data.\n \"\"\"\n serialization_dict = default_to_dict(\n self,\n device=None,\n model=self.model_name_or_path,\n token=self.token.to_dict() if self.token else None,\n top_k=self.top_k,\n query_prefix=self.query_prefix,\n document_prefix=self.document_prefix,\n meta_fields_to_embed=self.meta_fields_to_embed,\n embedding_separator=self.embedding_separator,\n scale_score=self.scale_score,\n calibration_factor=self.calibration_factor,\n score_threshold=self.score_threshold,\n model_kwargs=self.model_kwargs,\n tokenizer_kwargs=self.tokenizer_kwargs,\n )\n\n serialize_hf_model_kwargs(serialization_dict[\"init_parameters\"][\"model_kwargs\"])\n return serialization_dict"}], "type": ["function_empty"], "node": ["haystack.core.serialization.default_to_dict", "haystack.utils.hf.serialize_hf_model_kwargs", "haystack.components.rankers.transformers_similarity.TransformersSimilarityRanker.to_dict"], "language": "Python", "toolfunc_count": 3, "func_count": 3, "pytest_info": {"total_num": 26, "base_passed_num": 20}} {"id": ["haystack.haystack.core.serialization.default_to_dict", "haystack.haystack.utils.hf.serialize_hf_model_kwargs", "haystack.haystack.components.readers.extractive.ExtractiveReader::to_dict", "haystack.haystack.components.readers.extractive.ExtractiveReader::_should_keep", "haystack.haystack.components.readers.extractive.ExtractiveReader::deduplicate_by_overlap"], "project": "haystack", "origin_file": ["haystack/core/serialization.py", "haystack/utils/hf.py", "haystack/components/readers/extractive.py", "haystack/components/readers/extractive.py", "haystack/components/readers/extractive.py"], "test_list": ["test/components/readers/test_extractive.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 264, "func_start_lineno": 172, "func_end_lineno": 210, "func_code": "def default_to_dict(obj: Any, **init_parameters) -> Dict[str, Any]:\n \"\"\"\n Utility function to serialize an object to a dictionary.\n\n This is mostly necessary for components but can be used by any object.\n `init_parameters` are parameters passed to the object class `__init__`.\n They must be defined explicitly as they'll be used when creating a new\n instance of `obj` with `from_dict`. Omitting them might cause deserialisation\n errors or unexpected behaviours later, when calling `from_dict`.\n\n An example usage:\n\n ```python\n class MyClass:\n def __init__(self, my_param: int = 10):\n self.my_param = my_param\n\n def to_dict(self):\n return default_to_dict(self, my_param=self.my_param)\n\n\n obj = MyClass(my_param=1000)\n data = obj.to_dict()\n assert data == {\n \"type\": \"MyClass\",\n \"init_parameters\": {\n \"my_param\": 1000,\n },\n }\n ```\n\n :param obj:\n The object to be serialized.\n :param init_parameters:\n The parameters used to create a new instance of the class.\n :returns:\n A dictionary representation of the instance.\n \"\"\"\n return {\"type\": generate_qualified_class_name(type(obj)), \"init_parameters\": init_parameters}"}, {"class_start_lineno": 1, "class_end_lineno": 395, "func_start_lineno": 98, "func_end_lineno": 112, "func_code": "def serialize_hf_model_kwargs(kwargs: Dict[str, Any]):\n \"\"\"\n Recursively serialize HuggingFace specific model keyword arguments in-place to make them JSON serializable.\n\n :param kwargs: The keyword arguments to serialize\n \"\"\"\n torch_import.check()\n\n for k, v in kwargs.items():\n # torch.dtype\n if isinstance(v, torch.dtype):\n kwargs[k] = str(v)\n\n if isinstance(v, dict):\n serialize_hf_model_kwargs(v)"}, {"class_start_lineno": 26, "class_end_lineno": 660, "func_start_lineno": 136, "func_end_lineno": 160, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serializes the component to a dictionary.\n\n :returns:\n Dictionary with serialized data.\n \"\"\"\n serialization_dict = default_to_dict(\n self,\n model=self.model_name_or_path,\n device=None,\n token=self.token.to_dict() if self.token else None,\n max_seq_length=self.max_seq_length,\n top_k=self.top_k,\n score_threshold=self.score_threshold,\n stride=self.stride,\n max_batch_size=self.max_batch_size,\n answers_per_seq=self.answers_per_seq,\n no_answer=self.no_answer,\n calibration_factor=self.calibration_factor,\n model_kwargs=self.model_kwargs,\n )\n\n serialize_hf_model_kwargs(serialization_dict[\"init_parameters\"][\"model_kwargs\"])\n return serialization_dict"}, {"class_start_lineno": 26, "class_end_lineno": 660, "func_start_lineno": 432, "func_end_lineno": 492, "func_code": " def _should_keep(\n self, candidate_answer: ExtractedAnswer, current_answers: List[ExtractedAnswer], overlap_threshold: float\n ) -> bool:\n \"\"\"\n Determines if the answer should be kept based on how much it overlaps with previous answers.\n\n NOTE: We might want to avoid throwing away answers that only have a few character (or word) overlap:\n - E.g. The answers \"the river in\" and \"in Maine\" from the context \"I want to go to the river in Maine.\"\n might both want to be kept.\n\n :param candidate_answer:\n Candidate answer that will be checked if it should be kept.\n :param current_answers:\n Current list of answers that will be kept.\n :param overlap_threshold:\n If the overlap between two answers is greater than this threshold then return False.\n \"\"\"\n keep = True\n\n # If the candidate answer doesn't have a document keep it\n if not candidate_answer.document:\n return keep\n\n for ans in current_answers:\n # If an answer in current_answers doesn't have a document skip the comparison\n if not ans.document:\n continue\n\n # If offset is missing then keep both\n if ans.document_offset is None:\n continue\n\n # If offset is missing then keep both\n if candidate_answer.document_offset is None:\n continue\n\n # If the answers come from different documents then keep both\n if candidate_answer.document.id != ans.document.id:\n continue\n\n overlap_len = self._calculate_overlap(\n answer1_start=ans.document_offset.start,\n answer1_end=ans.document_offset.end,\n answer2_start=candidate_answer.document_offset.start,\n answer2_end=candidate_answer.document_offset.end,\n )\n\n # If overlap is 0 then keep\n if overlap_len == 0:\n continue\n\n overlap_frac_answer1 = overlap_len / (ans.document_offset.end - ans.document_offset.start)\n overlap_frac_answer2 = overlap_len / (\n candidate_answer.document_offset.end - candidate_answer.document_offset.start\n )\n\n if overlap_frac_answer1 > overlap_threshold or overlap_frac_answer2 > overlap_threshold:\n keep = False\n break\n\n return keep"}, {"class_start_lineno": 26, "class_end_lineno": 660, "func_start_lineno": 494, "func_end_lineno": 529, "func_code": " def deduplicate_by_overlap(\n self, answers: List[ExtractedAnswer], overlap_threshold: Optional[float]\n ) -> List[ExtractedAnswer]:\n \"\"\"\n De-duplicates overlapping Extractive Answers.\n\n De-duplicates overlapping Extractive Answers from the same document based on how much the spans of the\n answers overlap.\n\n :param answers:\n List of answers to be deduplicated.\n :param overlap_threshold:\n If set this will remove duplicate answers if they have an overlap larger than the\n supplied threshold. For example, for the answers \"in the river in Maine\" and \"the river\" we would remove\n one of these answers since the second answer has a 100% (1.0) overlap with the first answer.\n However, for the answers \"the river in\" and \"in Maine\" there is only a max overlap percentage of 25% so\n both of these answers could be kept if this variable is set to 0.24 or lower.\n If None is provided then all answers are kept.\n :returns:\n List of deduplicated answers.\n \"\"\"\n if overlap_threshold is None:\n return answers\n\n # Initialize with the first answer and its offsets_in_document\n deduplicated_answers = [answers[0]]\n\n # Loop over remaining answers to check for overlaps\n for ans in answers[1:]:\n keep = self._should_keep(\n candidate_answer=ans, current_answers=deduplicated_answers, overlap_threshold=overlap_threshold\n )\n if keep:\n deduplicated_answers.append(ans)\n\n return deduplicated_answers"}], "type": ["function_empty", "TDD"], "node": ["haystack.core.serialization.default_to_dict", "haystack.utils.hf.serialize_hf_model_kwargs", "haystack.components.readers.extractive.ExtractiveReader.to_dict", "haystack.components.readers.extractive.ExtractiveReader._should_keep", "haystack.components.readers.extractive.ExtractiveReader.deduplicate_by_overlap"], "language": "Python", "toolfunc_count": 4, "func_count": 5, "pytest_info": {"total_num": 34, "base_passed_num": 20}} {"id": ["haystack.haystack.core.serialization.default_to_dict", "haystack.haystack.document_stores.in_memory.document_store.InMemoryDocumentStore::to_dict"], "project": "haystack", "origin_file": ["haystack/core/serialization.py", "haystack/document_stores/in_memory/document_store.py", "haystack/components/retrievers/filter_retriever.py"], "test_list": ["test/components/retrievers/test_filter_retriever.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 264, "func_start_lineno": 172, "func_end_lineno": 210, "func_code": "def default_to_dict(obj: Any, **init_parameters) -> Dict[str, Any]:\n \"\"\"\n Utility function to serialize an object to a dictionary.\n\n This is mostly necessary for components but can be used by any object.\n `init_parameters` are parameters passed to the object class `__init__`.\n They must be defined explicitly as they'll be used when creating a new\n instance of `obj` with `from_dict`. Omitting them might cause deserialisation\n errors or unexpected behaviours later, when calling `from_dict`.\n\n An example usage:\n\n ```python\n class MyClass:\n def __init__(self, my_param: int = 10):\n self.my_param = my_param\n\n def to_dict(self):\n return default_to_dict(self, my_param=self.my_param)\n\n\n obj = MyClass(my_param=1000)\n data = obj.to_dict()\n assert data == {\n \"type\": \"MyClass\",\n \"init_parameters\": {\n \"my_param\": 1000,\n },\n }\n ```\n\n :param obj:\n The object to be serialized.\n :param init_parameters:\n The parameters used to create a new instance of the class.\n :returns:\n A dictionary representation of the instance.\n \"\"\"\n return {\"type\": generate_qualified_class_name(type(obj)), \"init_parameters\": init_parameters}"}, {"class_start_lineno": 58, "class_end_lineno": 738, "func_start_lineno": 344, "func_end_lineno": 358, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serializes the component to a dictionary.\n\n :returns:\n Dictionary with serialized data.\n \"\"\"\n return default_to_dict(\n self,\n bm25_tokenization_regex=self.bm25_tokenization_regex,\n bm25_algorithm=self.bm25_algorithm,\n bm25_parameters=self.bm25_parameters,\n embedding_similarity_function=self.embedding_similarity_function,\n index=self.index,\n )"}, {"class_start_lineno": 15, "class_end_lineno": 96, "func_start_lineno": 60, "func_end_lineno": 68, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serializes the component to a dictionary.\n\n :returns:\n Dictionary with serialized data.\n \"\"\"\n docstore = self.document_store.to_dict()\n return default_to_dict(self, document_store=docstore, filters=self.filters)"}], "type": ["function_empty"], "node": ["haystack.core.serialization.default_to_dict", "haystack.document_stores.in_memory.document_store.InMemoryDocumentStore.to_dict", "haystack.components.retrievers.filter_retriever.FilterRetriever.to_dict"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 10, "base_passed_num": 8}} {"id": ["haystack.haystack.core.serialization.default_to_dict", "haystack.haystack.document_stores.in_memory.document_store.InMemoryDocumentStore::to_dict", "haystack.haystack.components.preprocessors.document_splitter.DocumentSplitter::_split_document", "haystack.haystack.components.preprocessors.document_splitter.DocumentSplitter::run"], "project": "haystack", "origin_file": ["haystack/core/serialization.py", "haystack/document_stores/in_memory/document_store.py", "haystack/components/retrievers/sentence_window_retriever.py", "haystack/components/preprocessors/document_splitter.py", "haystack/components/preprocessors/document_splitter.py"], "test_list": ["test/components/retrievers/test_sentence_window_retriever.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 264, "func_start_lineno": 172, "func_end_lineno": 210, "func_code": "def default_to_dict(obj: Any, **init_parameters) -> Dict[str, Any]:\n \"\"\"\n Utility function to serialize an object to a dictionary.\n\n This is mostly necessary for components but can be used by any object.\n `init_parameters` are parameters passed to the object class `__init__`.\n They must be defined explicitly as they'll be used when creating a new\n instance of `obj` with `from_dict`. Omitting them might cause deserialisation\n errors or unexpected behaviours later, when calling `from_dict`.\n\n An example usage:\n\n ```python\n class MyClass:\n def __init__(self, my_param: int = 10):\n self.my_param = my_param\n\n def to_dict(self):\n return default_to_dict(self, my_param=self.my_param)\n\n\n obj = MyClass(my_param=1000)\n data = obj.to_dict()\n assert data == {\n \"type\": \"MyClass\",\n \"init_parameters\": {\n \"my_param\": 1000,\n },\n }\n ```\n\n :param obj:\n The object to be serialized.\n :param init_parameters:\n The parameters used to create a new instance of the class.\n :returns:\n A dictionary representation of the instance.\n \"\"\"\n return {\"type\": generate_qualified_class_name(type(obj)), \"init_parameters\": init_parameters}"}, {"class_start_lineno": 58, "class_end_lineno": 738, "func_start_lineno": 344, "func_end_lineno": 358, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serializes the component to a dictionary.\n\n :returns:\n Dictionary with serialized data.\n \"\"\"\n return default_to_dict(\n self,\n bm25_tokenization_regex=self.bm25_tokenization_regex,\n bm25_algorithm=self.bm25_algorithm,\n bm25_parameters=self.bm25_parameters,\n embedding_similarity_function=self.embedding_similarity_function,\n index=self.index,\n )"}, {"class_start_lineno": 13, "class_end_lineno": 198, "func_start_lineno": 122, "func_end_lineno": 130, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serializes the component to a dictionary.\n\n :returns:\n Dictionary with serialized data.\n \"\"\"\n docstore = self.document_store.to_dict()\n return default_to_dict(self, document_store=docstore, window_size=self.window_size)"}, {"class_start_lineno": 22, "class_end_lineno": 490, "func_start_lineno": 204, "func_end_lineno": 211, "func_code": " def _split_document(self, doc: Document) -> List[Document]:\n if self.split_by == \"sentence\" or self.respect_sentence_boundary:\n return self._split_by_nltk_sentence(doc)\n\n if self.split_by == \"function\" and self.splitting_function is not None:\n return self._split_by_function(doc)\n\n return self._split_by_character(doc)"}, {"class_start_lineno": 22, "class_end_lineno": 490, "func_start_lineno": 166, "func_end_lineno": 202, "func_code": " def run(self, documents: List[Document]):\n \"\"\"\n Split documents into smaller parts.\n\n Splits documents by the unit expressed in `split_by`, with a length of `split_length`\n and an overlap of `split_overlap`.\n\n :param documents: The documents to split.\n :returns: A dictionary with the following key:\n - `documents`: List of documents with the split texts. Each document includes:\n - A metadata field `source_id` to track the original document.\n - A metadata field `page_number` to track the original page number.\n - All other metadata copied from the original document.\n\n :raises TypeError: if the input is not a list of Documents.\n :raises ValueError: if the content of a document is None.\n \"\"\"\n if self._use_sentence_splitter and self.sentence_splitter is None:\n raise RuntimeError(\n \"The component DocumentSplitter wasn't warmed up. Run 'warm_up()' before calling 'run()'.\"\n )\n\n if not isinstance(documents, list) or (documents and not isinstance(documents[0], Document)):\n raise TypeError(\"DocumentSplitter expects a List of Documents as input.\")\n\n split_docs: List[Document] = []\n for doc in documents:\n if doc.content is None:\n raise ValueError(\n f\"DocumentSplitter only works with text documents but content for document ID {doc.id} is None.\"\n )\n if doc.content == \"\":\n logger.warning(\"Document ID {doc_id} has an empty content. Skipping this document.\", doc_id=doc.id)\n continue\n\n split_docs += self._split_document(doc)\n return {\"documents\": split_docs}"}], "type": ["function_empty", "TDD"], "node": ["haystack.core.serialization.default_to_dict", "haystack.document_stores.in_memory.document_store.InMemoryDocumentStore.to_dict", "haystack.components.retrievers.sentence_window_retriever.SentenceWindowRetriever.to_dict", "haystack.components.preprocessors.document_splitter.DocumentSplitter._split_document", "haystack.components.preprocessors.document_splitter.DocumentSplitter.run"], "language": "Python", "toolfunc_count": 3, "func_count": 4, "pytest_info": {"total_num": 16, "base_passed_num": 13}} {"id": ["haystack.haystack.components.routers.conditional_router.ConditionalRouter::_validate_template", "haystack.haystack.components.routers.conditional_router.ConditionalRouter::_validate_routes", "haystack.haystack.utils.type_serialization.serialize_type", "haystack.haystack.components.routers.conditional_router.ConditionalRouter::to_dict"], "project": "haystack", "origin_file": ["haystack/components/routers/conditional_router.py", "haystack/components/routers/conditional_router.py", "haystack/utils/type_serialization.py", "haystack/components/routers/conditional_router.py"], "test_list": ["test/components/routers/test_conditional_router.py"], "prob_info": [{"class_start_lineno": 29, "class_end_lineno": 433, "func_start_lineno": 371, "func_end_lineno": 383, "func_code": " def _validate_template(self, env: Environment, template_text: str):\n \"\"\"\n Validates a template string by parsing it with Jinja.\n\n :param env: A Jinja environment.\n :param template_text: A Jinja template string.\n :returns: `True` if the template is valid, `False` otherwise.\n \"\"\"\n try:\n env.parse(template_text)\n return True\n except TemplateSyntaxError:\n return False"}, {"class_start_lineno": 29, "class_end_lineno": 433, "func_start_lineno": 335, "func_end_lineno": 355, "func_code": " def _validate_routes(self, routes: List[Dict]):\n \"\"\"\n Validates a list of routes.\n\n :param routes: A list of routes.\n \"\"\"\n for route in routes:\n try:\n keys = set(route.keys())\n except AttributeError:\n raise ValueError(f\"Route must be a dictionary, got: {route}\")\n\n mandatory_fields = {\"condition\", \"output\", \"output_type\", \"output_name\"}\n has_all_mandatory_fields = mandatory_fields.issubset(keys)\n if not has_all_mandatory_fields:\n raise ValueError(\n f\"Route must contain 'condition', 'output', 'output_type' and 'output_name' fields: {route}\"\n )\n for field in [\"condition\", \"output\"]:\n if not self._validate_template(self._env, route[field]):\n raise ValueError(f\"Invalid template for field '{field}': {route[field]}\")"}, {"class_start_lineno": 1, "class_end_lineno": 170, "func_start_lineno": 19, "func_end_lineno": 52, "func_code": "def serialize_type(target: Any) -> str:\n \"\"\"\n Serializes a type or an instance to its string representation, including the module name.\n\n This function handles types, instances of types, and special typing objects.\n It assumes that non-typing objects will have a '__name__' attribute.\n\n :param target:\n The object to serialize, can be an instance or a type.\n :return:\n The string representation of the type.\n \"\"\"\n name = getattr(target, \"__name__\", str(target))\n\n # Remove the 'typing.' prefix when using python <3.9\n if name.startswith(\"typing.\"):\n name = name[7:]\n # Remove the arguments from the name when using python <3.9\n if \"[\" in name:\n name = name.split(\"[\")[0]\n\n # Get module name\n module = inspect.getmodule(target)\n module_name = \"\"\n # We omit the module name for builtins to not clutter the output\n if module and hasattr(module, \"__name__\") and module.__name__ != \"builtins\":\n module_name = f\"{module.__name__}\"\n\n args = get_args(target)\n if args:\n args_str = \", \".join([serialize_type(a) for a in args if a is not type(None)])\n return f\"{module_name}.{name}[{args_str}]\" if module_name else f\"{name}[{args_str}]\"\n\n return f\"{module_name}.{name}\" if module_name else f\"{name}\""}, {"class_start_lineno": 29, "class_end_lineno": 433, "func_start_lineno": 237, "func_end_lineno": 256, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serializes the component to a dictionary.\n\n :returns:\n Dictionary with serialized data.\n \"\"\"\n serialized_routes = []\n for route in self.routes:\n # output_type needs to be serialized to a string\n serialized_routes.append({**route, \"output_type\": serialize_type(route[\"output_type\"])})\n se_filters = {name: serialize_callable(filter_func) for name, filter_func in self.custom_filters.items()}\n return default_to_dict(\n self,\n routes=serialized_routes,\n custom_filters=se_filters,\n unsafe=self._unsafe,\n validate_output_type=self._validate_output_type,\n optional_variables=self.optional_variables,\n )"}], "type": ["function_empty"], "node": ["haystack.components.routers.conditional_router.ConditionalRouter._validate_template", "haystack.components.routers.conditional_router.ConditionalRouter._validate_routes", "haystack.utils.type_serialization.serialize_type", "haystack.components.routers.conditional_router.ConditionalRouter.to_dict"], "language": "Python", "toolfunc_count": 4, "func_count": 4, "pytest_info": {"total_num": 23, "base_passed_num": 15}} {"id": ["haystack.haystack.components.samplers.top_p.TopPSampler::_get_documents_and_scores", "haystack.haystack.components.samplers.top_p.TopPSampler::run"], "project": "haystack", "origin_file": ["haystack/components/samplers/top_p.py", "haystack/components/samplers/top_p.py"], "test_list": ["test/components/samplers/test_top_p.py"], "prob_info": [{"class_start_lineno": 18, "class_end_lineno": 177, "func_start_lineno": 144, "func_end_lineno": 177, "func_code": " def _get_documents_and_scores(self, documents: List[Document]) -> Tuple[List[Document], List[float]]:\n \"\"\"\n Checks if documents have scores in their metadata or score field and returns the documents with scores.\n\n :param documents: List of Documents.\n :return: List of scores.\n \"\"\"\n docs_with_scores = []\n scores = []\n docs_missing_scores = []\n for doc in documents:\n score = self._get_doc_score(doc=doc, score_field=self.score_field)\n if score is None:\n docs_missing_scores.append(doc)\n else:\n scores.append(score)\n docs_with_scores.append(doc)\n\n if len(docs_missing_scores) > 0:\n missing_scores_docs_ids = [d.id for d in docs_missing_scores if d.id]\n if self.score_field:\n logger.warning(\n \"Score field '{score_field}' not found in metadata of documents with IDs: {doc_ids}.\"\n \"Make sure that all documents have a score field '{score_field_2}' in their metadata.\",\n score_field=self.score_field,\n doc_ids=\",\".join(missing_scores_docs_ids),\n score_field_2=self.score_field,\n )\n else:\n logger.warning(\n \"Ensure all documents have a valid score value. These documents {doc_ids} are missing scores.\",\n doc_ids=\",\".join(missing_scores_docs_ids),\n )\n return docs_with_scores, scores"}, {"class_start_lineno": 18, "class_end_lineno": 177, "func_start_lineno": 65, "func_end_lineno": 122, "func_code": " def run(self, documents: List[Document], top_p: Optional[float] = None):\n \"\"\"\n Filters documents using top-p sampling based on their scores.\n\n If the specified top_p results in no documents being selected (especially in cases of a low top_p value), the\n method returns the document with the highest score.\n\n :param documents: List of Document objects to be filtered.\n :param top_p: If specified, a float to override the cumulative probability threshold set during initialization.\n\n :returns: A dictionary with the following key:\n - `documents`: List of Document objects that have been selected based on the top-p sampling.\n :raises ValueError: If the top_p value is not within the range [0, 1].\n \"\"\"\n if not documents:\n return {\"documents\": []}\n\n top_p = top_p or self.top_p\n if not 0 <= top_p <= 1:\n raise ValueError(f\"top_p must be between 0 and 1. Got {top_p}.\")\n\n documents_with_scores, scores = self._get_documents_and_scores(documents)\n if len(documents_with_scores) == 0:\n logger.warning(\"No documents with scores found. Returning the original documents.\")\n return {\"documents\": documents}\n\n sorted_docs_with_scores = sorted(zip(documents_with_scores, scores), key=lambda x: x[1], reverse=True)\n sorted_documents, sorted_scores = [list(t) for t in zip(*sorted_docs_with_scores)]\n\n tensor_scores = torch.tensor(sorted_scores, dtype=torch.float32)\n probs = torch.nn.functional.softmax(tensor_scores, dim=-1)\n cumulative_probs = torch.cumsum(probs, dim=-1)\n\n # Check if the cumulative probabilities are close to top_p with a 1e-6 tolerance\n close_to_top_p = torch.isclose(cumulative_probs, torch.tensor(top_p, device=cumulative_probs.device), atol=1e-6)\n\n # Combine the close_to_top_p with original condition using logical OR\n condition = (cumulative_probs <= top_p) | close_to_top_p\n\n # Find the indices with cumulative probabilities that exceed top_p\n top_p_indices = torch.where(torch.BoolTensor(condition))[0]\n\n # Map the selected indices back to their original indices\n selected_docs = [sorted_documents[i.item()] for i in top_p_indices]\n\n if self.min_top_k and len(selected_docs) < self.min_top_k:\n selected_docs = sorted_documents[: self.min_top_k]\n\n # If low p resulted in no documents being selected, then return at least one document\n if len(selected_docs) == 0:\n logger.warning(\n \"Top-p sampling with p={top_p} resulted in no documents being selected. \"\n \"Returning the document with the highest score.\",\n top_p=top_p,\n )\n selected_docs = [sorted_documents[0]]\n\n return {\"documents\": selected_docs}"}], "type": ["function_empty"], "node": ["haystack.components.samplers.top_p.TopPSampler._get_documents_and_scores", "haystack.components.samplers.top_p.TopPSampler.run"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 11, "base_passed_num": 1}} {"id": ["haystack.haystack.dataclasses.chat_message.ChatMessage::__getattribute__", "haystack.haystack.components.tools.tool_invoker.ToolInvoker::run", "haystack.haystack.core.type_utils._strict_types_are_compatible", "haystack.haystack.core.type_utils._types_are_compatible"], "project": "haystack", "origin_file": ["haystack/dataclasses/chat_message.py", "haystack/components/tools/tool_invoker.py", "haystack/dataclasses/chat_message.py", "haystack/dataclasses/chat_message.py", "haystack/dataclasses/chat_message.py", "haystack/core/type_utils.py", "haystack/core/type_utils.py"], "test_list": ["test/components/tools/test_tool_invoker.py"], "prob_info": [{"class_start_lineno": 88, "class_end_lineno": 481, "func_start_lineno": 127, "func_end_lineno": 140, "func_code": " def __getattribute__(self, name):\n \"\"\"\n This method is reimplemented to make the `content` attribute removal more visible.\n \"\"\"\n\n if name == \"content\":\n msg = (\n \"The `content` attribute of `ChatMessage` has been removed. \"\n \"Use the `text` property to access the textual value. \"\n \"For more information about the new API and how to migrate, see the documentation: \"\n \"https://docs.haystack.deepset.ai/docs/chatmessage\"\n )\n raise AttributeError(msg)\n return object.__getattribute__(self, name)"}, {"class_start_lineno": 38, "class_end_lineno": 242, "func_start_lineno": 166, "func_end_lineno": 214, "func_code": " def run(self, messages: List[ChatMessage]) -> Dict[str, Any]:\n \"\"\"\n Processes ChatMessage objects containing tool calls and invokes the corresponding tools, if available.\n\n :param messages:\n A list of ChatMessage objects.\n :returns:\n A dictionary with the key `tool_messages` containing a list of ChatMessage objects with tool role.\n Each ChatMessage objects wraps the result of a tool invocation.\n\n :raises ToolNotFoundException:\n If the tool is not found in the list of available tools and `raise_on_failure` is True.\n :raises ToolInvocationError:\n If the tool invocation fails and `raise_on_failure` is True.\n :raises StringConversionError:\n If the conversion of the tool result to a string fails and `raise_on_failure` is True.\n \"\"\"\n tool_messages = []\n\n for message in messages:\n tool_calls = message.tool_calls\n if not tool_calls:\n continue\n\n for tool_call in tool_calls:\n tool_name = tool_call.tool_name\n tool_arguments = tool_call.arguments\n\n if not tool_name in self._tools_with_names:\n msg = _TOOL_NOT_FOUND.format(tool_name=tool_name, available_tools=self._tools_with_names.keys())\n if self.raise_on_failure:\n raise ToolNotFoundException(msg)\n tool_messages.append(ChatMessage.from_tool(tool_result=msg, origin=tool_call, error=True))\n continue\n\n tool_to_invoke = self._tools_with_names[tool_name]\n try:\n tool_result = tool_to_invoke.invoke(**tool_arguments)\n except ToolInvocationError as e:\n if self.raise_on_failure:\n raise e\n msg = _TOOL_INVOCATION_FAILURE.format(error=e)\n tool_messages.append(ChatMessage.from_tool(tool_result=msg, origin=tool_call, error=True))\n continue\n\n tool_message = self._prepare_tool_result_message(tool_result, tool_call)\n tool_messages.append(tool_message)\n\n return {\"tool_messages\": tool_messages}"}, {"class_start_lineno": 88, "class_end_lineno": 481, "func_start_lineno": 183, "func_end_lineno": 187, "func_code": " def tool_calls(self) -> List[ToolCall]:\n \"\"\"\n Returns the list of all Tool calls contained in the message.\n \"\"\"\n return [content for content in self._content if isinstance(content, ToolCall)]"}, {"class_start_lineno": 88, "class_end_lineno": 481, "func_start_lineno": 199, "func_end_lineno": 203, "func_code": " def tool_call_results(self) -> List[ToolCallResult]:\n \"\"\"\n Returns the list of all Tool call results contained in the message.\n \"\"\"\n return [content for content in self._content if isinstance(content, ToolCallResult)]"}, {"class_start_lineno": 88, "class_end_lineno": 481, "func_start_lineno": 206, "func_end_lineno": 212, "func_code": " def tool_call_result(self) -> Optional[ToolCallResult]:\n \"\"\"\n Returns the first Tool call result contained in the message.\n \"\"\"\n if tool_call_results := self.tool_call_results:\n return tool_call_results[0]\n return None"}, {"class_start_lineno": 1, "class_end_lineno": 105, "func_start_lineno": 29, "func_end_lineno": 76, "func_code": "def _strict_types_are_compatible(sender, receiver): # pylint: disable=too-many-return-statements\n \"\"\"\n Checks whether the sender type is equal to or a subtype of the receiver type under strict validation.\n\n Note: this method has no pretense to perform proper type matching. It especially does not deal with aliasing of\n typing classes such as `List` or `Dict` to their runtime counterparts `list` and `dict`. It also does not deal well\n with \"bare\" types, so `List` is treated differently from `List[Any]`, even though they should be the same.\n Consider simplifying the typing of your components if you observe unexpected errors during component connection.\n\n :param sender: The sender type.\n :param receiver: The receiver type.\n :return: True if the sender type is strictly compatible with the receiver type, False otherwise.\n \"\"\"\n if sender == receiver or receiver is Any:\n return True\n\n if sender is Any:\n return False\n\n try:\n if issubclass(sender, receiver):\n return True\n except TypeError: # typing classes can't be used with issubclass, so we deal with them below\n pass\n\n sender_origin = get_origin(sender)\n receiver_origin = get_origin(receiver)\n\n if sender_origin is not Union and receiver_origin is Union:\n return any(_strict_types_are_compatible(sender, union_arg) for union_arg in get_args(receiver))\n\n # Both must have origins and they must be equal\n if not (sender_origin and receiver_origin and sender_origin == receiver_origin):\n return False\n\n # Compare generic type arguments\n sender_args = get_args(sender)\n receiver_args = get_args(receiver)\n\n # Handle bare types\n if not sender_args and sender_origin:\n sender_args = (Any,)\n if not receiver_args and receiver_origin:\n receiver_args = (Any,) * (len(sender_args) if sender_args else 1)\n if len(sender_args) > len(receiver_args):\n return False\n\n return all(_strict_types_are_compatible(*args) for args in zip(sender_args, receiver_args))"}, {"class_start_lineno": 1, "class_end_lineno": 105, "func_start_lineno": 14, "func_end_lineno": 26, "func_code": "def _types_are_compatible(sender, receiver, type_validation: bool = True) -> bool:\n \"\"\"\n Determines if two types are compatible based on the specified validation mode.\n\n :param sender: The sender type.\n :param receiver: The receiver type.\n :param type_validation: Whether to perform strict type validation.\n :return: True if the types are compatible, False otherwise.\n \"\"\"\n if type_validation:\n return _strict_types_are_compatible(sender, receiver)\n else:\n return True"}], "type": ["function_empty", "TDD"], "node": ["haystack.dataclasses.chat_message.ChatMessage.__getattribute__", "haystack.components.tools.tool_invoker.ToolInvoker.run", "haystack.dataclasses.chat_message.ChatMessage.tool_calls", "haystack.dataclasses.chat_message.ChatMessage.tool_call_results", "haystack.dataclasses.chat_message.ChatMessage.tool_call_result", "haystack.core.type_utils._strict_types_are_compatible", "haystack.core.type_utils._types_are_compatible"], "language": "Python", "toolfunc_count": 3, "func_count": 4, "pytest_info": {"total_num": 16, "base_passed_num": 6}} {"id": ["haystack.haystack.dataclasses.chat_message.ChatMessage::__getattribute__", "haystack.haystack.components.validators.json_schema.JsonSchemaValidator::run", "haystack.haystack.core.type_utils._strict_types_are_compatible", "haystack.haystack.core.type_utils._types_are_compatible"], "project": "haystack", "origin_file": ["haystack/dataclasses/chat_message.py", "haystack/components/validators/json_schema.py", "haystack/dataclasses/chat_message.py", "haystack/dataclasses/chat_message.py", "haystack/core/type_utils.py", "haystack/core/type_utils.py"], "test_list": ["test/components/validators/test_json_schema.py"], "prob_info": [{"class_start_lineno": 88, "class_end_lineno": 481, "func_start_lineno": 127, "func_end_lineno": 140, "func_code": " def __getattribute__(self, name):\n \"\"\"\n This method is reimplemented to make the `content` attribute removal more visible.\n \"\"\"\n\n if name == \"content\":\n msg = (\n \"The `content` attribute of `ChatMessage` has been removed. \"\n \"Use the `text` property to access the textual value. \"\n \"For more information about the new API and how to migrate, see the documentation: \"\n \"https://docs.haystack.deepset.ai/docs/chatmessage\"\n )\n raise AttributeError(msg)\n return object.__getattribute__(self, name)"}, {"class_start_lineno": 29, "class_end_lineno": 257, "func_start_lineno": 115, "func_end_lineno": 186, "func_code": " def run(\n self,\n messages: List[ChatMessage],\n json_schema: Optional[Dict[str, Any]] = None,\n error_template: Optional[str] = None,\n ) -> Dict[str, List[ChatMessage]]:\n \"\"\"\n Validates the last of the provided messages against the specified json schema.\n\n If it does, the message is passed along the \"validated\" output. If it does not, the message is passed along\n the \"validation_error\" output.\n\n :param messages: A list of ChatMessage instances to be validated. The last message in this list is the one\n that is validated.\n :param json_schema: A dictionary representing the [JSON schema](https://json-schema.org/)\n against which the messages' content is validated. If not provided, the schema from the component init\n is used.\n :param error_template: A custom template string for formatting the error message in case of validation. If not\n provided, the `error_template` from the component init is used.\n :return: A dictionary with the following keys:\n - \"validated\": A list of messages if the last message is valid.\n - \"validation_error\": A list of messages if the last message is invalid.\n :raises ValueError: If no JSON schema is provided or if the message content is not a dictionary or a list of\n dictionaries.\n \"\"\"\n last_message = messages[-1]\n if last_message.text is None:\n raise ValueError(f\"The provided ChatMessage has no text. ChatMessage: {last_message}\")\n if not is_valid_json(last_message.text):\n return {\n \"validation_error\": [\n ChatMessage.from_user(\n f\"The message '{last_message.text}' is not a valid JSON object. \"\n f\"Please provide only a valid JSON object in string format.\"\n f\"Don't use any markdown and don't add any comment.\"\n )\n ]\n }\n\n last_message_content = json.loads(last_message.text)\n json_schema = json_schema or self.json_schema\n error_template = error_template or self.error_template or self.default_error_template\n\n if not json_schema:\n raise ValueError(\"Provide a JSON schema for validation either in the run method or in the component init.\")\n # fc payload is json object but subtree `parameters` is string - we need to convert to json object\n # we need complete json to validate it against schema\n last_message_json = self._recursive_json_to_object(last_message_content)\n using_openai_schema: bool = self._is_openai_function_calling_schema(json_schema)\n if using_openai_schema:\n validation_schema = json_schema[\"parameters\"]\n else:\n validation_schema = json_schema\n try:\n last_message_json = [last_message_json] if not isinstance(last_message_json, list) else last_message_json\n for content in last_message_json:\n if using_openai_schema:\n validate(instance=content[\"function\"][\"arguments\"], schema=validation_schema)\n else:\n validate(instance=content, schema=validation_schema)\n\n return {\"validated\": [last_message]}\n except ValidationError as e:\n error_path = \" -> \".join(map(str, e.absolute_path)) if e.absolute_path else \"N/A\"\n error_schema_path = \" -> \".join(map(str, e.absolute_schema_path)) if e.absolute_schema_path else \"N/A\"\n\n error_template = error_template or self.default_error_template\n\n recovery_prompt = self._construct_error_recovery_message(\n error_template, str(e), error_path, error_schema_path, validation_schema, failing_json=last_message.text\n )\n return {\"validation_error\": [ChatMessage.from_user(recovery_prompt)]}"}, {"class_start_lineno": 88, "class_end_lineno": 481, "func_start_lineno": 167, "func_end_lineno": 171, "func_code": " def texts(self) -> List[str]:\n \"\"\"\n Returns the list of all texts contained in the message.\n \"\"\"\n return [content.text for content in self._content if isinstance(content, TextContent)]"}, {"class_start_lineno": 88, "class_end_lineno": 481, "func_start_lineno": 174, "func_end_lineno": 180, "func_code": " def text(self) -> Optional[str]:\n \"\"\"\n Returns the first text contained in the message.\n \"\"\"\n if texts := self.texts:\n return texts[0]\n return None"}, {"class_start_lineno": 1, "class_end_lineno": 105, "func_start_lineno": 29, "func_end_lineno": 76, "func_code": "def _strict_types_are_compatible(sender, receiver): # pylint: disable=too-many-return-statements\n \"\"\"\n Checks whether the sender type is equal to or a subtype of the receiver type under strict validation.\n\n Note: this method has no pretense to perform proper type matching. It especially does not deal with aliasing of\n typing classes such as `List` or `Dict` to their runtime counterparts `list` and `dict`. It also does not deal well\n with \"bare\" types, so `List` is treated differently from `List[Any]`, even though they should be the same.\n Consider simplifying the typing of your components if you observe unexpected errors during component connection.\n\n :param sender: The sender type.\n :param receiver: The receiver type.\n :return: True if the sender type is strictly compatible with the receiver type, False otherwise.\n \"\"\"\n if sender == receiver or receiver is Any:\n return True\n\n if sender is Any:\n return False\n\n try:\n if issubclass(sender, receiver):\n return True\n except TypeError: # typing classes can't be used with issubclass, so we deal with them below\n pass\n\n sender_origin = get_origin(sender)\n receiver_origin = get_origin(receiver)\n\n if sender_origin is not Union and receiver_origin is Union:\n return any(_strict_types_are_compatible(sender, union_arg) for union_arg in get_args(receiver))\n\n # Both must have origins and they must be equal\n if not (sender_origin and receiver_origin and sender_origin == receiver_origin):\n return False\n\n # Compare generic type arguments\n sender_args = get_args(sender)\n receiver_args = get_args(receiver)\n\n # Handle bare types\n if not sender_args and sender_origin:\n sender_args = (Any,)\n if not receiver_args and receiver_origin:\n receiver_args = (Any,) * (len(sender_args) if sender_args else 1)\n if len(sender_args) > len(receiver_args):\n return False\n\n return all(_strict_types_are_compatible(*args) for args in zip(sender_args, receiver_args))"}, {"class_start_lineno": 1, "class_end_lineno": 105, "func_start_lineno": 14, "func_end_lineno": 26, "func_code": "def _types_are_compatible(sender, receiver, type_validation: bool = True) -> bool:\n \"\"\"\n Determines if two types are compatible based on the specified validation mode.\n\n :param sender: The sender type.\n :param receiver: The receiver type.\n :param type_validation: Whether to perform strict type validation.\n :return: True if the types are compatible, False otherwise.\n \"\"\"\n if type_validation:\n return _strict_types_are_compatible(sender, receiver)\n else:\n return True"}], "type": ["function_empty", "TDD"], "node": ["haystack.dataclasses.chat_message.ChatMessage.__getattribute__", "haystack.components.validators.json_schema.JsonSchemaValidator.run", "haystack.dataclasses.chat_message.ChatMessage.texts", "haystack.dataclasses.chat_message.ChatMessage.text", "haystack.core.type_utils._strict_types_are_compatible", "haystack.core.type_utils._types_are_compatible"], "language": "Python", "toolfunc_count": 3, "func_count": 4, "pytest_info": {"total_num": 8, "base_passed_num": 2}} {"id": ["haystack.haystack.document_stores.in_memory.document_store.InMemoryDocumentStore::write_documents", "haystack.haystack.components.writers.document_writer.DocumentWriter::run"], "project": "haystack", "origin_file": ["haystack/document_stores/in_memory/document_store.py", "haystack/components/writers/document_writer.py"], "test_list": ["test/components/writers/test_document_writer.py"], "prob_info": [{"class_start_lineno": 58, "class_end_lineno": 738, "func_start_lineno": 432, "func_end_lineno": 473, "func_code": " def write_documents(self, documents: List[Document], policy: DuplicatePolicy = DuplicatePolicy.NONE) -> int:\n \"\"\"\n Refer to the DocumentStore.write_documents() protocol documentation.\n\n If `policy` is set to `DuplicatePolicy.NONE` defaults to `DuplicatePolicy.FAIL`.\n \"\"\"\n if (\n not isinstance(documents, Iterable)\n or isinstance(documents, str)\n or any(not isinstance(doc, Document) for doc in documents)\n ):\n raise ValueError(\"Please provide a list of Documents.\")\n\n if policy == DuplicatePolicy.NONE:\n policy = DuplicatePolicy.FAIL\n\n written_documents = len(documents)\n for document in documents:\n if policy != DuplicatePolicy.OVERWRITE and document.id in self.storage.keys():\n if policy == DuplicatePolicy.FAIL:\n raise DuplicateDocumentError(f\"ID '{document.id}' already exists.\")\n if policy == DuplicatePolicy.SKIP:\n logger.warning(\"ID '{document_id}' already exists\", document_id=document.id)\n written_documents -= 1\n continue\n\n # Since the statistics are updated in an incremental manner,\n # we need to explicitly remove the existing document to revert\n # the statistics before updating them with the new document.\n if document.id in self.storage.keys():\n self.delete_documents([document.id])\n\n tokens = []\n if document.content is not None:\n tokens = self._tokenize_bm25(document.content)\n\n self.storage[document.id] = document\n\n self._bm25_attr[document.id] = BM25DocumentStats(Counter(tokens), len(tokens))\n self._freq_vocab_for_idf.update(set(tokens))\n self._avg_doc_len = (len(tokens) + self._avg_doc_len * len(self._bm25_attr)) / (len(self._bm25_attr) + 1)\n return written_documents"}, {"class_start_lineno": 15, "class_end_lineno": 134, "func_start_lineno": 85, "func_end_lineno": 103, "func_code": " def run(self, documents: List[Document], policy: Optional[DuplicatePolicy] = None):\n \"\"\"\n Run the DocumentWriter on the given input data.\n\n :param documents:\n A list of documents to write to the document store.\n :param policy:\n The policy to use when encountering duplicate documents.\n :returns:\n Number of documents written to the document store.\n\n :raises ValueError:\n If the specified document store is not found.\n \"\"\"\n if policy is None:\n policy = self.policy\n\n documents_written = self.document_store.write_documents(documents=documents, policy=policy)\n return {\"documents_written\": documents_written}"}], "type": ["function_empty"], "node": ["haystack.document_stores.in_memory.document_store.InMemoryDocumentStore.write_documents", "haystack.components.writers.document_writer.DocumentWriter.run"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 11, "base_passed_num": 7}} {"id": ["haystack.haystack.core.pipeline.component_checks.are_all_sockets_ready", "haystack.haystack.core.pipeline.component_checks.has_lazy_variadic_socket_received_all_inputs", "haystack.haystack.core.pipeline.component_checks.has_socket_received_all_inputs", "haystack.haystack.core.pipeline.component_checks.can_component_run"], "project": "haystack", "origin_file": ["haystack/core/pipeline/component_checks.py", "haystack/core/pipeline/component_checks.py", "haystack/core/pipeline/component_checks.py", "haystack/core/pipeline/component_checks.py"], "test_list": ["test/core/pipeline/test_component_checks.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 251, "func_start_lineno": 52, "func_end_lineno": 83, "func_code": "def are_all_sockets_ready(component: Dict, inputs: Dict, only_check_mandatory: bool = False) -> bool:\n \"\"\"\n Checks if all sockets of a component have enough inputs for the component to execute.\n\n :param component: Component metadata and the component instance.\n :param inputs: Inputs for the component.\n :param only_check_mandatory: If only mandatory sockets should be checked.\n \"\"\"\n filled_sockets = set()\n expected_sockets = set()\n if only_check_mandatory:\n sockets_to_check = {\n socket_name: socket for socket_name, socket in component[\"input_sockets\"].items() if socket.is_mandatory\n }\n else:\n sockets_to_check = {\n socket_name: socket\n for socket_name, socket in component[\"input_sockets\"].items()\n if socket.is_mandatory or len(socket.senders)\n }\n\n for socket_name, socket in sockets_to_check.items():\n socket_inputs = inputs.get(socket_name, [])\n expected_sockets.add(socket_name)\n\n # Check if socket has all required inputs or is a lazy variadic socket with any input\n if has_socket_received_all_inputs(socket, socket_inputs) or (\n is_socket_lazy_variadic(socket) and any_socket_input_received(socket_inputs)\n ):\n filled_sockets.add(socket_name)\n\n return filled_sockets == expected_sockets"}, {"class_start_lineno": 1, "class_end_lineno": 251, "func_start_lineno": 149, "func_end_lineno": 163, "func_code": "def has_lazy_variadic_socket_received_all_inputs(socket: InputSocket, socket_inputs: List[Dict]) -> bool:\n \"\"\"\n Checks if a lazy variadic socket has received all expected inputs from other components in the pipeline.\n\n :param socket: The InputSocket of a component.\n :param socket_inputs: Inputs for the socket.\n \"\"\"\n expected_senders = set(socket.senders)\n actual_senders = {\n sock[\"sender\"]\n for sock in socket_inputs\n if sock[\"value\"] is not _NO_OUTPUT_PRODUCED and sock[\"sender\"] is not None\n }\n\n return expected_senders == actual_senders"}, {"class_start_lineno": 1, "class_end_lineno": 251, "func_start_lineno": 175, "func_end_lineno": 199, "func_code": "def has_socket_received_all_inputs(socket: InputSocket, socket_inputs: List[Dict]) -> bool:\n \"\"\"\n Checks if a socket has received all expected inputs.\n\n :param socket: The InputSocket of a component.\n :param socket_inputs: Inputs for the socket.\n \"\"\"\n # No inputs received for the socket, it is not filled.\n if len(socket_inputs) == 0:\n return False\n\n # The socket is greedy variadic and at least one input was produced, it is complete.\n if (\n socket.is_variadic\n and socket.is_greedy\n and any(sock[\"value\"] is not _NO_OUTPUT_PRODUCED for sock in socket_inputs)\n ):\n return True\n\n # The socket is lazy variadic and all expected inputs were produced.\n if is_socket_lazy_variadic(socket) and has_lazy_variadic_socket_received_all_inputs(socket, socket_inputs):\n return True\n\n # The socket is not variadic and the only expected input is complete.\n return not socket.is_variadic and socket_inputs[0][\"value\"] is not _NO_OUTPUT_PRODUCED"}, {"class_start_lineno": 1, "class_end_lineno": 251, "func_start_lineno": 12, "func_end_lineno": 25, "func_code": "def can_component_run(component: Dict, inputs: Dict) -> bool:\n \"\"\"\n Checks if the component can run, given the current state of its inputs.\n\n A component needs to pass two gates so that it is ready to run:\n 1. It has received all mandatory inputs.\n 2. It has received a trigger.\n :param component: Component metadata and the component instance.\n :param inputs: Inputs for the component.\n \"\"\"\n received_all_mandatory_inputs = are_all_sockets_ready(component, inputs, only_check_mandatory=True)\n received_trigger = has_any_trigger(component, inputs)\n\n return received_all_mandatory_inputs and received_trigger"}], "type": ["function_empty"], "node": ["haystack.core.pipeline.component_checks.are_all_sockets_ready", "haystack.core.pipeline.component_checks.has_lazy_variadic_socket_received_all_inputs", "haystack.core.pipeline.component_checks.has_socket_received_all_inputs", "haystack.core.pipeline.component_checks.can_component_run"], "language": "Python", "toolfunc_count": 4, "func_count": 4, "pytest_info": {"total_num": 78, "base_passed_num": 44}} {"id": ["haystack.haystack.dataclasses.document.Document::to_dict", "haystack.haystack.dataclasses.answer.ExtractedAnswer::to_dict"], "project": "haystack", "origin_file": ["haystack/dataclasses/document.py", "haystack/dataclasses/answer.py"], "test_list": ["test/dataclasses/test_answer.py"], "prob_info": [{"class_start_lineno": 49, "class_end_lineno": 186, "func_start_lineno": 123, "func_end_lineno": 140, "func_code": " def to_dict(self, flatten=True) -> Dict[str, Any]:\n \"\"\"\n Converts Document into a dictionary.\n\n `blob` field is converted to a JSON-serializable type.\n\n :param flatten:\n Whether to flatten `meta` field or not. Defaults to `True` to be backward-compatible with Haystack 1.x.\n \"\"\"\n data = asdict(self)\n if (blob := data.get(\"blob\")) is not None:\n data[\"blob\"] = {\"data\": list(blob[\"data\"]), \"mime_type\": blob[\"mime_type\"]}\n\n if flatten:\n meta = data.pop(\"meta\")\n return {**data, **meta}\n\n return data"}, {"class_start_lineno": 28, "class_end_lineno": 84, "func_start_lineno": 43, "func_end_lineno": 63, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Serialize the object to a dictionary.\n\n :returns:\n Serialized dictionary representation of the object.\n \"\"\"\n document = self.document.to_dict(flatten=False) if self.document is not None else None\n document_offset = asdict(self.document_offset) if self.document_offset is not None else None\n context_offset = asdict(self.context_offset) if self.context_offset is not None else None\n return default_to_dict(\n self,\n data=self.data,\n query=self.query,\n document=document,\n context=self.context,\n score=self.score,\n document_offset=document_offset,\n context_offset=context_offset,\n meta=self.meta,\n )"}], "type": ["function_empty"], "node": ["haystack.dataclasses.document.Document.to_dict", "haystack.dataclasses.answer.ExtractedAnswer.to_dict"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 8, "base_passed_num": 7}} {"id": ["haystack.haystack.dataclasses.chat_message.ChatMessage::__getattribute__", "haystack.haystack.dataclasses.chat_message.ChatMessage::to_dict", "haystack.haystack.dataclasses.chat_message.ChatMessage::to_openai_dict_format"], "project": "haystack", "origin_file": ["haystack/dataclasses/chat_message.py", "haystack/dataclasses/chat_message.py", "haystack/dataclasses/chat_message.py", "haystack/dataclasses/chat_message.py", "haystack/dataclasses/chat_message.py", "haystack/dataclasses/chat_message.py", "haystack/dataclasses/chat_message.py", "haystack/dataclasses/chat_message.py", "haystack/dataclasses/chat_message.py", "haystack/dataclasses/chat_message.py", "haystack/dataclasses/chat_message.py"], "test_list": ["test/dataclasses/test_chat_message.py"], "prob_info": [{"class_start_lineno": 88, "class_end_lineno": 481, "func_start_lineno": 127, "func_end_lineno": 140, "func_code": " def __getattribute__(self, name):\n \"\"\"\n This method is reimplemented to make the `content` attribute removal more visible.\n \"\"\"\n\n if name == \"content\":\n msg = (\n \"The `content` attribute of `ChatMessage` has been removed. \"\n \"Use the `text` property to access the textual value. \"\n \"For more information about the new API and how to migrate, see the documentation: \"\n \"https://docs.haystack.deepset.ai/docs/chatmessage\"\n )\n raise AttributeError(msg)\n return object.__getattribute__(self, name)"}, {"class_start_lineno": 88, "class_end_lineno": 481, "func_start_lineno": 146, "func_end_lineno": 150, "func_code": " def role(self) -> ChatRole:\n \"\"\"\n Returns the role of the entity sending the message.\n \"\"\"\n return self._role"}, {"class_start_lineno": 88, "class_end_lineno": 481, "func_start_lineno": 160, "func_end_lineno": 164, "func_code": " def name(self) -> Optional[str]:\n \"\"\"\n Returns the name associated with the message.\n \"\"\"\n return self._name"}, {"class_start_lineno": 88, "class_end_lineno": 481, "func_start_lineno": 167, "func_end_lineno": 171, "func_code": " def texts(self) -> List[str]:\n \"\"\"\n Returns the list of all texts contained in the message.\n \"\"\"\n return [content.text for content in self._content if isinstance(content, TextContent)]"}, {"class_start_lineno": 88, "class_end_lineno": 481, "func_start_lineno": 174, "func_end_lineno": 180, "func_code": " def text(self) -> Optional[str]:\n \"\"\"\n Returns the first text contained in the message.\n \"\"\"\n if texts := self.texts:\n return texts[0]\n return None"}, {"class_start_lineno": 88, "class_end_lineno": 481, "func_start_lineno": 183, "func_end_lineno": 187, "func_code": " def tool_calls(self) -> List[ToolCall]:\n \"\"\"\n Returns the list of all Tool calls contained in the message.\n \"\"\"\n return [content for content in self._content if isinstance(content, ToolCall)]"}, {"class_start_lineno": 88, "class_end_lineno": 481, "func_start_lineno": 190, "func_end_lineno": 196, "func_code": " def tool_call(self) -> Optional[ToolCall]:\n \"\"\"\n Returns the first Tool call contained in the message.\n \"\"\"\n if tool_calls := self.tool_calls:\n return tool_calls[0]\n return None"}, {"class_start_lineno": 88, "class_end_lineno": 481, "func_start_lineno": 199, "func_end_lineno": 203, "func_code": " def tool_call_results(self) -> List[ToolCallResult]:\n \"\"\"\n Returns the list of all Tool call results contained in the message.\n \"\"\"\n return [content for content in self._content if isinstance(content, ToolCallResult)]"}, {"class_start_lineno": 88, "class_end_lineno": 481, "func_start_lineno": 206, "func_end_lineno": 212, "func_code": " def tool_call_result(self) -> Optional[ToolCallResult]:\n \"\"\"\n Returns the first Tool call result contained in the message.\n \"\"\"\n if tool_call_results := self.tool_call_results:\n return tool_call_results[0]\n return None"}, {"class_start_lineno": 88, "class_end_lineno": 481, "func_start_lineno": 293, "func_end_lineno": 316, "func_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"\n Converts ChatMessage into a dictionary.\n\n :returns:\n Serialized version of the object.\n \"\"\"\n serialized: Dict[str, Any] = {}\n serialized[\"_role\"] = self._role.value\n serialized[\"_meta\"] = self._meta\n serialized[\"_name\"] = self._name\n content: List[Dict[str, Any]] = []\n for part in self._content:\n if isinstance(part, TextContent):\n content.append({\"text\": part.text})\n elif isinstance(part, ToolCall):\n content.append({\"tool_call\": asdict(part)})\n elif isinstance(part, ToolCallResult):\n content.append({\"tool_call_result\": asdict(part)})\n else:\n raise TypeError(f\"Unsupported type in ChatMessage content: `{type(part).__name__}` for `{part}`.\")\n\n serialized[\"_content\"] = content\n return serialized"}, {"class_start_lineno": 88, "class_end_lineno": 481, "func_start_lineno": 357, "func_end_lineno": 403, "func_code": " def to_openai_dict_format(self) -> Dict[str, Any]:\n \"\"\"\n Convert a ChatMessage to the dictionary format expected by OpenAI's Chat API.\n \"\"\"\n text_contents = self.texts\n tool_calls = self.tool_calls\n tool_call_results = self.tool_call_results\n\n if not text_contents and not tool_calls and not tool_call_results:\n raise ValueError(\n \"A `ChatMessage` must contain at least one `TextContent`, `ToolCall`, or `ToolCallResult`.\"\n )\n if len(text_contents) + len(tool_call_results) > 1:\n raise ValueError(\"A `ChatMessage` can only contain one `TextContent` or one `ToolCallResult`.\")\n\n openai_msg: Dict[str, Any] = {\"role\": self._role.value}\n\n # Add name field if present\n if self._name is not None:\n openai_msg[\"name\"] = self._name\n\n if tool_call_results:\n result = tool_call_results[0]\n if result.origin.id is None:\n raise ValueError(\"`ToolCall` must have a non-null `id` attribute to be used with OpenAI.\")\n openai_msg[\"content\"] = result.result\n openai_msg[\"tool_call_id\"] = result.origin.id\n # OpenAI does not provide a way to communicate errors in tool invocations, so we ignore the error field\n return openai_msg\n\n if text_contents:\n openai_msg[\"content\"] = text_contents[0]\n if tool_calls:\n openai_tool_calls = []\n for tc in tool_calls:\n if tc.id is None:\n raise ValueError(\"`ToolCall` must have a non-null `id` attribute to be used with OpenAI.\")\n openai_tool_calls.append(\n {\n \"id\": tc.id,\n \"type\": \"function\",\n # We disable ensure_ascii so special chars like emojis are not converted\n \"function\": {\"name\": tc.tool_name, \"arguments\": json.dumps(tc.arguments, ensure_ascii=False)},\n }\n )\n openai_msg[\"tool_calls\"] = openai_tool_calls\n return openai_msg"}], "type": ["function_empty", "TDD"], "node": ["haystack.dataclasses.chat_message.ChatMessage.__getattribute__", "haystack.dataclasses.chat_message.ChatMessage.role", "haystack.dataclasses.chat_message.ChatMessage.name", "haystack.dataclasses.chat_message.ChatMessage.texts", "haystack.dataclasses.chat_message.ChatMessage.text", "haystack.dataclasses.chat_message.ChatMessage.tool_calls", "haystack.dataclasses.chat_message.ChatMessage.tool_call", "haystack.dataclasses.chat_message.ChatMessage.tool_call_results", "haystack.dataclasses.chat_message.ChatMessage.tool_call_result", "haystack.dataclasses.chat_message.ChatMessage.to_dict", "haystack.dataclasses.chat_message.ChatMessage.to_openai_dict_format"], "language": "Python", "toolfunc_count": 1, "func_count": 3, "pytest_info": {"total_num": 35, "base_passed_num": 15}} {"id": ["haystack.haystack.evaluation.eval_run_result.EvaluationRunResult::detailed_report", "haystack.haystack.evaluation.eval_run_result.EvaluationRunResult::comparative_detailed_report"], "project": "haystack", "origin_file": ["haystack/evaluation/eval_run_result.py", "haystack/evaluation/eval_run_result.py"], "test_list": ["test/evaluation/test_eval_run_result.py"], "prob_info": [{"class_start_lineno": 16, "class_end_lineno": 222, "func_start_lineno": 138, "func_end_lineno": 162, "func_code": " def detailed_report(\n self, output_format: Literal[\"json\", \"csv\", \"df\"] = \"json\", csv_file: Optional[str] = None\n ) -> Union[Dict[str, List[Any]], \"DataFrame\", str]:\n \"\"\"\n Generates a report with detailed scores for each metric.\n\n :param output_format: The output format for the report, \"json\", \"csv\", or \"df\", default to \"json\".\n :param csv_file: Filepath to save CSV output if `output_format` is \"csv\", must be provided.\n\n :returns:\n JSON or DataFrame with the detailed scores, in case the output is set to a CSV file, a message confirming\n the successful write or an error message.\n \"\"\"\n\n combined_data = {col: self.inputs[col] for col in self.inputs}\n\n # enforce columns type consistency\n scores_columns = list(self.results.keys())\n for col in scores_columns:\n col_values = self.results[col][\"individual_scores\"]\n if any(isinstance(v, float) for v in col_values):\n col_values = [float(v) for v in col_values]\n combined_data[col] = col_values\n\n return self._handle_output(combined_data, output_format, csv_file)"}, {"class_start_lineno": 16, "class_end_lineno": 222, "func_start_lineno": 164, "func_end_lineno": 222, "func_code": " def comparative_detailed_report(\n self,\n other: \"EvaluationRunResult\",\n keep_columns: Optional[List[str]] = None,\n output_format: Literal[\"json\", \"csv\", \"df\"] = \"json\",\n csv_file: Optional[str] = None,\n ) -> Union[str, \"DataFrame\", None]:\n \"\"\"\n Generates a report with detailed scores for each metric from two evaluation runs for comparison.\n\n :param other: Results of another evaluation run to compare with.\n :param keep_columns: List of common column names to keep from the inputs of the evaluation runs to compare.\n :param output_format: The output format for the report, \"json\", \"csv\", or \"df\", default to \"json\".\n :param csv_file: Filepath to save CSV output if `output_format` is \"csv\", must be provided.\n\n :returns:\n JSON or DataFrame with a comparison of the detailed scores, in case the output is set to a CSV file,\n a message confirming the successful write or an error message.\n \"\"\"\n\n if not isinstance(other, EvaluationRunResult):\n raise ValueError(\"Comparative scores can only be computed between EvaluationRunResults.\")\n\n if not hasattr(other, \"run_name\") or not hasattr(other, \"inputs\") or not hasattr(other, \"results\"):\n raise ValueError(\"The 'other' parameter must have 'run_name', 'inputs', and 'results' attributes.\")\n\n if self.run_name == other.run_name:\n warn(f\"The run names of the two evaluation results are the same ('{self.run_name}')\")\n\n if self.inputs.keys() != other.inputs.keys():\n warn(f\"The input columns differ between the results; using the input columns of '{self.run_name}'.\")\n\n # got both detailed reports\n detailed_a = self.detailed_report(output_format=\"json\")\n detailed_b = other.detailed_report(output_format=\"json\")\n\n # ensure both detailed reports are in dictionaries format\n if not isinstance(detailed_a, dict) or not isinstance(detailed_b, dict):\n raise ValueError(\"Detailed reports must be dictionaries.\")\n\n # determine which columns to ignore\n if keep_columns is None:\n ignore = list(self.inputs.keys())\n else:\n ignore = [col for col in list(self.inputs.keys()) if col not in keep_columns]\n\n # filter out ignored columns from pipe_b_dict\n filtered_detailed_b = {\n f\"{other.run_name}_{key}\": value for key, value in detailed_b.items() if key not in ignore\n }\n\n # rename columns in pipe_a_dict based on ignore list\n renamed_detailed_a = {\n (key if key in ignore else f\"{self.run_name}_{key}\"): value for key, value in detailed_a.items()\n }\n\n # combine both detailed reports\n combined_results = {**renamed_detailed_a, **filtered_detailed_b}\n return self._handle_output(combined_results, output_format, csv_file)"}], "type": ["function_empty"], "node": ["haystack.evaluation.eval_run_result.EvaluationRunResult.detailed_report", "haystack.evaluation.eval_run_result.EvaluationRunResult.comparative_detailed_report"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 4, "base_passed_num": 2}} {"id": ["haystack.haystack.tools.from_function.create_tool_from_function", "haystack.haystack.tools.from_function.tool"], "project": "haystack", "origin_file": ["haystack/tools/from_function.py", "haystack/tools/from_function.py"], "test_list": ["test/tools/test_from_function.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 166, "func_start_lineno": 14, "func_end_lineno": 112, "func_code": "def create_tool_from_function(\n function: Callable, name: Optional[str] = None, description: Optional[str] = None\n) -> \"Tool\":\n \"\"\"\n Create a Tool instance from a function.\n\n Allows customizing the Tool name and description.\n For simpler use cases, consider using the `@tool` decorator.\n\n ### Usage example\n\n ```python\n from typing import Annotated, Literal\n from haystack.tools import create_tool_from_function\n\n def get_weather(\n city: Annotated[str, \"the city for which to get the weather\"] = \"Munich\",\n unit: Annotated[Literal[\"Celsius\", \"Fahrenheit\"], \"the unit for the temperature\"] = \"Celsius\"):\n '''A simple function to get the current weather for a location.'''\n return f\"Weather report for {city}: 20 {unit}, sunny\"\n\n tool = create_tool_from_function(get_weather)\n\n print(tool)\n >>> Tool(name='get_weather', description='A simple function to get the current weather for a location.',\n >>> parameters={\n >>> 'type': 'object',\n >>> 'properties': {\n >>> 'city': {'type': 'string', 'description': 'the city for which to get the weather', 'default': 'Munich'},\n >>> 'unit': {\n >>> 'type': 'string',\n >>> 'enum': ['Celsius', 'Fahrenheit'],\n >>> 'description': 'the unit for the temperature',\n >>> 'default': 'Celsius',\n >>> },\n >>> }\n >>> },\n >>> function=)\n ```\n\n :param function:\n The function to be converted into a Tool.\n The function must include type hints for all parameters.\n The function is expected to have basic python input types (str, int, float, bool, list, dict, tuple).\n Other input types may work but are not guaranteed.\n If a parameter is annotated using `typing.Annotated`, its metadata will be used as parameter description.\n :param name:\n The name of the Tool. If not provided, the name of the function will be used.\n :param description:\n The description of the Tool. If not provided, the docstring of the function will be used.\n To intentionally leave the description empty, pass an empty string.\n\n :returns:\n The Tool created from the function.\n\n :raises ValueError:\n If any parameter of the function lacks a type hint.\n :raises SchemaGenerationError:\n If there is an error generating the JSON schema for the Tool.\n \"\"\"\n\n tool_description = description if description is not None else (function.__doc__ or \"\")\n\n signature = inspect.signature(function)\n\n # collect fields (types and defaults) and descriptions from function parameters\n fields: Dict[str, Any] = {}\n descriptions = {}\n\n for param_name, param in signature.parameters.items():\n if param.annotation is param.empty:\n raise ValueError(f\"Function '{function.__name__}': parameter '{param_name}' does not have a type hint.\")\n\n # if the parameter has not a default value, Pydantic requires an Ellipsis (...)\n # to explicitly indicate that the parameter is required\n default = param.default if param.default is not param.empty else ...\n fields[param_name] = (param.annotation, default)\n\n if hasattr(param.annotation, \"__metadata__\"):\n descriptions[param_name] = param.annotation.__metadata__[0]\n\n # create Pydantic model and generate JSON schema\n try:\n model = create_model(function.__name__, **fields)\n schema = model.model_json_schema()\n except Exception as e:\n raise SchemaGenerationError(f\"Failed to create JSON schema for function '{function.__name__}'\") from e\n\n # we don't want to include title keywords in the schema, as they contain redundant information\n # there is no programmatic way to prevent Pydantic from adding them, so we remove them later\n # see https://github.com/pydantic/pydantic/discussions/8504\n _remove_title_from_schema(schema)\n\n # add parameters descriptions to the schema\n for param_name, param_description in descriptions.items():\n if param_name in schema[\"properties\"]:\n schema[\"properties\"][param_name][\"description\"] = param_description\n\n return Tool(name=name or function.__name__, description=tool_description, parameters=schema, function=function)"}, {"class_start_lineno": 1, "class_end_lineno": 166, "func_start_lineno": 115, "func_end_lineno": 151, "func_code": "def tool(function: Callable) -> Tool:\n \"\"\"\n Decorator to convert a function into a Tool.\n\n Tool name, description, and parameters are inferred from the function.\n If you need to customize more the Tool, use `create_tool_from_function` instead.\n\n ### Usage example\n ```python\n from typing import Annotated, Literal\n from haystack.tools import tool\n\n @tool\n def get_weather(\n city: Annotated[str, \"the city for which to get the weather\"] = \"Munich\",\n unit: Annotated[Literal[\"Celsius\", \"Fahrenheit\"], \"the unit for the temperature\"] = \"Celsius\"):\n '''A simple function to get the current weather for a location.'''\n return f\"Weather report for {city}: 20 {unit}, sunny\"\n\n print(get_weather)\n >>> Tool(name='get_weather', description='A simple function to get the current weather for a location.',\n >>> parameters={\n >>> 'type': 'object',\n >>> 'properties': {\n >>> 'city': {'type': 'string', 'description': 'the city for which to get the weather', 'default': 'Munich'},\n >>> 'unit': {\n >>> 'type': 'string',\n >>> 'enum': ['Celsius', 'Fahrenheit'],\n >>> 'description': 'the unit for the temperature',\n >>> 'default': 'Celsius',\n >>> },\n >>> }\n >>> },\n >>> function=)\n ```\n \"\"\"\n return create_tool_from_function(function)"}], "type": ["function_empty"], "node": ["haystack.tools.from_function.create_tool_from_function", "haystack.tools.from_function.tool"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 12, "base_passed_num": 3}} {"id": ["haystack.haystack.core.serialization.import_class_by_name", "haystack.haystack.tools.tool.deserialize_tools_inplace"], "project": "haystack", "origin_file": ["haystack/core/serialization.py", "haystack/tools/tool.py"], "test_list": ["test/tools/test_tool.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 264, "func_start_lineno": 243, "func_end_lineno": 264, "func_code": "def import_class_by_name(fully_qualified_name: str) -> Type[object]:\n \"\"\"\n Utility function to import (load) a class object based on its fully qualified class name.\n\n This function dynamically imports a class based on its string name.\n It splits the name into module path and class name, imports the module,\n and returns the class object.\n\n :param fully_qualified_name: the fully qualified class name as a string\n :returns: the class object.\n :raises ImportError: If the class cannot be imported or found.\n \"\"\"\n try:\n module_path, class_name = fully_qualified_name.rsplit(\".\", 1)\n logger.debug(\n \"Attempting to import class '{cls_name}' from module '{md_path}'\", cls_name=class_name, md_path=module_path\n )\n module = thread_safe_import(module_path)\n return getattr(module, class_name)\n except (ImportError, AttributeError) as error:\n logger.error(\"Failed to import class '{full_name}'\", full_name=fully_qualified_name)\n raise ImportError(f\"Could not import class '{fully_qualified_name}'\") from error"}, {"class_start_lineno": 1, "class_end_lineno": 136, "func_start_lineno": 106, "func_end_lineno": 136, "func_code": "def deserialize_tools_inplace(data: Dict[str, Any], key: str = \"tools\"):\n \"\"\"\n Deserialize Tools in a dictionary inplace.\n\n :param data:\n The dictionary with the serialized data.\n :param key:\n The key in the dictionary where the Tools are stored.\n \"\"\"\n if key in data:\n serialized_tools = data[key]\n\n if serialized_tools is None:\n return\n\n if not isinstance(serialized_tools, list):\n raise TypeError(f\"The value of '{key}' is not a list\")\n\n deserialized_tools = []\n for tool in serialized_tools:\n if not isinstance(tool, dict):\n raise TypeError(f\"Serialized tool '{tool}' is not a dictionary\")\n\n # different classes are allowed: Tool, ComponentTool, etc.\n tool_class = import_class_by_name(tool[\"type\"])\n if not issubclass(tool_class, Tool):\n raise TypeError(f\"Class '{tool_class}' is not a subclass of Tool\")\n\n deserialized_tools.append(tool_class.from_dict(tool))\n\n data[key] = deserialized_tools"}], "type": ["function_empty"], "node": ["haystack.core.serialization.import_class_by_name", "haystack.tools.tool.deserialize_tools_inplace"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 10, "base_passed_num": 8}} {"id": ["haystack.haystack.dataclasses.document.Document::to_dict", "haystack.haystack.tracing.utils.coerce_tag_value"], "project": "haystack", "origin_file": ["haystack/dataclasses/document.py", "haystack/tracing/utils.py", "haystack/tracing/utils.py"], "test_list": ["test/tracing/test_utils.py"], "prob_info": [{"class_start_lineno": 49, "class_end_lineno": 186, "func_start_lineno": 123, "func_end_lineno": 140, "func_code": " def to_dict(self, flatten=True) -> Dict[str, Any]:\n \"\"\"\n Converts Document into a dictionary.\n\n `blob` field is converted to a JSON-serializable type.\n\n :param flatten:\n Whether to flatten `meta` field or not. Defaults to `True` to be backward-compatible with Haystack 1.x.\n \"\"\"\n data = asdict(self)\n if (blob := data.get(\"blob\")) is not None:\n data[\"blob\"] = {\"data\": list(blob[\"data\"]), \"mime_type\": blob[\"mime_type\"]}\n\n if flatten:\n meta = data.pop(\"meta\")\n return {**data, **meta}\n\n return data"}, {"class_start_lineno": 1, "class_end_lineno": 52, "func_start_lineno": 42, "func_end_lineno": 52, "func_code": "def _serializable_value(value: Any) -> Any:\n if isinstance(value, list):\n return [_serializable_value(v) for v in value]\n\n if isinstance(value, dict):\n return {k: _serializable_value(v) for k, v in value.items()}\n\n if getattr(value, \"to_dict\", None):\n return _serializable_value(value.to_dict())\n\n return value"}, {"class_start_lineno": 1, "class_end_lineno": 52, "func_start_lineno": 15, "func_end_lineno": 39, "func_code": "def coerce_tag_value(value: Any) -> Union[bool, str, int, float]:\n \"\"\"\n Coerces span tag values to compatible types for the tracing backend.\n\n Most tracing libraries don't support sending complex types to the backend. Hence, we need to convert them to\n compatible types.\n\n :param value: an arbitrary value which should be coerced to a compatible type\n :return: the value coerced to a compatible type\n \"\"\"\n if isinstance(value, PRIMITIVE_TYPES):\n return value\n\n if value is None:\n return \"\"\n\n try:\n # do that with-in try-except because who knows what kind of objects are being passed\n serializable = _serializable_value(value)\n return json.dumps(serializable)\n except Exception as error:\n logger.debug(\"Failed to coerce tag value to string: {error}\", error=error)\n\n # Our last resort is to convert the value to a string\n return str(value)"}], "type": ["function_empty"], "node": ["haystack.dataclasses.document.Document.to_dict", "haystack.tracing.utils._serializable_value", "haystack.tracing.utils.coerce_tag_value"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 11, "base_passed_num": 0}} {"id": ["haystack.haystack.core.serialization.import_class_by_name", "haystack.haystack.utils.base_serialization.deserialize_class_instance"], "project": "haystack", "origin_file": ["haystack/core/serialization.py", "haystack/utils/base_serialization.py"], "test_list": ["test/utils/test_base_serialization.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 264, "func_start_lineno": 243, "func_end_lineno": 264, "func_code": "def import_class_by_name(fully_qualified_name: str) -> Type[object]:\n \"\"\"\n Utility function to import (load) a class object based on its fully qualified class name.\n\n This function dynamically imports a class based on its string name.\n It splits the name into module path and class name, imports the module,\n and returns the class object.\n\n :param fully_qualified_name: the fully qualified class name as a string\n :returns: the class object.\n :raises ImportError: If the class cannot be imported or found.\n \"\"\"\n try:\n module_path, class_name = fully_qualified_name.rsplit(\".\", 1)\n logger.debug(\n \"Attempting to import class '{cls_name}' from module '{md_path}'\", cls_name=class_name, md_path=module_path\n )\n module = thread_safe_import(module_path)\n return getattr(module, class_name)\n except (ImportError, AttributeError) as error:\n logger.error(\"Failed to import class '{full_name}'\", full_name=fully_qualified_name)\n raise ImportError(f\"Could not import class '{fully_qualified_name}'\") from error"}, {"class_start_lineno": 1, "class_end_lineno": 54, "func_start_lineno": 29, "func_end_lineno": 54, "func_code": "def deserialize_class_instance(data: Dict[str, Any]) -> Any:\n \"\"\"\n Deserializes an object from a dictionary representation generated by `auto_serialize_class_instance`.\n\n :param data:\n The dictionary to deserialize from.\n :returns:\n The deserialized object.\n :raises DeserializationError:\n If the serialization data is malformed, the class type cannot be imported, or the\n class does not have a `from_dict` method.\n \"\"\"\n if \"type\" not in data:\n raise DeserializationError(\"Missing 'type' in serialization data\")\n if \"data\" not in data:\n raise DeserializationError(\"Missing 'data' in serialization data\")\n\n try:\n obj_class = import_class_by_name(data[\"type\"])\n except ImportError as e:\n raise DeserializationError(f\"Class '{data['type']}' not correctly imported\") from e\n\n if not hasattr(obj_class, \"from_dict\"):\n raise DeserializationError(f\"Class '{data['type']}' does not have a 'from_dict' method\")\n\n return obj_class.from_dict(data[\"data\"])"}], "type": ["function_empty"], "node": ["haystack.core.serialization.import_class_by_name", "haystack.utils.base_serialization.deserialize_class_instance"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 4, "base_passed_num": 2}} {"id": ["haystack.haystack.utils.type_serialization.thread_safe_import", "haystack.haystack.utils.callable_serialization.deserialize_callable"], "project": "haystack", "origin_file": ["haystack/utils/type_serialization.py", "haystack/utils/callable_serialization.py"], "test_list": ["test/utils/test_callable_serialization.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 170, "func_start_lineno": 159, "func_end_lineno": 170, "func_code": "def thread_safe_import(module_name: str) -> ModuleType:\n \"\"\"\n Import a module in a thread-safe manner.\n\n Importing modules in a multi-threaded environment can lead to race conditions.\n This function ensures that the module is imported in a thread-safe manner without having impact\n on the performance of the import for single-threaded environments.\n\n :param module_name: the module to import\n \"\"\"\n with _import_lock:\n return importlib.import_module(module_name)"}, {"class_start_lineno": 1, "class_end_lineno": 80, "func_start_lineno": 45, "func_end_lineno": 80, "func_code": "def deserialize_callable(callable_handle: str) -> Callable:\n \"\"\"\n Deserializes a callable given its full import path as a string.\n\n :param callable_handle: The full path of the callable_handle\n :return: The callable\n :raises DeserializationError: If the callable cannot be found\n \"\"\"\n parts = callable_handle.split(\".\")\n\n for i in range(len(parts), 0, -1):\n module_name = \".\".join(parts[:i])\n try:\n mod: Any = thread_safe_import(module_name)\n except Exception:\n # keep reducing i until we find a valid module import\n continue\n\n attr_value = mod\n for part in parts[i:]:\n try:\n attr_value = getattr(attr_value, part)\n except AttributeError as e:\n raise DeserializationError(f\"Could not find attribute '{part}' in {attr_value.__name__}\") from e\n\n # when the attribute is a classmethod, we need the underlying function\n if isinstance(attr_value, (classmethod, staticmethod)):\n attr_value = attr_value.__func__\n\n if not callable(attr_value):\n raise DeserializationError(f\"The final attribute is not callable: {attr_value}\")\n\n return attr_value\n\n # Fallback if we never find anything\n raise DeserializationError(f\"Could not import '{callable_handle}' as a module or callable.\")"}], "type": ["function_empty", "TDD"], "node": ["haystack.utils.type_serialization.thread_safe_import", "haystack.utils.callable_serialization.deserialize_callable"], "language": "Python", "toolfunc_count": 1, "func_count": 2, "pytest_info": {"total_num": 11, "base_passed_num": 5}} {"id": ["haystack.haystack.utils.device.ComponentDevice::to_hf", "haystack.haystack.utils.device.ComponentDevice::update_hf_kwargs"], "project": "haystack", "origin_file": ["haystack/utils/device.py", "haystack/utils/device.py"], "test_list": ["test/utils/test_device.py"], "prob_info": [{"class_start_lineno": 240, "class_end_lineno": 480, "func_start_lineno": 359, "func_end_lineno": 379, "func_code": " def to_hf(self) -> Union[Union[int, str], Dict[str, Union[int, str]]]:\n \"\"\"\n Convert the component device representation to HuggingFace format.\n\n :returns:\n The HuggingFace device representation.\n \"\"\"\n self._validate()\n\n def convert_device(device: Device, *, gpu_id_only: bool = False) -> Union[int, str]:\n if gpu_id_only and device.type == DeviceType.GPU:\n assert device.id is not None\n return device.id\n else:\n return str(device)\n\n if self._single_device is not None:\n return convert_device(self._single_device)\n\n assert self._multiple_devices is not None\n return {key: convert_device(device, gpu_id_only=True) for key, device in self._multiple_devices.mapping.items()}"}, {"class_start_lineno": 240, "class_end_lineno": 480, "func_start_lineno": 381, "func_end_lineno": 402, "func_code": " def update_hf_kwargs(self, hf_kwargs: Dict[str, Any], *, overwrite: bool) -> Dict[str, Any]:\n \"\"\"\n Convert the component device representation to HuggingFace format.\n\n Add them as canonical keyword arguments to the keyword arguments dictionary.\n\n :param hf_kwargs:\n The HuggingFace keyword arguments dictionary.\n :param overwrite:\n Whether to overwrite existing device arguments.\n :returns:\n The HuggingFace keyword arguments dictionary.\n \"\"\"\n self._validate()\n\n if not overwrite and any(x in hf_kwargs for x in (\"device\", \"device_map\")):\n return hf_kwargs\n\n converted = self.to_hf()\n key = \"device_map\" if self.has_multiple_devices else \"device\"\n hf_kwargs[key] = converted\n return hf_kwargs"}], "type": ["function_empty"], "node": ["haystack.utils.device.ComponentDevice.to_hf", "haystack.utils.device.ComponentDevice.update_hf_kwargs"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 7, "base_passed_num": 4}} {"id": ["haystack.haystack.core.serialization.import_class_by_name", "haystack.haystack.utils.docstore_deserialization.deserialize_document_store_in_init_params_inplace"], "project": "haystack", "origin_file": ["haystack/core/serialization.py", "haystack/utils/docstore_deserialization.py"], "test_list": ["test/utils/test_docstore_deserialization.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 264, "func_start_lineno": 243, "func_end_lineno": 264, "func_code": "def import_class_by_name(fully_qualified_name: str) -> Type[object]:\n \"\"\"\n Utility function to import (load) a class object based on its fully qualified class name.\n\n This function dynamically imports a class based on its string name.\n It splits the name into module path and class name, imports the module,\n and returns the class object.\n\n :param fully_qualified_name: the fully qualified class name as a string\n :returns: the class object.\n :raises ImportError: If the class cannot be imported or found.\n \"\"\"\n try:\n module_path, class_name = fully_qualified_name.rsplit(\".\", 1)\n logger.debug(\n \"Attempting to import class '{cls_name}' from module '{md_path}'\", cls_name=class_name, md_path=module_path\n )\n module = thread_safe_import(module_path)\n return getattr(module, class_name)\n except (ImportError, AttributeError) as error:\n logger.error(\"Failed to import class '{full_name}'\", full_name=fully_qualified_name)\n raise ImportError(f\"Could not import class '{fully_qualified_name}'\") from error"}, {"class_start_lineno": 1, "class_end_lineno": 39, "func_start_lineno": 11, "func_end_lineno": 39, "func_code": "def deserialize_document_store_in_init_params_inplace(data: Dict[str, Any], key: str = \"document_store\"):\n \"\"\"\n Deserializes a generic document store from the init_parameters of a serialized component in place.\n\n :param data:\n The dictionary to deserialize from.\n :param key:\n The key in the `data[\"init_parameters\"]` dictionary where the document store is specified.\n :returns:\n The dictionary, with the document store deserialized.\n\n :raises DeserializationError:\n If the document store is not properly specified in the serialization data or its type cannot be imported.\n \"\"\"\n init_params = data.get(\"init_parameters\", {})\n if key not in init_params:\n raise DeserializationError(f\"Missing '{key}' in serialization data\")\n if \"type\" not in init_params[key]:\n raise DeserializationError(f\"Missing 'type' in {key} serialization data\")\n\n doc_store_data = data[\"init_parameters\"][key]\n try:\n doc_store_class = import_class_by_name(doc_store_data[\"type\"])\n except ImportError as e:\n raise DeserializationError(f\"Class '{doc_store_data['type']}' not correctly imported\") from e\n if hasattr(doc_store_class, \"from_dict\"):\n data[\"init_parameters\"][key] = doc_store_class.from_dict(doc_store_data)\n else:\n data[\"init_parameters\"][key] = default_from_dict(doc_store_class, doc_store_data)"}], "type": ["function_empty"], "node": ["haystack.core.serialization.import_class_by_name", "haystack.utils.docstore_deserialization.deserialize_document_store_in_init_params_inplace"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 6, "base_passed_num": 0}} {"id": ["inference.inference.core.utils.image_utils.validate_numpy_image", "inference.inference.core.utils.image_utils.load_image_with_inferred_type"], "project": "inference", "origin_file": ["inference/core/utils/image_utils.py", "inference/core/utils/image_utils.py"], "test_list": ["tests/inference/unit_tests/core/active_learning/test_middlewares.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 599, "func_start_lineno": 353, "func_end_lineno": 377, "func_code": "def validate_numpy_image(data: np.ndarray) -> None:\n \"\"\"\n Validate if the provided data is a valid numpy image.\n\n Args:\n data (np.ndarray): The numpy array representing an image.\n\n Raises:\n InvalidNumpyInput: If the provided data is not a valid numpy image.\n \"\"\"\n if not issubclass(type(data), np.ndarray):\n raise InvalidNumpyInput(\n message=f\"Data provided as input could not be decoded into np.ndarray object.\",\n public_message=f\"Data provided as input could not be decoded into np.ndarray object.\",\n )\n if len(data.shape) != 3 and len(data.shape) != 2:\n raise InvalidNumpyInput(\n message=f\"For image given as np.ndarray expected 2 or 3 dimensions, got {len(data.shape)} dimensions.\",\n public_message=f\"For image given as np.ndarray expected 2 or 3 dimensions.\",\n )\n if data.shape[-1] != 3 and data.shape[-1] != 1:\n raise InvalidNumpyInput(\n message=f\"For image given as np.ndarray expected 1 or 3 channels, got {data.shape[-1]} channels.\",\n public_message=\"For image given as np.ndarray expected 1 or 3 channels.\",\n )"}, {"class_start_lineno": 1, "class_end_lineno": 599, "func_start_lineno": 180, "func_end_lineno": 212, "func_code": "def load_image_with_inferred_type(\n value: Any,\n cv_imread_flags: int = cv2.IMREAD_COLOR,\n) -> Tuple[np.ndarray, bool]:\n \"\"\"Load an image by inferring its type.\n\n Args:\n value (Any): The image data.\n cv_imread_flags (int): Flags used for OpenCV's imread function.\n\n Returns:\n Tuple[np.ndarray, bool]: Loaded image as a numpy array and a boolean indicating if the image is in BGR format.\n\n Raises:\n NotImplementedError: If the image type could not be inferred.\n \"\"\"\n if isinstance(value, (np.ndarray, np.generic)):\n validate_numpy_image(data=value)\n return value, True\n elif isinstance(value, Image.Image):\n return np.asarray(value.convert(\"RGB\")), False\n elif isinstance(value, str) and (value.startswith(\"http\")):\n return load_image_from_url(value=value, cv_imread_flags=cv_imread_flags), True\n elif (\n isinstance(value, str)\n and ALLOW_LOADING_IMAGES_FROM_LOCAL_FILESYSTEM\n and os.path.isfile(value)\n ):\n return cv2.imread(value, cv_imread_flags), True\n else:\n return attempt_loading_image_from_string(\n value=value, cv_imread_flags=cv_imread_flags\n )"}], "type": ["function_empty"], "node": ["inference.core.utils.image_utils.validate_numpy_image", "inference.core.utils.image_utils.load_image_with_inferred_type"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 7, "base_passed_num": 4}} {"id": ["inference.inference.core.interfaces.camera.video_source.VideoSource::read_frame", "inference.inference.core.interfaces.camera.video_source.VideoSource::__next__", "inference.inference.core.interfaces.camera.utils.get_video_frames_generator", "inference.inference.core.interfaces.camera.video_source.get_from_queue"], "project": "inference", "origin_file": ["inference/core/interfaces/camera/video_source.py", "inference/core/interfaces/camera/video_source.py", "inference/core/interfaces/camera/utils.py", "inference/core/interfaces/camera/utils.py", "inference/core/interfaces/camera/video_source.py"], "test_list": ["tests/inference/unit_tests/core/interfaces/camera/test_utils.py"], "prob_info": [{"class_start_lineno": 181, "class_end_lineno": 738, "func_start_lineno": 526, "func_end_lineno": 555, "func_code": " def read_frame(self, timeout: Optional[float] = None) -> Optional[VideoFrame]:\n \"\"\"\n Method to be used by the consumer to get decoded source frame.\n\n Returns: VideoFrame object with decoded frame and its metadata.\n Throws:\n * EndOfStreamError: when trying to get the frame from closed source.\n \"\"\"\n video_frame: Optional[Union[VideoFrame, str]] = get_from_queue(\n queue=self._frames_buffer,\n on_successful_read=self._video_consumer.notify_frame_consumed,\n timeout=timeout,\n purge=self._buffer_consumption_strategy is BufferConsumptionStrategy.EAGER,\n )\n if video_frame == POISON_PILL:\n raise EndOfStreamError(\n \"Attempted to retrieve frame from stream that already ended.\"\n )\n if video_frame is not None:\n send_video_source_status_update(\n severity=UpdateSeverity.DEBUG,\n event_type=FRAME_CONSUMED_EVENT,\n payload={\n \"frame_timestamp\": video_frame.frame_timestamp,\n \"frame_id\": video_frame.frame_id,\n \"source_id\": video_frame.source_id,\n },\n status_update_handlers=self._status_update_handlers,\n )\n return video_frame"}, {"class_start_lineno": 181, "class_end_lineno": 738, "func_start_lineno": 720, "func_end_lineno": 738, "func_code": " def __next__(self) -> VideoFrame:\n \"\"\"\n Method allowing to use `VideoSource` convenient to read frames\n\n Returns: VideoFrame\n\n Example:\n ```python\n source = VideoSource.init(video_reference=\"./some.mp4\")\n source.start()\n\n for frame in source:\n pass\n ```\n \"\"\"\n try:\n return self.read_frame()\n except EndOfStreamError:\n raise StopIteration()"}, {"class_start_lineno": 1, "class_end_lineno": 516, "func_start_lineno": 479, "func_end_lineno": 494, "func_code": "def limit_frame_rate(\n frames_generator: Iterable[T],\n max_fps: Union[float, int],\n strategy: FPSLimiterStrategy,\n) -> Generator[T, None, None]:\n rate_limiter = RateLimiter(desired_fps=max_fps)\n for frame_data in frames_generator:\n delay = rate_limiter.estimate_next_action_delay()\n if delay <= 0.0:\n rate_limiter.tick()\n yield frame_data\n continue\n if strategy is FPSLimiterStrategy.WAIT:\n time.sleep(delay)\n rate_limiter.tick()\n yield frame_data"}, {"class_start_lineno": 1, "class_end_lineno": 516, "func_start_lineno": 46, "func_end_lineno": 97, "func_code": "def get_video_frames_generator(\n video: Union[VideoSource, str, int],\n max_fps: Optional[Union[float, int]] = None,\n limiter_strategy: Optional[FPSLimiterStrategy] = None,\n) -> Generator[VideoFrame, None, None]:\n \"\"\"\n Util function to create a frames generator from `VideoSource` with possibility to\n limit FPS of consumed frames and dictate what to do if frames are produced to fast.\n\n Args:\n video (Union[VideoSource, str, int]): Either instance of VideoSource or video reference accepted\n by VideoSource.init(...)\n max_fps (Optional[Union[float, int]]): value of maximum FPS rate of generated frames - can be used to limit\n generation frequency\n limiter_strategy (Optional[FPSLimiterStrategy]): strategy used to deal with frames decoding exceeding\n limit of `max_fps`. By default - for files, in the interest of processing all frames -\n generation will be awaited, for streams - frames will be dropped on the floor.\n Returns: generator of `VideoFrame`\n\n Example:\n ```python\n from inference.core.interfaces.camera.utils import get_video_frames_generator\n\n for frame in get_video_frames_generator(\n video=\"./some.mp4\",\n max_fps=50,\n ):\n pass\n ```\n \"\"\"\n is_managed_source = False\n if issubclass(type(video), str) or issubclass(type(video), int):\n video = VideoSource.init(\n video_reference=video,\n )\n video.start()\n is_managed_source = True\n if max_fps is None:\n yield from video\n if is_managed_source:\n video.terminate(purge_frames_buffer=True)\n return None\n limiter_strategy = resolve_limiter_strategy(\n explicitly_defined_strategy=limiter_strategy,\n source_properties=video.describe_source().source_properties,\n )\n yield from limit_frame_rate(\n frames_generator=video, max_fps=max_fps, strategy=limiter_strategy\n )\n if is_managed_source:\n video.terminate(purge_frames_buffer=True)\n return None"}, {"class_start_lineno": 1, "class_end_lineno": 1209, "func_start_lineno": 1064, "func_end_lineno": 1089, "func_code": "def get_from_queue(\n queue: Queue,\n timeout: Optional[float] = None,\n on_successful_read: Callable[[], None] = lambda: None,\n purge: bool = False,\n) -> Optional[Any]:\n \"\"\"\n Function is supposed to take element from the queue waiting on the first element to appear using `timeout`\n parameter. One may ask to go to the very last element of the queue and return it - then `purge` should be set\n to True. No additional wait on new elements to appear happen and the purge stops once queue is free returning last\n element consumed.\n queue.task_done() and on_successful_read(...) will be called on each received element.\n \"\"\"\n result = None\n if queue.empty() or not purge:\n try:\n result = queue.get(timeout=timeout)\n queue.task_done()\n on_successful_read()\n except Empty:\n pass\n while not queue.empty() and purge:\n result = queue.get()\n queue.task_done()\n on_successful_read()\n return result"}], "type": ["function_empty"], "node": ["inference.core.interfaces.camera.video_source.VideoSource.read_frame", "inference.core.interfaces.camera.video_source.VideoSource.__next__", "inference.core.interfaces.camera.utils.limit_frame_rate", "inference.core.interfaces.camera.utils.get_video_frames_generator", "inference.core.interfaces.camera.video_source.get_from_queue"], "language": "Python", "toolfunc_count": 4, "func_count": 4, "pytest_info": {"total_num": 42, "base_passed_num": 0}} {"id": ["inference.inference.core.interfaces.camera.video_source.get_from_queue", "inference.inference.core.interfaces.camera.video_source.VideoSource::read_frame", "inference.inference.core.interfaces.camera.video_source.VideoSource::__next__"], "project": "inference", "origin_file": ["inference/core/interfaces/camera/video_source.py", "inference/core/interfaces/camera/video_source.py", "inference/core/interfaces/camera/video_source.py"], "test_list": ["tests/inference/unit_tests/core/interfaces/camera/test_video_source.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 1209, "func_start_lineno": 1064, "func_end_lineno": 1089, "func_code": "def get_from_queue(\n queue: Queue,\n timeout: Optional[float] = None,\n on_successful_read: Callable[[], None] = lambda: None,\n purge: bool = False,\n) -> Optional[Any]:\n \"\"\"\n Function is supposed to take element from the queue waiting on the first element to appear using `timeout`\n parameter. One may ask to go to the very last element of the queue and return it - then `purge` should be set\n to True. No additional wait on new elements to appear happen and the purge stops once queue is free returning last\n element consumed.\n queue.task_done() and on_successful_read(...) will be called on each received element.\n \"\"\"\n result = None\n if queue.empty() or not purge:\n try:\n result = queue.get(timeout=timeout)\n queue.task_done()\n on_successful_read()\n except Empty:\n pass\n while not queue.empty() and purge:\n result = queue.get()\n queue.task_done()\n on_successful_read()\n return result"}, {"class_start_lineno": 181, "class_end_lineno": 738, "func_start_lineno": 526, "func_end_lineno": 555, "func_code": " def read_frame(self, timeout: Optional[float] = None) -> Optional[VideoFrame]:\n \"\"\"\n Method to be used by the consumer to get decoded source frame.\n\n Returns: VideoFrame object with decoded frame and its metadata.\n Throws:\n * EndOfStreamError: when trying to get the frame from closed source.\n \"\"\"\n video_frame: Optional[Union[VideoFrame, str]] = get_from_queue(\n queue=self._frames_buffer,\n on_successful_read=self._video_consumer.notify_frame_consumed,\n timeout=timeout,\n purge=self._buffer_consumption_strategy is BufferConsumptionStrategy.EAGER,\n )\n if video_frame == POISON_PILL:\n raise EndOfStreamError(\n \"Attempted to retrieve frame from stream that already ended.\"\n )\n if video_frame is not None:\n send_video_source_status_update(\n severity=UpdateSeverity.DEBUG,\n event_type=FRAME_CONSUMED_EVENT,\n payload={\n \"frame_timestamp\": video_frame.frame_timestamp,\n \"frame_id\": video_frame.frame_id,\n \"source_id\": video_frame.source_id,\n },\n status_update_handlers=self._status_update_handlers,\n )\n return video_frame"}, {"class_start_lineno": 181, "class_end_lineno": 738, "func_start_lineno": 720, "func_end_lineno": 738, "func_code": " def __next__(self) -> VideoFrame:\n \"\"\"\n Method allowing to use `VideoSource` convenient to read frames\n\n Returns: VideoFrame\n\n Example:\n ```python\n source = VideoSource.init(video_reference=\"./some.mp4\")\n source.start()\n\n for frame in source:\n pass\n ```\n \"\"\"\n try:\n return self.read_frame()\n except EndOfStreamError:\n raise StopIteration()"}], "type": ["function_empty"], "node": ["inference.core.interfaces.camera.video_source.get_from_queue", "inference.core.interfaces.camera.video_source.VideoSource.read_frame", "inference.core.interfaces.camera.video_source.VideoSource.__next__"], "language": "Python", "toolfunc_count": 3, "func_count": 3, "pytest_info": {"total_num": 45, "base_passed_num": 0}} {"id": ["inference.inference.core.utils.preprocess.resize_image_keeping_aspect_ratio", "inference.inference.core.utils.preprocess.letterbox_image"], "project": "inference", "origin_file": ["inference/core/utils/preprocess.py", "inference/core/utils/preprocess.py", "inference/core/interfaces/stream/sinks.py"], "test_list": ["tests/inference/unit_tests/core/interfaces/stream/test_sinks.py", "tests/inference/unit_tests/core/utils/test_drawing.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 298, "func_start_lineno": 253, "func_end_lineno": 298, "func_code": "def resize_image_keeping_aspect_ratio(\n image: ImageMetaType,\n desired_size: Tuple[int, int],\n) -> ImageMetaType:\n \"\"\"\n Resize reserving its aspect ratio.\n\n Parameters:\n - image: numpy array representing the image.\n - desired_size: tuple (width, height) representing the target dimensions.\n \"\"\"\n if isinstance(image, np.ndarray):\n img_ratio = image.shape[1] / image.shape[0]\n elif USE_PYTORCH_FOR_PREPROCESSING:\n img_ratio = image.shape[-1] / image.shape[-2]\n else:\n raise ValueError(\n f\"Received an image of unknown type, {type(image)}; \"\n \"This is most likely a bug. Contact Roboflow team through github issues \"\n \"(https://github.com/roboflow/inference/issues) providing full context of the problem\"\n )\n desired_ratio = desired_size[0] / desired_size[1]\n\n # Determine the new dimensions\n if img_ratio >= desired_ratio:\n # Resize by width\n new_width = desired_size[0]\n new_height = int(desired_size[0] / img_ratio)\n else:\n # Resize by height\n new_height = desired_size[1]\n new_width = int(desired_size[1] * img_ratio)\n\n # Resize the image to new dimensions\n if isinstance(image, np.ndarray):\n return cv2.resize(image, (new_width, new_height))\n elif USE_PYTORCH_FOR_PREPROCESSING:\n return torch.nn.functional.interpolate(\n image, size=(new_height, new_width), mode=\"bilinear\"\n )\n else:\n raise ValueError(\n f\"Received an image of unknown type, {type(image)}; \"\n \"This is most likely a bug. Contact Roboflow team through github issues \"\n \"(https://github.com/roboflow/inference/issues) providing full context of the problem\"\n )"}, {"class_start_lineno": 1, "class_end_lineno": 298, "func_start_lineno": 190, "func_end_lineno": 241, "func_code": "def letterbox_image(\n image: ImageMetaType,\n desired_size: Tuple[int, int],\n color: Tuple[int, int, int] = (0, 0, 0),\n) -> ImageMetaType:\n \"\"\"\n Resize and pad image to fit the desired size, preserving its aspect ratio.\n\n Parameters:\n - image: numpy array representing the image.\n - desired_size: tuple (width, height) representing the target dimensions.\n - color: tuple (B, G, R) representing the color to pad with.\n\n Returns:\n - letterboxed image.\n \"\"\"\n resized_img = resize_image_keeping_aspect_ratio(\n image=image,\n desired_size=desired_size,\n )\n new_height, new_width = (\n resized_img.shape[:2]\n if isinstance(resized_img, np.ndarray)\n else resized_img.shape[-2:]\n )\n top_padding = (desired_size[1] - new_height) // 2\n bottom_padding = desired_size[1] - new_height - top_padding\n left_padding = (desired_size[0] - new_width) // 2\n right_padding = desired_size[0] - new_width - left_padding\n if isinstance(resized_img, np.ndarray):\n return cv2.copyMakeBorder(\n resized_img,\n top_padding,\n bottom_padding,\n left_padding,\n right_padding,\n cv2.BORDER_CONSTANT,\n value=color,\n )\n elif USE_PYTORCH_FOR_PREPROCESSING:\n return torch.nn.functional.pad(\n resized_img,\n (left_padding, right_padding, top_padding, bottom_padding),\n \"constant\",\n color[0],\n )\n else:\n raise ValueError(\n f\"Received an image of unknown type, {type(resized_img)}; \"\n \"This is most likely a bug. Contact Roboflow team through github issues \"\n \"(https://github.com/roboflow/inference/issues) providing full context of the problem\"\n )"}, {"class_start_lineno": 1, "class_end_lineno": 570, "func_start_lineno": 155, "func_end_lineno": 196, "func_code": "def _handle_frame_rendering(\n frame: Optional[VideoFrame],\n prediction: dict,\n annotators: List[BaseAnnotator],\n display_size: Optional[Tuple[int, int]],\n display_statistics: bool,\n fps_value: Optional[float],\n) -> np.ndarray:\n if frame is None:\n image = np.zeros((256, 256, 3), dtype=np.uint8)\n else:\n try:\n labels = [p[\"class\"] for p in prediction[\"predictions\"]]\n if hasattr(sv.Detections, \"from_inference\"):\n detections = sv.Detections.from_inference(prediction)\n else:\n detections = sv.Detections.from_inference(prediction)\n image = frame.image.copy()\n for annotator in annotators:\n kwargs = {\n \"scene\": image,\n \"detections\": detections,\n }\n if isinstance(annotator, sv.LabelAnnotator):\n kwargs[\"labels\"] = labels\n image = annotator.annotate(**kwargs)\n except (TypeError, KeyError):\n logger.warning(\n f\"Used `render_boxes(...)` sink, but predictions that were provided do not match the expected \"\n f\"format of object detection prediction that could be accepted by \"\n f\"`supervision.Detection.from_inference(...)\"\n )\n image = frame.image.copy()\n if display_size is not None:\n image = letterbox_image(image, desired_size=display_size)\n if display_statistics:\n image = render_statistics(\n image=image,\n frame_timestamp=(frame.frame_timestamp if frame is not None else None),\n fps=fps_value,\n )\n return image"}], "type": ["function_empty"], "node": ["inference.core.utils.preprocess.resize_image_keeping_aspect_ratio", "inference.core.utils.preprocess.letterbox_image", "inference.core.interfaces.stream.sinks._handle_frame_rendering"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 21, "base_passed_num": 10}} {"id": ["inference.inference.core.utils.image_utils.validate_numpy_image", "inference.inference.core.utils.image_utils.load_image_from_numpy_str", "inference.inference.core.utils.image_utils.load_image_base64", "inference.inference.core.utils.image_utils.load_image_from_encoded_bytes", "inference.inference.core.utils.image_utils.attempt_loading_image_from_string", "inference.inference.core.utils.image_utils.load_image_with_inferred_type"], "project": "inference", "origin_file": ["inference/core/utils/image_utils.py", "inference/core/utils/image_utils.py", "inference/core/utils/image_utils.py", "inference/core/utils/image_utils.py", "inference/core/utils/image_utils.py", "inference/core/utils/image_utils.py"], "test_list": ["tests/inference/unit_tests/core/utils/test_image_utils.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 599, "func_start_lineno": 353, "func_end_lineno": 377, "func_code": "def validate_numpy_image(data: np.ndarray) -> None:\n \"\"\"\n Validate if the provided data is a valid numpy image.\n\n Args:\n data (np.ndarray): The numpy array representing an image.\n\n Raises:\n InvalidNumpyInput: If the provided data is not a valid numpy image.\n \"\"\"\n if not issubclass(type(data), np.ndarray):\n raise InvalidNumpyInput(\n message=f\"Data provided as input could not be decoded into np.ndarray object.\",\n public_message=f\"Data provided as input could not be decoded into np.ndarray object.\",\n )\n if len(data.shape) != 3 and len(data.shape) != 2:\n raise InvalidNumpyInput(\n message=f\"For image given as np.ndarray expected 2 or 3 dimensions, got {len(data.shape)} dimensions.\",\n public_message=f\"For image given as np.ndarray expected 2 or 3 dimensions.\",\n )\n if data.shape[-1] != 3 and data.shape[-1] != 1:\n raise InvalidNumpyInput(\n message=f\"For image given as np.ndarray expected 1 or 3 channels, got {data.shape[-1]} channels.\",\n public_message=\"For image given as np.ndarray expected 1 or 3 channels.\",\n )"}, {"class_start_lineno": 1, "class_end_lineno": 599, "func_start_lineno": 318, "func_end_lineno": 345, "func_code": "def load_image_from_numpy_str(value: Union[bytes, str]) -> np.ndarray:\n \"\"\"Loads an image from a numpy array string.\n\n Args:\n value (Union[bytes, str]): Base64 string or byte sequence representing the pickled numpy array of the image.\n\n Returns:\n Image.Image: The loaded PIL image.\n\n Raises:\n InvalidNumpyInput: If the numpy data is invalid.\n \"\"\"\n if not ALLOW_NUMPY_INPUT:\n raise InvalidImageTypeDeclared(\n message=f\"NumPy image type is not supported in this configuration of `inference`.\",\n public_message=f\"NumPy image type is not supported in this configuration of `inference`.\",\n )\n try:\n if isinstance(value, str):\n value = pybase64.b64decode(value)\n data = pickle.loads(value)\n except (EOFError, TypeError, pickle.UnpicklingError, binascii.Error) as error:\n raise InvalidNumpyInput(\n message=f\"Could not unpickle image data. Cause: {error}\",\n public_message=\"Could not deserialize pickle payload.\",\n ) from error\n validate_numpy_image(data=data)\n return data"}, {"class_start_lineno": 1, "class_end_lineno": 599, "func_start_lineno": 258, "func_end_lineno": 292, "func_code": "def load_image_base64(\n value: Union[str, bytes], cv_imread_flags=cv2.IMREAD_COLOR\n) -> np.ndarray:\n \"\"\"Loads an image from a base64 encoded string using OpenCV.\n\n Args:\n value (str): Base64 encoded string representing the image.\n\n Returns:\n np.ndarray: The loaded image as a numpy array.\n \"\"\"\n # New routes accept images via json body (str), legacy routes accept bytes which need to be decoded as strings\n if not isinstance(value, str):\n value = value.decode(\"utf-8\")\n value = BASE64_DATA_TYPE_PATTERN.sub(\"\", value)\n try:\n value = pybase64.b64decode(value)\n except binascii.Error as error:\n raise InputImageLoadError(\n message=\"Could not load valid image from base64 string.\",\n public_message=\"Malformed base64 input image.\",\n ) from error\n if len(value) == 0:\n raise InputImageLoadError(\n message=\"Could not load valid image from base64 string.\",\n public_message=\"Empty image payload.\",\n )\n image_np = np.frombuffer(value, np.uint8)\n result = cv2.imdecode(image_np, cv_imread_flags)\n if result is None:\n raise InputImageLoadError(\n message=\"Could not load valid image from base64 string.\",\n public_message=\"Malformed base64 input image.\",\n )\n return result"}, {"class_start_lineno": 1, "class_end_lineno": 599, "func_start_lineno": 496, "func_end_lineno": 516, "func_code": "def load_image_from_encoded_bytes(\n value: bytes, cv_imread_flags: int = cv2.IMREAD_COLOR\n) -> np.ndarray:\n \"\"\"\n Load an image from encoded bytes.\n\n Args:\n value (bytes): The byte sequence representing the image.\n cv_imread_flags (int): OpenCV flags used for image reading.\n\n Returns:\n np.ndarray: The loaded image as a numpy array.\n \"\"\"\n image_np = np.asarray(bytearray(value), dtype=np.uint8)\n image = cv2.imdecode(image_np, cv_imread_flags)\n if image is None:\n raise InputImageLoadError(\n message=f\"Could not decode bytes as image.\",\n public_message=\"Data is not image.\",\n )\n return image"}, {"class_start_lineno": 1, "class_end_lineno": 599, "func_start_lineno": 215, "func_end_lineno": 255, "func_code": "def attempt_loading_image_from_string(\n value: Union[str, bytes, bytearray, _IOBase],\n cv_imread_flags: int = cv2.IMREAD_COLOR,\n) -> Tuple[np.ndarray, bool]:\n \"\"\"\n Attempt to load an image from a string.\n\n Args:\n value (Union[str, bytes, bytearray, _IOBase]): The image data in string format.\n cv_imread_flags (int): OpenCV flags used for image reading.\n\n Returns:\n Tuple[np.ndarray, bool]: A tuple of the loaded image in numpy array format and a boolean flag indicating if the image is in BGR format.\n \"\"\"\n try:\n return load_image_base64(value=value, cv_imread_flags=cv_imread_flags), True\n except:\n pass\n try:\n return (\n load_image_from_encoded_bytes(value=value, cv_imread_flags=cv_imread_flags),\n True,\n )\n except:\n pass\n try:\n return (\n load_image_from_buffer(value=value, cv_imread_flags=cv_imread_flags),\n True,\n )\n except:\n pass\n try:\n return load_image_from_numpy_str(value=value), True\n except InvalidImageTypeDeclared as error:\n raise error\n except InvalidNumpyInput as error:\n raise InputFormatInferenceFailed(\n message=\"Input image format could not be inferred from string.\",\n public_message=\"Input image format could not be inferred from string.\",\n ) from error"}, {"class_start_lineno": 1, "class_end_lineno": 599, "func_start_lineno": 180, "func_end_lineno": 212, "func_code": "def load_image_with_inferred_type(\n value: Any,\n cv_imread_flags: int = cv2.IMREAD_COLOR,\n) -> Tuple[np.ndarray, bool]:\n \"\"\"Load an image by inferring its type.\n\n Args:\n value (Any): The image data.\n cv_imread_flags (int): Flags used for OpenCV's imread function.\n\n Returns:\n Tuple[np.ndarray, bool]: Loaded image as a numpy array and a boolean indicating if the image is in BGR format.\n\n Raises:\n NotImplementedError: If the image type could not be inferred.\n \"\"\"\n if isinstance(value, (np.ndarray, np.generic)):\n validate_numpy_image(data=value)\n return value, True\n elif isinstance(value, Image.Image):\n return np.asarray(value.convert(\"RGB\")), False\n elif isinstance(value, str) and (value.startswith(\"http\")):\n return load_image_from_url(value=value, cv_imread_flags=cv_imread_flags), True\n elif (\n isinstance(value, str)\n and ALLOW_LOADING_IMAGES_FROM_LOCAL_FILESYSTEM\n and os.path.isfile(value)\n ):\n return cv2.imread(value, cv_imread_flags), True\n else:\n return attempt_loading_image_from_string(\n value=value, cv_imread_flags=cv_imread_flags\n )"}], "type": ["function_empty"], "node": ["inference.core.utils.image_utils.validate_numpy_image", "inference.core.utils.image_utils.load_image_from_numpy_str", "inference.core.utils.image_utils.load_image_base64", "inference.core.utils.image_utils.load_image_from_encoded_bytes", "inference.core.utils.image_utils.attempt_loading_image_from_string", "inference.core.utils.image_utils.load_image_with_inferred_type"], "language": "Python", "toolfunc_count": 6, "func_count": 6, "pytest_info": {"total_num": 152, "base_passed_num": 77}} {"id": ["inference.inference.core.utils.postprocess.get_static_crop_dimensions", "inference.inference.core.utils.postprocess.post_process_bboxes", "inference.inference.core.utils.postprocess.post_process_polygons", "inference.inference.core.utils.postprocess.post_process_keypoints"], "project": "inference", "origin_file": ["inference/core/utils/postprocess.py", "inference/core/utils/postprocess.py", "inference/core/utils/postprocess.py", "inference/core/utils/postprocess.py"], "test_list": ["tests/inference/unit_tests/core/utils/test_postprocess.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 658, "func_start_lineno": 473, "func_end_lineno": 513, "func_code": "def get_static_crop_dimensions(\n orig_shape: Tuple[int, int],\n preproc: dict,\n disable_preproc_static_crop: bool = False,\n) -> Tuple[Tuple[int, int], Tuple[int, int]]:\n \"\"\"\n Generates a transformation based on preprocessing configuration.\n\n Args:\n orig_shape (tuple): The original shape of the object (e.g., image) - (height, width).\n preproc (dict): Preprocessing configuration dictionary, containing information such as static cropping.\n disable_preproc_static_crop (bool, optional): If true, the static crop preprocessing step is disabled for this call. Default is False.\n\n Returns:\n tuple: A tuple containing the shift in the x and y directions, and the updated original shape after cropping.\n \"\"\"\n try:\n if static_crop_should_be_applied(\n preprocessing_config=preproc,\n disable_preproc_static_crop=disable_preproc_static_crop,\n ):\n x_min, y_min, x_max, y_max = standardise_static_crop(\n static_crop_config=preproc[STATIC_CROP_KEY]\n )\n else:\n x_min, y_min, x_max, y_max = 0, 0, 1, 1\n crop_shift_x, crop_shift_y = (\n round(x_min * orig_shape[1]),\n round(y_min * orig_shape[0]),\n )\n cropped_percent_x = x_max - x_min\n cropped_percent_y = y_max - y_min\n orig_shape = (\n round(orig_shape[0] * cropped_percent_y),\n round(orig_shape[1] * cropped_percent_x),\n )\n return (crop_shift_x, crop_shift_y), orig_shape\n except KeyError as error:\n raise PostProcessingError(\n f\"Could not find a proper configuration key {error} in post-processing.\"\n )"}, {"class_start_lineno": 1, "class_end_lineno": 658, "func_start_lineno": 98, "func_end_lineno": 163, "func_code": "def post_process_bboxes(\n predictions: List[List[List[float]]],\n infer_shape: Tuple[int, int],\n img_dims: List[Tuple[int, int]],\n preproc: dict,\n disable_preproc_static_crop: bool = False,\n resize_method: str = \"Stretch to\",\n) -> List[List[List[float]]]:\n \"\"\"\n Postprocesses each patch of detections by scaling them to the original image coordinates and by shifting them based on a static crop preproc (if applied).\n\n Args:\n predictions (List[List[List[float]]]): The predictions output from NMS, indices are: batch x prediction x [x1, y1, x2, y2, ...].\n infer_shape (Tuple[int, int]): The shape of the inference image.\n img_dims (List[Tuple[int, int]]): The dimensions of the original image for each batch, indices are: batch x [height, width].\n preproc (dict): Preprocessing configuration dictionary.\n disable_preproc_static_crop (bool, optional): If true, the static crop preprocessing step is disabled for this call. Default is False.\n resize_method (str, optional): Resize method for image. Defaults to \"Stretch to\".\n\n Returns:\n List[List[List[float]]]: The scaled and shifted predictions, indices are: batch x prediction x [x1, y1, x2, y2, ...].\n \"\"\"\n\n # Get static crop params\n scaled_predictions = []\n # Loop through batches\n for i, batch_predictions in enumerate(predictions):\n if len(batch_predictions) == 0:\n scaled_predictions.append([])\n continue\n np_batch_predictions = np.array(batch_predictions)\n # Get bboxes from predictions (x1,y1,x2,y2)\n predicted_bboxes = np_batch_predictions[:, :4]\n (crop_shift_x, crop_shift_y), origin_shape = get_static_crop_dimensions(\n img_dims[i],\n preproc,\n disable_preproc_static_crop=disable_preproc_static_crop,\n )\n if resize_method == \"Stretch to\":\n predicted_bboxes = stretch_bboxes(\n predicted_bboxes=predicted_bboxes,\n infer_shape=infer_shape,\n origin_shape=origin_shape,\n )\n elif (\n resize_method == \"Fit (black edges) in\"\n or resize_method == \"Fit (white edges) in\"\n or resize_method == \"Fit (grey edges) in\"\n ):\n predicted_bboxes = undo_image_padding_for_predicted_boxes(\n predicted_bboxes=predicted_bboxes,\n infer_shape=infer_shape,\n origin_shape=origin_shape,\n )\n predicted_bboxes = clip_boxes_coordinates(\n predicted_bboxes=predicted_bboxes,\n origin_shape=origin_shape,\n )\n predicted_bboxes = shift_bboxes(\n bboxes=predicted_bboxes,\n shift_x=crop_shift_x,\n shift_y=crop_shift_y,\n )\n np_batch_predictions[:, :4] = predicted_bboxes\n scaled_predictions.append(np_batch_predictions.tolist())\n return scaled_predictions"}, {"class_start_lineno": 1, "class_end_lineno": 658, "func_start_lineno": 393, "func_end_lineno": 441, "func_code": "def post_process_polygons(\n origin_shape: Tuple[int, int],\n polys: List[List[Tuple[float, float]]],\n infer_shape: Tuple[int, int],\n preproc: dict,\n resize_method: str = \"Stretch to\",\n) -> List[List[Tuple[float, float]]]:\n \"\"\"Scales and shifts polygons based on the given image shapes and preprocessing method.\n\n This function performs polygon scaling and shifting based on the specified resizing method and\n pre-processing steps. The polygons are transformed according to the ratio and padding between two images.\n\n Args:\n origin_shape (tuple of int): Shape of the source image (height, width).\n infer_shape (tuple of int): Shape of the target image (height, width).\n polys (list of list of tuple): List of polygons, where each polygon is represented by a list of (x, y) coordinates.\n preproc (object): Preprocessing details used for generating the transformation.\n resize_method (str, optional): Resizing method, either \"Stretch to\", \"Fit (black edges) in\", \"Fit (white edges) in\", or \"Fit (grey edges) in\". Defaults to \"Stretch to\".\n\n Returns:\n list of list of tuple: A list of shifted and scaled polygons.\n \"\"\"\n (crop_shift_x, crop_shift_y), origin_shape = get_static_crop_dimensions(\n origin_shape, preproc\n )\n new_polys = []\n if resize_method == \"Stretch to\":\n width_ratio = origin_shape[1] / infer_shape[1]\n height_ratio = origin_shape[0] / infer_shape[0]\n new_polys = scale_polygons(\n polygons=polys,\n x_scale=width_ratio,\n y_scale=height_ratio,\n )\n elif resize_method in {\n \"Fit (black edges) in\",\n \"Fit (white edges) in\",\n \"Fit (grey edges) in\",\n }:\n new_polys = undo_image_padding_for_predicted_polygons(\n polygons=polys,\n infer_shape=infer_shape,\n origin_shape=origin_shape,\n )\n shifted_polys = []\n for poly in new_polys:\n poly = [(p[0] + crop_shift_x, p[1] + crop_shift_y) for p in poly]\n shifted_polys.append(poly)\n return shifted_polys"}, {"class_start_lineno": 1, "class_end_lineno": 658, "func_start_lineno": 522, "func_end_lineno": 585, "func_code": "def post_process_keypoints(\n predictions: List[List[List[float]]],\n keypoints_start_index: int,\n infer_shape: Tuple[int, int],\n img_dims: List[Tuple[int, int]],\n preproc: dict,\n disable_preproc_static_crop: bool = False,\n resize_method: str = \"Stretch to\",\n) -> List[List[List[float]]]:\n \"\"\"Scales and shifts keypoints based on the given image shapes and preprocessing method.\n\n This function performs polygon scaling and shifting based on the specified resizing method and\n pre-processing steps. The polygons are transformed according to the ratio and padding between two images.\n\n Args:\n predictions: predictions from model\n keypoints_start_index: offset in the 3rd dimension pointing where in the prediction start keypoints [(x, y, cfg), ...] for each keypoint class\n img_dims list of (tuple of int): Shape of the source image (height, width).\n infer_shape (tuple of int): Shape of the target image (height, width).\n preproc (object): Preprocessing details used for generating the transformation.\n resize_method (str, optional): Resizing method, either \"Stretch to\", \"Fit (black edges) in\", \"Fit (white edges) in\", or \"Fit (grey edges) in\". Defaults to \"Stretch to\".\n disable_preproc_static_crop: flag to disable static crop\n Returns:\n list of list of list: predictions with post-processed keypoints\n \"\"\"\n # Get static crop params\n scaled_predictions = []\n # Loop through batches\n for i, batch_predictions in enumerate(predictions):\n if len(batch_predictions) == 0:\n scaled_predictions.append([])\n continue\n np_batch_predictions = np.array(batch_predictions)\n keypoints = np_batch_predictions[:, keypoints_start_index:]\n (crop_shift_x, crop_shift_y), origin_shape = get_static_crop_dimensions(\n img_dims[i],\n preproc,\n disable_preproc_static_crop=disable_preproc_static_crop,\n )\n if resize_method == \"Stretch to\":\n keypoints = stretch_keypoints(\n keypoints=keypoints,\n infer_shape=infer_shape,\n origin_shape=origin_shape,\n )\n elif (\n resize_method == \"Fit (black edges) in\"\n or resize_method == \"Fit (white edges) in\"\n or resize_method == \"Fit (grey edges) in\"\n ):\n keypoints = undo_image_padding_for_predicted_keypoints(\n keypoints=keypoints,\n infer_shape=infer_shape,\n origin_shape=origin_shape,\n )\n keypoints = clip_keypoints_coordinates(\n keypoints=keypoints, origin_shape=origin_shape\n )\n keypoints = shift_keypoints(\n keypoints=keypoints, shift_x=crop_shift_x, shift_y=crop_shift_y\n )\n np_batch_predictions[:, keypoints_start_index:] = keypoints\n scaled_predictions.append(np_batch_predictions.tolist())\n return scaled_predictions"}], "type": ["function_empty"], "node": ["inference.core.utils.postprocess.get_static_crop_dimensions", "inference.core.utils.postprocess.post_process_bboxes", "inference.core.utils.postprocess.post_process_polygons", "inference.core.utils.postprocess.post_process_keypoints"], "language": "Python", "toolfunc_count": 4, "func_count": 4, "pytest_info": {"total_num": 54, "base_passed_num": 24}} {"id": ["open-iris.src.iris.utils.math.estimate_diameter", "open-iris.src.iris.nodes.normalization.nonlinear_normalization.NonlinearNormalization::_generate_correspondences"], "project": "open-iris", "origin_file": ["iris/utils/math.py", "iris/nodes/normalization/nonlinear_normalization.py"], "test_list": ["tests/unit_tests/nodes/normalization/test_nonlinear_normalization.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 203, "func_start_lineno": 38, "func_end_lineno": 50, "func_code": "def estimate_diameter(polygon: np.ndarray) -> float:\n \"\"\"Estimates the diameter of an arbitrary arc by evaluating the maximum distance between any two points on the arc.\n\n Args:\n polygon (np.ndarray): Polygon points.\n\n Returns:\n float: Estimated diameter length.\n\n Reference:\n [1] https://sparrow.dev/pairwise-distance-in-numpy/\n \"\"\"\n return float(np.linalg.norm(polygon[:, None, :] - polygon[None, :, :], axis=-1).max())"}, {"class_start_lineno": 13, "class_end_lineno": 113, "func_start_lineno": 89, "func_end_lineno": 113, "func_code": " def _generate_correspondences(self, pupil_points: np.ndarray, iris_points: np.ndarray) -> np.ndarray:\n \"\"\"Generate corresponding positions in original image.\n\n Args:\n pupil_points (np.ndarray): Pupil bounding points. NumPy array of shape (num_points x 2).\n iris_points (np.ndarray): Iris bounding points. NumPy array of shape (num_points x 2).\n\n Returns:\n np.ndarray: generated corresponding points.\n \"\"\"\n pupil_diameter = math.estimate_diameter(pupil_points)\n iris_diameter = math.estimate_diameter(iris_points)\n p2i_ratio = pupil_diameter / iris_diameter\n\n if p2i_ratio <= 0 or p2i_ratio >= 1:\n raise NormalizationError(f\"Invalid pupil to iris ratio, not in the range (0,1): {p2i_ratio}.\")\n\n src_points = np.array(\n [\n pupil_points + x * (iris_points - pupil_points)\n for x in self.params.intermediate_radiuses[round(100 * (p2i_ratio))]\n ]\n )\n\n return np.round(src_points).astype(int)"}], "type": ["function_empty"], "node": ["iris.utils.math.estimate_diameter", "iris.nodes.normalization.nonlinear_normalization.NonlinearNormalization._generate_correspondences"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 3, "base_passed_num": 2}} {"id": ["open-iris.src.iris.utils.math.area", "open-iris.src.iris.nodes.vectorization.contouring.filter_polygon_areas", "open-iris.src.iris.nodes.vectorization.contouring.ContouringAlgorithm::_filter_contours"], "project": "open-iris", "origin_file": ["iris/utils/math.py", "iris/nodes/vectorization/contouring.py", "iris/nodes/vectorization/contouring.py"], "test_list": ["tests/unit_tests/nodes/vectorization/test_contouring.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 203, "func_start_lineno": 7, "func_end_lineno": 35, "func_code": "def area(array: np.ndarray, signed: bool = False) -> float:\n \"\"\"Shoelace formula for simple polygon area calculation.\n\n WARNING: This formula only works for \"simple polygons\", i.e planar polygon without self-intersection nor holes.\n These conditions are not checked within this function.\n\n Args:\n array (np.ndarray): np array representing a polygon as a list of points, i.e. of shape (_, 2).\n signed (bool): If True, the area is signed, i.e. negative if the polygon is oriented clockwise.\n\n Returns:\n float: Polygon area\n\n Raises:\n ValueError: if the input array does not have shape (_, 2)\n\n References:\n [1] https://en.wikipedia.org/wiki/Shoelace_formula\n [2] https://stackoverflow.com/questions/24467972/calculate-area-of-polygon-given-x-y-coordinates\n \"\"\"\n if len(array.shape) != 2 or array.shape[1] != 2:\n raise ValueError(f\"Unable to determine the area of a polygon with shape {array.shape}. Expecting (_, 2).\")\n\n xs, ys = array.T\n area = 0.5 * (np.dot(xs, np.roll(ys, 1)) - np.dot(ys, np.roll(xs, 1)))\n if not signed:\n area = abs(area)\n\n return float(area)"}, {"class_start_lineno": 1, "class_end_lineno": 133, "func_start_lineno": 13, "func_end_lineno": 35, "func_code": "def filter_polygon_areas(\n polygons: List[np.ndarray], rel_tr: NonNegativeFloat = 0.03, abs_tr: NonNegativeFloat = 0.0\n) -> List[np.ndarray]:\n \"\"\"Filter out polygons whose area is below either an absolute threshold or a fraction of the largest area.\n\n Args:\n polygons (List[np.ndarray]): List of polygons to filter.\n rel_tr (NonNegativeFloat, optional): Relative threshold. Defaults to 0.03.\n abs_tr (NonNegativeFloat, optional): Absolute threshold. Defaults to 0.0.\n\n Returns:\n List[np.ndarray]: Filtered polygons' list.\n \"\"\"\n areas = [area(polygon) if len(polygon) > 2 else 1.0 for polygon in polygons]\n area_factors = np.array(areas) / np.max(areas)\n\n filtered_polygons = [\n polygon\n for area, area_factor, polygon in zip(areas, area_factors, polygons)\n if area > abs_tr and area_factor > rel_tr\n ]\n\n return filtered_polygons"}, {"class_start_lineno": 38, "class_end_lineno": 133, "func_start_lineno": 121, "func_end_lineno": 133, "func_code": " def _filter_contours(self, contours: List[np.ndarray]) -> List[np.ndarray]:\n \"\"\"Filter contours based on predefined filters.\n\n Args:\n contours (List[np.ndarray]): Contours list.\n\n Returns:\n List[np.ndarray]: Filtered list of contours.\n \"\"\"\n for filter_func in self.params.contour_filters:\n contours = filter_func(contours)\n\n return contours"}], "type": ["function_empty", "TDD"], "node": ["iris.utils.math.area", "iris.nodes.vectorization.contouring.filter_polygon_areas", "iris.nodes.vectorization.contouring.ContouringAlgorithm._filter_contours"], "language": "Python", "toolfunc_count": 2, "func_count": 3, "pytest_info": {"total_num": 12, "base_passed_num": 9}} {"id": ["open-iris.src.iris.utils.math.cartesian2polar", "open-iris.src.iris.nodes.geometry_estimation.linear_extrapolation.LinearExtrapolation::_estimate"], "project": "open-iris", "origin_file": ["iris/utils/math.py", "iris/nodes/geometry_estimation/linear_extrapolation.py"], "test_list": ["tests/unit_tests/nodes/geometry_estimation/test_linear_extrapolation.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 203, "func_start_lineno": 53, "func_end_lineno": 73, "func_code": "def cartesian2polar(xs: np.ndarray, ys: np.ndarray, center_x: float, center_y: float) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"Convert xs and ys cartesian coordinates to polar coordinates.\n\n Args:\n xs (np.ndarray): x values.\n ys (np.ndarray): y values.\n center_x (float): center's x.\n center_y (float): center's y.\n\n Returns:\n Tuple[np.ndarray, np.ndarray]: Converted coordinates (rhos, phis).\n \"\"\"\n x_rel: np.ndarray = xs - center_x\n y_rel: np.ndarray = ys - center_y\n\n C = np.vectorize(complex)(x_rel, y_rel)\n\n rho = np.abs(C)\n phi = np.angle(C) % (2 * np.pi)\n\n return rho, phi"}, {"class_start_lineno": 12, "class_end_lineno": 82, "func_start_lineno": 58, "func_end_lineno": 82, "func_code": " def _estimate(self, vertices: np.ndarray, center_xy: Tuple[float, float]) -> np.ndarray:\n \"\"\"Estimate a circle fit for a single contour.\n\n Args:\n vertices (np.ndarray): Contour's vertices.\n center_xy (Tuple[float, float]): Contour's center position.\n\n Returns:\n np.ndarray: Estimated polygon.\n \"\"\"\n rhos, phis = math.cartesian2polar(vertices[:, 0], vertices[:, 1], *center_xy)\n\n padded_rhos = np.concatenate([rhos, rhos, rhos])\n padded_phis = np.concatenate([phis - 2 * np.pi, phis, phis + 2 * np.pi])\n\n interpolated_phis = np.arange(padded_phis.min(), padded_phis.max(), np.radians(self.params.dphi))\n interpolated_rhos = np.interp(interpolated_phis, xp=padded_phis, fp=padded_rhos, period=2 * np.pi)\n\n mask = (interpolated_phis >= 0) & (interpolated_phis < 2 * np.pi)\n interpolated_phis, interpolated_rhos = interpolated_phis[mask], interpolated_rhos[mask]\n\n xs, ys = math.polar2cartesian(interpolated_rhos, interpolated_phis, *center_xy)\n estimated_vertices = np.column_stack([xs, ys])\n\n return estimated_vertices"}], "type": ["function_empty", "TDD"], "node": ["iris.utils.math.cartesian2polar", "iris.nodes.geometry_estimation.linear_extrapolation.LinearExtrapolation._estimate"], "language": "Python", "toolfunc_count": 1, "func_count": 2, "pytest_info": {"total_num": 12, "base_passed_num": 0}} {"id": ["open-iris.src.iris.callbacks.pipeline_trace.PipelineCallTraceStorage::get", "open-iris.src.iris.callbacks.pipeline_trace.PipelineCallTraceStorage::__getitem__"], "project": "open-iris", "origin_file": ["iris/callbacks/pipeline_trace.py", "iris/callbacks/pipeline_trace.py"], "test_list": ["tests/unit_tests/callbacks/test_pipeline_trace.py"], "prob_info": [{"class_start_lineno": 16, "class_end_lineno": 146, "func_start_lineno": 52, "func_end_lineno": 67, "func_code": " def get(self, result_name: str) -> Any:\n \"\"\"Get result_name result.\n\n Args:\n result_name (str): Result name.\n\n Raises:\n PipelineCallTraceStorageError: Raised if result_name is not found.\n\n Returns:\n Any: Result object.\n \"\"\"\n if result_name not in self._storage.keys():\n raise PipelineCallTraceStorageError(f\"Unknown result name: {result_name}\")\n\n return self._storage[result_name]"}, {"class_start_lineno": 16, "class_end_lineno": 146, "func_start_lineno": 30, "func_end_lineno": 42, "func_code": " def __getitem__(self, result_name: str) -> Any:\n \"\"\"Get result_name result.\n\n Args:\n result_name (str): Result name.\n\n Raises:\n PipelineCallTraceStorageError: Raised if result_name is not found.\n\n Returns:\n Any: Result object.\n \"\"\"\n return self.get(result_name)"}], "type": ["function_empty"], "node": ["iris.callbacks.pipeline_trace.PipelineCallTraceStorage.get", "iris.callbacks.pipeline_trace.PipelineCallTraceStorage.__getitem__"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 8, "base_passed_num": 2}} {"id": ["open-iris.src.iris.utils.math.cartesian2polar", "open-iris.src.iris.nodes.eye_properties_estimation.occlusion_calculator.OcclusionCalculator::_get_quantile_points"], "project": "open-iris", "origin_file": ["iris/utils/math.py", "iris/nodes/eye_properties_estimation/occlusion_calculator.py"], "test_list": ["tests/unit_tests/nodes/eye_properties_estimation/test_occlusion_calculator.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 203, "func_start_lineno": 53, "func_end_lineno": 73, "func_code": "def cartesian2polar(xs: np.ndarray, ys: np.ndarray, center_x: float, center_y: float) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"Convert xs and ys cartesian coordinates to polar coordinates.\n\n Args:\n xs (np.ndarray): x values.\n ys (np.ndarray): y values.\n center_x (float): center's x.\n center_y (float): center's y.\n\n Returns:\n Tuple[np.ndarray, np.ndarray]: Converted coordinates (rhos, phis).\n \"\"\"\n x_rel: np.ndarray = xs - center_x\n y_rel: np.ndarray = ys - center_y\n\n C = np.vectorize(complex)(x_rel, y_rel)\n\n rho = np.abs(C)\n phi = np.angle(C) % (2 * np.pi)\n\n return rho, phi"}, {"class_start_lineno": 12, "class_end_lineno": 142, "func_start_lineno": 99, "func_end_lineno": 142, "func_code": " def _get_quantile_points(\n self, iris_coords: np.ndarray, eye_orientation: EyeOrientation, eye_centers: EyeCenters\n ) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"Get those iris's points which fall into a specified quantile.\n\n Args:\n iris_coords (np.ndarray): Iris polygon coordinates.\n eye_orientation: (EyeOrientation): Eye orientation.\n eye_centers: (EyeCenters): Eye centers.\n\n Returns:\n Tuple[np.ndarray, np.ndarray]: Tuple with xs and ys that falls into quantile region.\n \"\"\"\n orientation_angle = np.degrees(eye_orientation.angle)\n num_rotations = -round(orientation_angle * len(iris_coords) / 360.0)\n\n iris_xs, iris_ys = iris_coords[:, 0], iris_coords[:, 1]\n iris_rhos, iris_phis = math.cartesian2polar(iris_xs, iris_ys, eye_centers.iris_x, eye_centers.iris_y)\n\n iris_phis = np.roll(iris_phis, num_rotations, axis=0)\n iris_rhos = np.roll(iris_rhos, num_rotations, axis=0)\n\n scaled_quantile = round(self.params.quantile_angle * len(iris_coords) / 360.0)\n\n phis2mask = np.concatenate(\n [\n iris_phis[:scaled_quantile],\n iris_phis[-scaled_quantile:],\n iris_phis[len(iris_phis) // 2 : len(iris_phis) // 2 + scaled_quantile],\n iris_phis[len(iris_phis) // 2 - scaled_quantile : len(iris_phis) // 2],\n ]\n )\n rhos2mask = np.concatenate(\n [\n iris_rhos[:scaled_quantile],\n iris_rhos[-scaled_quantile:],\n iris_rhos[len(iris_rhos) // 2 : len(iris_rhos) // 2 + scaled_quantile],\n iris_rhos[len(iris_rhos) // 2 - scaled_quantile : len(iris_rhos) // 2],\n ]\n )\n phis2mask, rhos2mask = zip(*sorted(zip(phis2mask, rhos2mask)))\n xs2mask, ys2mask = math.polar2cartesian(rhos2mask, phis2mask, eye_centers.iris_x, eye_centers.iris_y)\n\n return xs2mask, ys2mask"}], "type": ["function_empty", "TDD"], "node": ["iris.utils.math.cartesian2polar", "iris.nodes.eye_properties_estimation.occlusion_calculator.OcclusionCalculator._get_quantile_points"], "language": "Python", "toolfunc_count": 1, "func_count": 2, "pytest_info": {"total_num": 19, "base_passed_num": 1}} {"id": ["open-iris.src.iris.nodes.eye_properties_estimation.bisectors_method.BisectorsMethod::_calculate_perpendicular_bisectors", "open-iris.src.iris.nodes.eye_properties_estimation.bisectors_method.BisectorsMethod::_find_center_coords"], "project": "open-iris", "origin_file": ["iris/nodes/eye_properties_estimation/bisectors_method.py", "iris/nodes/eye_properties_estimation/bisectors_method.py"], "test_list": ["tests/unit_tests/nodes/eye_properties_estimation/test_bisectors_method.py", "tests/unit_tests/nodes/eye_properties_estimation/test_pupil_iris_property_calculator.py"], "prob_info": [{"class_start_lineno": 11, "class_end_lineno": 170, "func_start_lineno": 84, "func_end_lineno": 140, "func_code": " def _calculate_perpendicular_bisectors(\n self, polygon: np.ndarray, min_distance_between_sector_points_in_px: float\n ) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"Calculate the perpendicular bisector of self.params.num_bisectors randomly chosen points from a polygon's vertices.\n A pair of points is used if their distance is larger then min_distance_between_sector_points_in_px.\n\n Args:\n polygon (np.ndarray): np.ndarray based on which we are searching the center of a circular shape.\n min_distance_between_sector_points_in_px (float): Minimum distance between sector points.\n\n Raises:\n EyeCentersEstimationError: Raised if not able to find enough random pairs of points on the arc with a large enough distance!\n\n Returns:\n Tuple[np.ndarray, np.ndarray]: Calculated perpendicular bisectors.\n \"\"\"\n np.random.seed(142857)\n\n bisectors_first_points = np.empty([0, 2])\n bisectors_second_points = np.empty([0, 2])\n for _ in range(self.params.max_iterations):\n random_indices = np.random.choice(len(polygon), size=(self.params.num_bisectors, 2))\n\n first_drawn_points = polygon[random_indices[:, 0]]\n second_drawn_points = polygon[random_indices[:, 1]]\n\n norms = np.linalg.norm(first_drawn_points - second_drawn_points, axis=1)\n mask = norms > min_distance_between_sector_points_in_px\n\n bisectors_first_points = np.vstack([bisectors_first_points, first_drawn_points[mask]])\n bisectors_second_points = np.vstack([bisectors_second_points, second_drawn_points[mask]])\n\n if len(bisectors_first_points) >= self.params.num_bisectors:\n break\n else:\n raise EyeCentersEstimationError(\n \"Not able to find enough random pairs of points on the arc with a large enough distance!\"\n )\n\n bisectors_first_points = bisectors_first_points[: self.params.num_bisectors]\n bisectors_second_points = bisectors_second_points[: self.params.num_bisectors]\n\n bisectors_center = (bisectors_first_points + bisectors_second_points) / 2\n\n # Flip xs with ys and flip sign of on of them to create a 90deg rotation\n inv_bisectors_center_slope = np.fliplr(bisectors_second_points - bisectors_first_points)\n inv_bisectors_center_slope[:, 1] = -inv_bisectors_center_slope[:, 1]\n\n # Add perpendicular vector to center and normalize\n norm = np.linalg.norm(inv_bisectors_center_slope, axis=1)\n inv_bisectors_center_slope[:, 0] /= norm\n inv_bisectors_center_slope[:, 1] /= norm\n\n first_bisectors_point = bisectors_center - inv_bisectors_center_slope\n second_bisectors_point = bisectors_center + inv_bisectors_center_slope\n\n return first_bisectors_point, second_bisectors_point"}, {"class_start_lineno": 11, "class_end_lineno": 170, "func_start_lineno": 66, "func_end_lineno": 82, "func_code": " def _find_center_coords(self, polygon: np.ndarray, diameter: float) -> Tuple[float, float]:\n \"\"\"Find center coordinates of a polygon.\n\n Args:\n polygon (np.ndarray): np.ndarray.\n diameter (float): diameter of the polygon.\n\n Returns:\n Tuple[float, float]: Tuple with the center location coordinates (x, y).\n \"\"\"\n min_distance_between_sector_points_in_px = self.params.min_distance_between_sector_points * diameter\n\n first_bisectors_point, second_bisectors_point = self._calculate_perpendicular_bisectors(\n polygon, min_distance_between_sector_points_in_px\n )\n\n return self._find_best_intersection(first_bisectors_point, second_bisectors_point)"}], "type": ["function_empty", "TDD"], "node": ["iris.nodes.eye_properties_estimation.bisectors_method.BisectorsMethod._calculate_perpendicular_bisectors", "iris.nodes.eye_properties_estimation.bisectors_method.BisectorsMethod._find_center_coords"], "language": "Python", "toolfunc_count": 1, "func_count": 2, "pytest_info": {"total_num": 20, "base_passed_num": 12}} {"id": ["open-iris.src.iris.utils.math.cartesian2polar", "open-iris.src.iris.nodes.geometry_refinement.smoothing.Smoothing::_cut_into_arcs", "open-iris.src.iris.nodes.geometry_refinement.smoothing.Smoothing::_smooth_arc", "open-iris.src.iris.nodes.geometry_refinement.smoothing.Smoothing::_smooth_circular_shape"], "project": "open-iris", "origin_file": ["iris/utils/math.py", "iris/nodes/geometry_refinement/smoothing.py", "iris/nodes/geometry_refinement/smoothing.py", "iris/nodes/geometry_refinement/smoothing.py"], "test_list": ["tests/unit_tests/nodes/geometry_refinement/test_smoothing.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 203, "func_start_lineno": 53, "func_end_lineno": 73, "func_code": "def cartesian2polar(xs: np.ndarray, ys: np.ndarray, center_x: float, center_y: float) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"Convert xs and ys cartesian coordinates to polar coordinates.\n\n Args:\n xs (np.ndarray): x values.\n ys (np.ndarray): y values.\n center_x (float): center's x.\n center_y (float): center's y.\n\n Returns:\n Tuple[np.ndarray, np.ndarray]: Converted coordinates (rhos, phis).\n \"\"\"\n x_rel: np.ndarray = xs - center_x\n y_rel: np.ndarray = ys - center_y\n\n C = np.vectorize(complex)(x_rel, y_rel)\n\n rho = np.abs(C)\n phi = np.angle(C) % (2 * np.pi)\n\n return rho, phi"}, {"class_start_lineno": 12, "class_end_lineno": 256, "func_start_lineno": 84, "func_end_lineno": 119, "func_code": " def _cut_into_arcs(self, polygon: np.ndarray, center_xy: Tuple[float, float]) -> Tuple[List[np.ndarray], int]:\n \"\"\"Cut contour into arcs.\n\n Args:\n polygon (np.ndarray): Contour polygon.\n center_xy (Tuple[float, float]): Polygon's center.\n\n Returns:\n Tuple[List[np.ndarray], int]: Tuple with: (list of list of vertices, number of gaps detected in a contour).\n \"\"\"\n rho, phi = math.cartesian2polar(polygon[:, 0], polygon[:, 1], *center_xy)\n phi, rho = self._sort_two_arrays(phi, rho)\n\n differences = np.abs(phi - np.roll(phi, -1))\n # True distance between first and last point\n differences[-1] = 2 * np.pi - differences[-1]\n\n gap_indices = np.argwhere(differences > np.radians(self.params.gap_threshold)).flatten()\n\n if gap_indices.size < 2:\n return [polygon], gap_indices.size\n\n gap_indices += 1\n phi, rho = np.split(phi, gap_indices), np.split(rho, gap_indices)\n\n arcs = [\n np.column_stack(math.polar2cartesian(rho_coords, phi_coords, *center_xy))\n for rho_coords, phi_coords in zip(rho, phi)\n ]\n\n # Connect arc which lies between 0 and 2π.\n if len(arcs) == gap_indices.size + 1:\n arcs[0] = np.vstack([arcs[0], arcs[-1]])\n arcs = arcs[:-1]\n\n return arcs, gap_indices.size"}, {"class_start_lineno": 12, "class_end_lineno": 256, "func_start_lineno": 121, "func_end_lineno": 144, "func_code": " def _smooth_arc(self, vertices: np.ndarray, center_xy: Tuple[float, float]) -> np.ndarray:\n \"\"\"Smooth a single contour arc.\n\n Args:\n vertices (np.ndarray): Arc's vertices.\n center_xy (Tuple[float, float]): Center of an entire contour.\n\n Returns:\n np.ndarray: Smoothed arc's vertices.\n \"\"\"\n rho, phi = math.cartesian2polar(vertices[:, 0], vertices[:, 1], *center_xy)\n phi, rho = self._sort_two_arrays(phi, rho)\n\n idx = self._find_start_index(phi)\n offset = phi[idx]\n relative_phi = (phi - offset) % (2 * np.pi)\n\n smoothed_relative_phi, smoothed_rho = self._smooth_array(relative_phi, rho)\n\n smoothed_phi = (smoothed_relative_phi + offset) % (2 * np.pi)\n\n x_smoothed, y_smoothed = math.polar2cartesian(smoothed_rho, smoothed_phi, *center_xy)\n\n return np.column_stack([x_smoothed, y_smoothed])"}, {"class_start_lineno": 12, "class_end_lineno": 256, "func_start_lineno": 146, "func_end_lineno": 168, "func_code": " def _smooth_circular_shape(self, vertices: np.ndarray, center_xy: Tuple[float, float]) -> np.ndarray:\n \"\"\"Smooth arc in a form of a circular shape.\n\n Args:\n vertices (np.ndarray): Arc's vertices.\n center_xy (Tuple[float, float]): Center of an entire contour.\n\n Returns:\n np.ndarray: Smoothed arc's vertices.\n \"\"\"\n rho, phi = math.cartesian2polar(vertices[:, 0], vertices[:, 1], *center_xy)\n\n padded_phi = np.concatenate([phi - 2 * np.pi, phi, phi + 2 * np.pi])\n padded_rho = np.concatenate([rho, rho, rho])\n\n smoothed_phi, smoothed_rho = self._smooth_array(padded_phi, padded_rho)\n\n mask = (smoothed_phi >= 0) & (smoothed_phi < 2 * np.pi)\n rho_smoothed, phi_smoothed = smoothed_rho[mask], smoothed_phi[mask]\n\n x_smoothed, y_smoothed = math.polar2cartesian(rho_smoothed, phi_smoothed, *center_xy)\n\n return np.column_stack([x_smoothed, y_smoothed])"}], "type": ["function_empty", "TDD"], "node": ["iris.utils.math.cartesian2polar", "iris.nodes.geometry_refinement.smoothing.Smoothing._cut_into_arcs", "iris.nodes.geometry_refinement.smoothing.Smoothing._smooth_arc", "iris.nodes.geometry_refinement.smoothing.Smoothing._smooth_circular_shape"], "language": "Python", "toolfunc_count": 2, "func_count": 4, "pytest_info": {"total_num": 12, "base_passed_num": 5}} {"id": ["open-iris.src.iris.pipelines.iris_pipeline.IRISPipeline::instanciate_class", "open-iris.src.iris.pipelines.iris_pipeline.IRISPipeline::instanciate_pipeline", "open-iris.src.iris.pipelines.iris_pipeline.IRISPipeline::instanciate_node", "open-iris.src.iris.pipelines.iris_pipeline.IRISPipeline::instanciate_nodes"], "project": "open-iris", "origin_file": ["iris/pipelines/iris_pipeline.py", "iris/pipelines/iris_pipeline.py", "iris/pipelines/iris_pipeline.py", "iris/pipelines/iris_pipeline.py"], "test_list": ["tests/unit_tests/pipelines/test_iris_pipeline.py"], "prob_info": [{"class_start_lineno": 27, "class_end_lineno": 324, "func_start_lineno": 225, "func_end_lineno": 245, "func_code": " def instanciate_class(self, class_name: str, kwargs: Dict[str, Any]) -> Callable:\n \"\"\"Instanciate a class from its string definition and its kwargs.\n\n This function relies on pydoc.locate, a safe way to instanciate a class from its string definition, which itself relies on pydoc.safe_import.\n\n Args:\n class_name (str): name of the class.\n kwargs (Dict): kwargs to pass to the class at instanciation time\n\n Returns:\n Callable: the instanciated class\n\n Raises:\n IRISPipelineError: Raised if the class cannot be located.\n \"\"\"\n object_class = pydoc.locate(class_name)\n\n if object_class is None:\n raise IRISPipelineError(f\"Could not locate class {class_name}\")\n\n return object_class(**kwargs)"}, {"class_start_lineno": 27, "class_end_lineno": 324, "func_start_lineno": 179, "func_end_lineno": 200, "func_code": " def instanciate_pipeline(self) -> List[PipelineNode]:\n \"\"\"Given a list of PipelineNodes, crawl the parameters and instanciate the PipelineClass available.\n\n Returns:\n List[PipelineNode]: pipeline with instanciated parameters\n \"\"\"\n instanciated_pipeline = []\n for node in self.params.pipeline:\n current_node = node\n for param_name, param_value in node.algorithm.params.items():\n if isinstance(param_value, (tuple, list)):\n for i, value in enumerate(param_value):\n if isinstance(value, PipelineClass):\n current_node.algorithm.params[param_name][i] = self.instanciate_class(\n class_name=value.class_name, kwargs=value.params\n )\n elif isinstance(param_value, PipelineClass):\n current_node.algorithm.params[param_name] = self.instanciate_class(\n class_name=param_value.class_name, kwargs=param_value.params\n )\n instanciated_pipeline.append(current_node)\n return instanciated_pipeline"}, {"class_start_lineno": 27, "class_end_lineno": 324, "func_start_lineno": 202, "func_end_lineno": 223, "func_code": " def instanciate_node(\n self, node_class: str, algorithm_params: Dict[str, Any], callbacks: Optional[List[PipelineClass]]\n ) -> Algorithm:\n \"\"\"Instanciate an Algorithm from its class, kwargs and optional Callbacks.\n\n NOTE: All callbacks of type listed in self.env.disabled_qa will be filtered out. This allows one config file to be used in various QA standards levels.\n\n Args:\n node_class (str): Node's class.\n algorithm_params (Dict[str, Any]): Node's kwargs.\n callbacks (Optional[List[PipelineClass]]): list of callbacks.\n\n Returns:\n Algorithm: instanciated node.\n \"\"\"\n if callbacks is not None and len(callbacks):\n instanciated_callbacks = [self.instanciate_class(cb.class_name, cb.params) for cb in callbacks]\n instanciated_callbacks = [cb for cb in instanciated_callbacks if type(cb) not in self.env.disabled_qa]\n\n algorithm_params = {**algorithm_params, **{\"callbacks\": instanciated_callbacks}}\n\n return self.instanciate_class(node_class, algorithm_params)"}, {"class_start_lineno": 27, "class_end_lineno": 324, "func_start_lineno": 159, "func_end_lineno": 177, "func_code": " def instanciate_nodes(self) -> Dict[str, Algorithm]:\n \"\"\"Given a list of PipelineNode, return the associated instanciated nodes.\n\n NOTE: All nodes of type listed in self.env.disabled_qa will be filtered out. This allows one config file to be used in various QA standards levels.\n\n Returns:\n Dict[str, Algorithm]: instanciated nodes.\n \"\"\"\n instanciated_pipeline = self.instanciate_pipeline()\n nodes = {\n node.name: self.instanciate_node(\n node_class=node.algorithm.class_name,\n algorithm_params=node.algorithm.params,\n callbacks=node.callbacks,\n )\n for node in instanciated_pipeline\n }\n nodes = {node_name: node for node_name, node in nodes.items() if type(node) not in self.env.disabled_qa}\n return nodes"}], "type": ["function_empty", "TDD"], "node": ["iris.pipelines.iris_pipeline.IRISPipeline.instanciate_class", "iris.pipelines.iris_pipeline.IRISPipeline.instanciate_pipeline", "iris.pipelines.iris_pipeline.IRISPipeline.instanciate_node", "iris.pipelines.iris_pipeline.IRISPipeline.instanciate_nodes"], "language": "Python", "toolfunc_count": 1, "func_count": 4, "pytest_info": {"total_num": 33, "base_passed_num": 0}} {"id": ["open-iris.src.iris.io.validators.is_binary", "open-iris.src.iris.nodes.binarization.specular_reflection_detection.SpecularReflectionDetection::run"], "project": "open-iris", "origin_file": ["iris/io/validators.py", "iris/nodes/binarization/specular_reflection_detection.py"], "test_list": ["tests/unit_tests/nodes/binarization/test_specular_reflection_detection.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 277, "func_start_lineno": 40, "func_end_lineno": 57, "func_code": "def is_binary(cls: type, v: np.ndarray, field: fields.ModelField) -> np.ndarray:\n \"\"\"Check if array has only boolean values, i.e. is binary.\n\n Args:\n cls (type): Class type.\n v (np.ndarray): Value to check.\n field (fields.ModelField): Field descriptor.\n\n Raises:\n ValueError: Exception raised if array doesn't contain bool datatypes.\n\n Returns:\n np.ndarray: `v` sent for further processing.\n \"\"\"\n if v.dtype != np.dtype(\"bool\"):\n raise ValueError(f\"{cls.__name__}: {field.name} must be binary. got dtype {v.dtype}\")\n\n return v"}, {"class_start_lineno": 8, "class_end_lineno": 40, "func_start_lineno": 26, "func_end_lineno": 40, "func_code": " def run(self, ir_image: IRImage) -> NoiseMask:\n \"\"\"Thresholds an IRImage to detect Specular Reflection.\n\n Args:\n ir_image (IRImage): Infrared image object.\n\n Returns:\n NoiseMask: a binary map of the thresholded IRImage.\n \"\"\"\n _, reflection_segmap = cv2.threshold(\n ir_image.img_data, self.params.reflection_threshold, 255, cv2.THRESH_BINARY\n )\n reflection_segmap = (reflection_segmap / 255.0).astype(bool)\n\n return NoiseMask(mask=reflection_segmap)"}], "type": ["function_empty"], "node": ["iris.io.validators.is_binary", "iris.nodes.binarization.specular_reflection_detection.SpecularReflectionDetection.run"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 4, "base_passed_num": 0}} {"id": ["transformers.src.transformers.image_utils.infer_channel_dimension_format", "transformers.src.transformers.image_transforms.to_channel_dimension_format", "transformers.src.transformers.image_utils.get_image_size", "transformers.src.transformers.image_transforms.flip_channel_order"], "project": "transformers", "origin_file": ["transformers/image_utils.py", "transformers/image_transforms.py", "transformers/image_utils.py", "transformers/image_transforms.py"], "test_list": ["tests/test_image_transforms.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 811, "func_start_lineno": 220, "func_end_lineno": 254, "func_code": "def infer_channel_dimension_format(\n image: np.ndarray, num_channels: Optional[Union[int, Tuple[int, ...]]] = None\n) -> ChannelDimension:\n \"\"\"\n Infers the channel dimension format of `image`.\n\n Args:\n image (`np.ndarray`):\n The image to infer the channel dimension of.\n num_channels (`int` or `Tuple[int, ...]`, *optional*, defaults to `(1, 3)`):\n The number of channels of the image.\n\n Returns:\n The channel dimension of the image.\n \"\"\"\n num_channels = num_channels if num_channels is not None else (1, 3)\n num_channels = (num_channels,) if isinstance(num_channels, int) else num_channels\n\n if image.ndim == 3:\n first_dim, last_dim = 0, 2\n elif image.ndim == 4:\n first_dim, last_dim = 1, 3\n else:\n raise ValueError(f\"Unsupported number of image dimensions: {image.ndim}\")\n\n if image.shape[first_dim] in num_channels and image.shape[last_dim] in num_channels:\n logger.warning(\n f\"The channel dimension is ambiguous. Got image shape {image.shape}. Assuming channels are the first dimension.\"\n )\n return ChannelDimension.FIRST\n elif image.shape[first_dim] in num_channels:\n return ChannelDimension.FIRST\n elif image.shape[last_dim] in num_channels:\n return ChannelDimension.LAST\n raise ValueError(\"Unable to infer channel dimension format\")"}, {"class_start_lineno": 1, "class_end_lineno": 854, "func_start_lineno": 58, "func_end_lineno": 94, "func_code": "def to_channel_dimension_format(\n image: np.ndarray,\n channel_dim: Union[ChannelDimension, str],\n input_channel_dim: Optional[Union[ChannelDimension, str]] = None,\n) -> np.ndarray:\n \"\"\"\n Converts `image` to the channel dimension format specified by `channel_dim`.\n\n Args:\n image (`numpy.ndarray`):\n The image to have its channel dimension set.\n channel_dim (`ChannelDimension`):\n The channel dimension format to use.\n input_channel_dim (`ChannelDimension`, *optional*):\n The channel dimension format of the input image. If not provided, it will be inferred from the input image.\n\n Returns:\n `np.ndarray`: The image with the channel dimension set to `channel_dim`.\n \"\"\"\n if not isinstance(image, np.ndarray):\n raise TypeError(f\"Input image must be of type np.ndarray, got {type(image)}\")\n\n if input_channel_dim is None:\n input_channel_dim = infer_channel_dimension_format(image)\n\n target_channel_dim = ChannelDimension(channel_dim)\n if input_channel_dim == target_channel_dim:\n return image\n\n if target_channel_dim == ChannelDimension.FIRST:\n image = image.transpose((2, 0, 1))\n elif target_channel_dim == ChannelDimension.LAST:\n image = image.transpose((1, 2, 0))\n else:\n raise ValueError(\"Unsupported channel dimension format: {}\".format(channel_dim))\n\n return image"}, {"class_start_lineno": 1, "class_end_lineno": 811, "func_start_lineno": 281, "func_end_lineno": 302, "func_code": "def get_image_size(image: np.ndarray, channel_dim: ChannelDimension = None) -> Tuple[int, int]:\n \"\"\"\n Returns the (height, width) dimensions of the image.\n\n Args:\n image (`np.ndarray`):\n The image to get the dimensions of.\n channel_dim (`ChannelDimension`, *optional*):\n Which dimension the channel dimension is in. If `None`, will infer the channel dimension from the image.\n\n Returns:\n A tuple of the image's height and width.\n \"\"\"\n if channel_dim is None:\n channel_dim = infer_channel_dimension_format(image)\n\n if channel_dim == ChannelDimension.FIRST:\n return image.shape[-2], image.shape[-1]\n elif channel_dim == ChannelDimension.LAST:\n return image.shape[-3], image.shape[-2]\n else:\n raise ValueError(f\"Unsupported data format: {channel_dim}\")"}, {"class_start_lineno": 1, "class_end_lineno": 854, "func_start_lineno": 774, "func_end_lineno": 809, "func_code": "def flip_channel_order(\n image: np.ndarray,\n data_format: Optional[ChannelDimension] = None,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n) -> np.ndarray:\n \"\"\"\n Flips the channel order of the image.\n\n If the image is in RGB format, it will be converted to BGR and vice versa.\n\n Args:\n image (`np.ndarray`):\n The image to flip.\n data_format (`ChannelDimension`, *optional*):\n The channel dimension format for the output image. Can be one of:\n - `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n If unset, will use same as the input image.\n input_data_format (`ChannelDimension`, *optional*):\n The channel dimension format for the input image. Can be one of:\n - `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n If unset, will use the inferred format of the input image.\n \"\"\"\n input_data_format = infer_channel_dimension_format(image) if input_data_format is None else input_data_format\n\n if input_data_format == ChannelDimension.LAST:\n image = image[..., ::-1]\n elif input_data_format == ChannelDimension.FIRST:\n image = image[::-1, ...]\n else:\n raise ValueError(f\"Unsupported channel dimension: {input_data_format}\")\n\n if data_format is not None:\n image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)\n return image"}], "type": ["function_empty"], "node": ["transformers.image_utils.infer_channel_dimension_format", "transformers.image_transforms.to_channel_dimension_format", "transformers.image_utils.get_image_size", "transformers.image_transforms.flip_channel_order"], "language": "Python", "toolfunc_count": 4, "func_count": 4, "pytest_info": {"total_num": 24, "base_passed_num": 5}} {"id": ["transformers.src.transformers.utils.logging._configure_library_root_logger", "transformers.src.transformers.utils.logging.get_logger", "transformers.src.transformers.generation.configuration_utils.GenerationConfig::to_diff_dict", "transformers.src.transformers.generation.configuration_utils.GenerationConfig::to_json_string"], "project": "transformers", "origin_file": ["transformers/utils/logging.py", "transformers/utils/logging.py", "transformers/generation/configuration_utils.py", "transformers/generation/configuration_utils.py", "transformers/generation/configuration_utils.py"], "test_list": ["tests/benchmark/test_benchmark.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 410, "func_start_lineno": 81, "func_end_lineno": 104, "func_code": "def _configure_library_root_logger() -> None:\n global _default_handler\n\n with _lock:\n if _default_handler:\n # This library has already configured the library root logger.\n return\n _default_handler = logging.StreamHandler() # Set sys.stderr as stream.\n # set defaults based on https://github.com/pyinstaller/pyinstaller/issues/7334#issuecomment-1357447176\n if sys.stderr is None:\n sys.stderr = open(os.devnull, \"w\")\n\n _default_handler.flush = sys.stderr.flush\n\n # Apply our default configuration to the library root logger.\n library_root_logger = _get_library_root_logger()\n library_root_logger.addHandler(_default_handler)\n library_root_logger.setLevel(_get_default_logging_level())\n # if logging level is debug, we add pathname and lineno to formatter for easy debugging\n if os.getenv(\"TRANSFORMERS_VERBOSITY\", None) == \"detail\":\n formatter = logging.Formatter(\"[%(levelname)s|%(pathname)s:%(lineno)s] %(asctime)s >> %(message)s\")\n _default_handler.setFormatter(formatter)\n\n library_root_logger.propagate = False"}, {"class_start_lineno": 1, "class_end_lineno": 410, "func_start_lineno": 147, "func_end_lineno": 158, "func_code": "def get_logger(name: Optional[str] = None) -> logging.Logger:\n \"\"\"\n Return a logger with the specified name.\n\n This function is not supposed to be directly accessed unless you are writing a custom transformers module.\n \"\"\"\n\n if name is None:\n name = _get_library_name()\n\n _configure_library_root_logger()\n return logging.getLogger(name)"}, {"class_start_lineno": 94, "class_end_lineno": 1274, "func_start_lineno": 1109, "func_end_lineno": 1130, "func_code": " def to_diff_dict(self) -> Dict[str, Any]:\n \"\"\"\n Removes all attributes from config which correspond to the default config attributes for better readability and\n serializes to a Python dictionary.\n\n Returns:\n `Dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance,\n \"\"\"\n config_dict = self.to_dict()\n\n # get the default config dict\n default_config_dict = GenerationConfig().to_dict()\n\n serializable_config_dict = {}\n\n # only serialize values that differ from the default config\n for key, value in config_dict.items():\n if key not in default_config_dict or key == \"transformers_version\" or value != default_config_dict[key]:\n serializable_config_dict[key] = value\n\n self.dict_torch_dtype_to_str(serializable_config_dict)\n return serializable_config_dict"}, {"class_start_lineno": 94, "class_end_lineno": 1274, "func_start_lineno": 1153, "func_end_lineno": 1195, "func_code": " def to_json_string(self, use_diff: bool = True, ignore_metadata: bool = False) -> str:\n \"\"\"\n Serializes this instance to a JSON string.\n\n Args:\n use_diff (`bool`, *optional*, defaults to `True`):\n If set to `True`, only the difference between the config instance and the default `GenerationConfig()`\n is serialized to JSON string.\n ignore_metadata (`bool`, *optional*, defaults to `False`):\n Whether to ignore the metadata fields present in the instance\n\n Returns:\n `str`: String containing all the attributes that make up this configuration instance in JSON format.\n \"\"\"\n if use_diff is True:\n config_dict = self.to_diff_dict()\n else:\n config_dict = self.to_dict()\n\n if ignore_metadata:\n for metadata_field in METADATA_FIELDS:\n config_dict.pop(metadata_field, None)\n\n def convert_keys_to_string(obj):\n if isinstance(obj, dict):\n return {str(key): convert_keys_to_string(value) for key, value in obj.items()}\n elif isinstance(obj, list):\n return [convert_keys_to_string(item) for item in obj]\n else:\n return obj\n\n def convert_dataclass_to_dict(obj):\n if isinstance(obj, dict):\n return {key: convert_dataclass_to_dict(value) for key, value in obj.items()}\n elif is_dataclass(obj):\n return obj.to_dict()\n else:\n return obj\n\n config_dict = convert_keys_to_string(config_dict)\n config_dict = convert_dataclass_to_dict(config_dict)\n\n return json.dumps(config_dict, indent=2, sort_keys=True) + \"\\n\""}, {"class_start_lineno": 94, "class_end_lineno": 1274, "func_start_lineno": 480, "func_end_lineno": 481, "func_code": " def __hash__(self):\n return hash(self.to_json_string(ignore_metadata=True))"}], "type": ["function_empty", "TDD"], "node": ["transformers.utils.logging._configure_library_root_logger", "transformers.utils.logging.get_logger", "transformers.generation.configuration_utils.GenerationConfig.to_diff_dict", "transformers.generation.configuration_utils.GenerationConfig.to_json_string", "transformers.generation.configuration_utils.GenerationConfig.__hash__"], "language": "Python", "toolfunc_count": 3, "func_count": 4, "pytest_info": {"total_num": 11, "base_passed_num": 0}} {"id": ["transformers.src.transformers.utils.generic.infer_framework_from_repr", "transformers.src.transformers.utils.generic._get_frameworks_and_test_func", "transformers.src.transformers.image_processing_utils.get_size_dict", "transformers.src.transformers.image_transforms.resize", "transformers.src.transformers.models.blip.image_processing_blip.BlipImageProcessor::resize"], "project": "transformers", "origin_file": ["transformers/utils/generic.py", "transformers/utils/generic.py", "transformers/image_processing_utils.py", "transformers/image_transforms.py", "transformers/models/blip/image_processing_blip.py"], "test_list": ["tests/models/blip/test_image_processing_blip.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 856, "func_start_lineno": 80, "func_end_lineno": 95, "func_code": "def infer_framework_from_repr(x):\n \"\"\"\n Tries to guess the framework of an object `x` from its repr (brittle but will help in `is_tensor` to try the\n frameworks in a smart order, without the need to import the frameworks).\n \"\"\"\n representation = str(type(x))\n if representation.startswith(\" dict:\n \"\"\"\n Converts the old size parameter in the config into the new dict expected in the config. This is to ensure backwards\n compatibility with the old image processor configs and removes ambiguity over whether the tuple is in (height,\n width) or (width, height) format.\n\n - If `size` is tuple, it is converted to `{\"height\": size[0], \"width\": size[1]}` or `{\"height\": size[1], \"width\":\n size[0]}` if `height_width_order` is `False`.\n - If `size` is an int, and `default_to_square` is `True`, it is converted to `{\"height\": size, \"width\": size}`.\n - If `size` is an int and `default_to_square` is False, it is converted to `{\"shortest_edge\": size}`. If `max_size`\n is set, it is added to the dict as `{\"longest_edge\": max_size}`.\n\n Args:\n size (`Union[int, Iterable[int], Dict[str, int]]`, *optional*):\n The `size` parameter to be cast into a size dictionary.\n max_size (`Optional[int]`, *optional*):\n The `max_size` parameter to be cast into a size dictionary.\n height_width_order (`bool`, *optional*, defaults to `True`):\n If `size` is a tuple, whether it's in (height, width) or (width, height) order.\n default_to_square (`bool`, *optional*, defaults to `True`):\n If `size` is an int, whether to default to a square image or not.\n \"\"\"\n if not isinstance(size, dict):\n size_dict = convert_to_size_dict(size, max_size, default_to_square, height_width_order)\n logger.info(\n f\"{param_name} should be a dictionary on of the following set of keys: {VALID_SIZE_DICT_KEYS}, got {size}.\"\n f\" Converted to {size_dict}.\",\n )\n else:\n size_dict = size\n\n if not is_valid_size_dict(size_dict):\n raise ValueError(\n f\"{param_name} must have one of the following set of keys: {VALID_SIZE_DICT_KEYS}, got {size_dict.keys()}\"\n )\n return size_dict"}, {"class_start_lineno": 1, "class_end_lineno": 854, "func_start_lineno": 281, "func_end_lineno": 349, "func_code": "def resize(\n image: np.ndarray,\n size: Tuple[int, int],\n resample: \"PILImageResampling\" = None,\n reducing_gap: Optional[int] = None,\n data_format: Optional[ChannelDimension] = None,\n return_numpy: bool = True,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n) -> np.ndarray:\n \"\"\"\n Resizes `image` to `(height, width)` specified by `size` using the PIL library.\n\n Args:\n image (`np.ndarray`):\n The image to resize.\n size (`Tuple[int, int]`):\n The size to use for resizing the image.\n resample (`int`, *optional*, defaults to `PILImageResampling.BILINEAR`):\n The filter to user for resampling.\n reducing_gap (`int`, *optional*):\n Apply optimization by resizing the image in two steps. The bigger `reducing_gap`, the closer the result to\n the fair resampling. See corresponding Pillow documentation for more details.\n data_format (`ChannelDimension`, *optional*):\n The channel dimension format of the output image. If unset, will use the inferred format from the input.\n return_numpy (`bool`, *optional*, defaults to `True`):\n Whether or not to return the resized image as a numpy array. If False a `PIL.Image.Image` object is\n returned.\n input_data_format (`ChannelDimension`, *optional*):\n The channel dimension format of the input image. If unset, will use the inferred format from the input.\n\n Returns:\n `np.ndarray`: The resized image.\n \"\"\"\n requires_backends(resize, [\"vision\"])\n\n resample = resample if resample is not None else PILImageResampling.BILINEAR\n\n if not len(size) == 2:\n raise ValueError(\"size must have 2 elements\")\n\n # For all transformations, we want to keep the same data format as the input image unless otherwise specified.\n # The resized image from PIL will always have channels last, so find the input format first.\n if input_data_format is None:\n input_data_format = infer_channel_dimension_format(image)\n data_format = input_data_format if data_format is None else data_format\n\n # To maintain backwards compatibility with the resizing done in previous image feature extractors, we use\n # the pillow library to resize the image and then convert back to numpy\n do_rescale = False\n if not isinstance(image, PIL.Image.Image):\n do_rescale = _rescale_for_pil_conversion(image)\n image = to_pil_image(image, do_rescale=do_rescale, input_data_format=input_data_format)\n height, width = size\n # PIL images are in the format (width, height)\n resized_image = image.resize((width, height), resample=resample, reducing_gap=reducing_gap)\n\n if return_numpy:\n resized_image = np.array(resized_image)\n # If the input image channel dimension was of size 1, then it is dropped when converting to a PIL image\n # so we need to add it back if necessary.\n resized_image = np.expand_dims(resized_image, axis=-1) if resized_image.ndim == 2 else resized_image\n # The image is always in channels last format after converting from a PIL image\n resized_image = to_channel_dimension_format(\n resized_image, data_format, input_channel_dim=ChannelDimension.LAST\n )\n # If an image was rescaled to be in the range [0, 255] before converting to a PIL image, then we need to\n # rescale it back to the original range.\n resized_image = rescale(resized_image, 1 / 255) if do_rescale else resized_image\n return resized_image"}, {"class_start_lineno": 46, "class_end_lineno": 294, "func_start_lineno": 111, "func_end_lineno": 157, "func_code": " def resize(\n self,\n image: np.ndarray,\n size: Dict[str, int],\n resample: PILImageResampling = PILImageResampling.BICUBIC,\n data_format: Optional[Union[str, ChannelDimension]] = None,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n **kwargs,\n ) -> np.ndarray:\n \"\"\"\n Resize an image to `(size[\"height\"], size[\"width\"])`.\n\n Args:\n image (`np.ndarray`):\n Image to resize.\n size (`Dict[str, int]`):\n Dictionary in the format `{\"height\": int, \"width\": int}` specifying the size of the output image.\n resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):\n `PILImageResampling` filter to use when resizing the image e.g. `PILImageResampling.BICUBIC`.\n data_format (`ChannelDimension` or `str`, *optional*):\n The channel dimension format for the output image. If unset, the channel dimension format of the input\n image is used. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n - `\"none\"` or `ChannelDimension.NONE`: image in (height, width) format.\n input_data_format (`ChannelDimension` or `str`, *optional*):\n The channel dimension format for the input image. If unset, the channel dimension format is inferred\n from the input image. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n - `\"none\"` or `ChannelDimension.NONE`: image in (height, width) format.\n\n Returns:\n `np.ndarray`: The resized image.\n \"\"\"\n size = get_size_dict(size)\n if \"height\" not in size or \"width\" not in size:\n raise ValueError(f\"The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}\")\n output_size = (size[\"height\"], size[\"width\"])\n return resize(\n image,\n size=output_size,\n resample=resample,\n data_format=data_format,\n input_data_format=input_data_format,\n **kwargs,\n )"}], "type": ["function_empty", "TDD"], "node": ["transformers.utils.generic.infer_framework_from_repr", "transformers.utils.generic._get_frameworks_and_test_func", "transformers.image_processing_utils.get_size_dict", "transformers.image_transforms.resize", "transformers.models.blip.image_processing_blip.BlipImageProcessor.resize"], "language": "Python", "toolfunc_count": 3, "func_count": 5, "pytest_info": {"total_num": 20, "base_passed_num": 12}} {"id": ["transformers.src.transformers.utils.generic.infer_framework_from_repr", "transformers.src.transformers.utils.generic._get_frameworks_and_test_func", "transformers.src.transformers.image_processing_utils.get_size_dict", "transformers.src.transformers.image_transforms.get_resize_output_image_size", "transformers.src.transformers.models.chinese_clip.image_processing_chinese_clip.ChineseCLIPImageProcessor::resize"], "project": "transformers", "origin_file": ["transformers/utils/generic.py", "transformers/utils/generic.py", "transformers/image_processing_utils.py", "transformers/image_transforms.py", "transformers/models/chinese_clip/image_processing_chinese_clip.py"], "test_list": ["tests/models/chinese_clip/test_image_processing_chinese_clip.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 856, "func_start_lineno": 80, "func_end_lineno": 95, "func_code": "def infer_framework_from_repr(x):\n \"\"\"\n Tries to guess the framework of an object `x` from its repr (brittle but will help in `is_tensor` to try the\n frameworks in a smart order, without the need to import the frameworks).\n \"\"\"\n representation = str(type(x))\n if representation.startswith(\" dict:\n \"\"\"\n Converts the old size parameter in the config into the new dict expected in the config. This is to ensure backwards\n compatibility with the old image processor configs and removes ambiguity over whether the tuple is in (height,\n width) or (width, height) format.\n\n - If `size` is tuple, it is converted to `{\"height\": size[0], \"width\": size[1]}` or `{\"height\": size[1], \"width\":\n size[0]}` if `height_width_order` is `False`.\n - If `size` is an int, and `default_to_square` is `True`, it is converted to `{\"height\": size, \"width\": size}`.\n - If `size` is an int and `default_to_square` is False, it is converted to `{\"shortest_edge\": size}`. If `max_size`\n is set, it is added to the dict as `{\"longest_edge\": max_size}`.\n\n Args:\n size (`Union[int, Iterable[int], Dict[str, int]]`, *optional*):\n The `size` parameter to be cast into a size dictionary.\n max_size (`Optional[int]`, *optional*):\n The `max_size` parameter to be cast into a size dictionary.\n height_width_order (`bool`, *optional*, defaults to `True`):\n If `size` is a tuple, whether it's in (height, width) or (width, height) order.\n default_to_square (`bool`, *optional*, defaults to `True`):\n If `size` is an int, whether to default to a square image or not.\n \"\"\"\n if not isinstance(size, dict):\n size_dict = convert_to_size_dict(size, max_size, default_to_square, height_width_order)\n logger.info(\n f\"{param_name} should be a dictionary on of the following set of keys: {VALID_SIZE_DICT_KEYS}, got {size}.\"\n f\" Converted to {size_dict}.\",\n )\n else:\n size_dict = size\n\n if not is_valid_size_dict(size_dict):\n raise ValueError(\n f\"{param_name} must have one of the following set of keys: {VALID_SIZE_DICT_KEYS}, got {size_dict.keys()}\"\n )\n return size_dict"}, {"class_start_lineno": 1, "class_end_lineno": 854, "func_start_lineno": 214, "func_end_lineno": 278, "func_code": "def get_resize_output_image_size(\n input_image: np.ndarray,\n size: Union[int, Tuple[int, int], List[int], Tuple[int]],\n default_to_square: bool = True,\n max_size: Optional[int] = None,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n) -> tuple:\n \"\"\"\n Find the target (height, width) dimension of the output image after resizing given the input image and the desired\n size.\n\n Args:\n input_image (`np.ndarray`):\n The image to resize.\n size (`int` or `Tuple[int, int]` or List[int] or `Tuple[int]`):\n The size to use for resizing the image. If `size` is a sequence like (h, w), output size will be matched to\n this.\n\n If `size` is an int and `default_to_square` is `True`, then image will be resized to (size, size). If\n `size` is an int and `default_to_square` is `False`, then smaller edge of the image will be matched to this\n number. i.e, if height > width, then image will be rescaled to (size * height / width, size).\n default_to_square (`bool`, *optional*, defaults to `True`):\n How to convert `size` when it is a single int. If set to `True`, the `size` will be converted to a square\n (`size`,`size`). If set to `False`, will replicate\n [`torchvision.transforms.Resize`](https://pytorch.org/vision/stable/transforms.html#torchvision.transforms.Resize)\n with support for resizing only the smallest edge and providing an optional `max_size`.\n max_size (`int`, *optional*):\n The maximum allowed for the longer edge of the resized image: if the longer edge of the image is greater\n than `max_size` after being resized according to `size`, then the image is resized again so that the longer\n edge is equal to `max_size`. As a result, `size` might be overruled, i.e the smaller edge may be shorter\n than `size`. Only used if `default_to_square` is `False`.\n input_data_format (`ChannelDimension`, *optional*):\n The channel dimension format of the input image. If unset, will use the inferred format from the input.\n\n Returns:\n `tuple`: The target (height, width) dimension of the output image after resizing.\n \"\"\"\n if isinstance(size, (tuple, list)):\n if len(size) == 2:\n return tuple(size)\n elif len(size) == 1:\n # Perform same logic as if size was an int\n size = size[0]\n else:\n raise ValueError(\"size must have 1 or 2 elements if it is a list or tuple\")\n\n if default_to_square:\n return (size, size)\n\n height, width = get_image_size(input_image, input_data_format)\n short, long = (width, height) if width <= height else (height, width)\n requested_new_short = size\n\n new_short, new_long = requested_new_short, int(requested_new_short * long / short)\n\n if max_size is not None:\n if max_size <= requested_new_short:\n raise ValueError(\n f\"max_size = {max_size} must be strictly greater than the requested \"\n f\"size for the smaller edge size = {size}\"\n )\n if new_long > max_size:\n new_short, new_long = int(max_size * new_short / new_long), max_size\n\n return (new_long, new_short) if width <= height else (new_short, new_long)"}, {"class_start_lineno": 51, "class_end_lineno": 306, "func_start_lineno": 125, "func_end_lineno": 162, "func_code": " def resize(\n self,\n image: np.ndarray,\n size: Dict[str, int],\n resample: PILImageResampling = PILImageResampling.BICUBIC,\n data_format: Optional[Union[str, ChannelDimension]] = None,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n **kwargs,\n ) -> np.ndarray:\n \"\"\"\n Resize an image. The shortest edge of the image is resized to size[\"shortest_edge\"], with the longest edge\n resized to keep the input aspect ratio.\n\n Args:\n image (`np.ndarray`):\n Image to resize.\n size (`Dict[str, int]`):\n Size of the output image.\n resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):\n Resampling filter to use when resiizing the image.\n data_format (`str` or `ChannelDimension`, *optional*):\n The channel dimension format of the image. If not provided, it will be the same as the input image.\n input_data_format (`ChannelDimension` or `str`, *optional*):\n The channel dimension format of the input image. If not provided, it will be inferred from the input\n image.\n \"\"\"\n size = get_size_dict(size, default_to_square=False)\n output_size = get_resize_output_image_size(\n image, size=(size[\"height\"], size[\"width\"]), default_to_square=False, input_data_format=input_data_format\n )\n return resize(\n image,\n size=output_size,\n resample=resample,\n data_format=data_format,\n input_data_format=input_data_format,\n **kwargs,\n )"}], "type": ["function_empty", "TDD"], "node": ["transformers.utils.generic.infer_framework_from_repr", "transformers.utils.generic._get_frameworks_and_test_func", "transformers.image_processing_utils.get_size_dict", "transformers.image_transforms.get_resize_output_image_size", "transformers.models.chinese_clip.image_processing_chinese_clip.ChineseCLIPImageProcessor.resize"], "language": "Python", "toolfunc_count": 3, "func_count": 5, "pytest_info": {"total_num": 21, "base_passed_num": 12}} {"id": ["transformers.src.transformers.utils.logging._configure_library_root_logger", "transformers.src.transformers.utils.logging.get_logger"], "project": "transformers", "origin_file": ["transformers/utils/logging.py", "transformers/utils/logging.py"], "test_list": ["tests/models/esm/test_tokenization_esm.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 410, "func_start_lineno": 81, "func_end_lineno": 104, "func_code": "def _configure_library_root_logger() -> None:\n global _default_handler\n\n with _lock:\n if _default_handler:\n # This library has already configured the library root logger.\n return\n _default_handler = logging.StreamHandler() # Set sys.stderr as stream.\n # set defaults based on https://github.com/pyinstaller/pyinstaller/issues/7334#issuecomment-1357447176\n if sys.stderr is None:\n sys.stderr = open(os.devnull, \"w\")\n\n _default_handler.flush = sys.stderr.flush\n\n # Apply our default configuration to the library root logger.\n library_root_logger = _get_library_root_logger()\n library_root_logger.addHandler(_default_handler)\n library_root_logger.setLevel(_get_default_logging_level())\n # if logging level is debug, we add pathname and lineno to formatter for easy debugging\n if os.getenv(\"TRANSFORMERS_VERBOSITY\", None) == \"detail\":\n formatter = logging.Formatter(\"[%(levelname)s|%(pathname)s:%(lineno)s] %(asctime)s >> %(message)s\")\n _default_handler.setFormatter(formatter)\n\n library_root_logger.propagate = False"}, {"class_start_lineno": 1, "class_end_lineno": 410, "func_start_lineno": 147, "func_end_lineno": 158, "func_code": "def get_logger(name: Optional[str] = None) -> logging.Logger:\n \"\"\"\n Return a logger with the specified name.\n\n This function is not supposed to be directly accessed unless you are writing a custom transformers module.\n \"\"\"\n\n if name is None:\n name = _get_library_name()\n\n _configure_library_root_logger()\n return logging.getLogger(name)"}], "type": ["function_empty", "TDD"], "node": ["transformers.utils.logging._configure_library_root_logger", "transformers.utils.logging.get_logger"], "language": "Python", "toolfunc_count": 1, "func_count": 2, "pytest_info": {"total_num": 6, "base_passed_num": 0}} {"id": ["transformers.src.transformers.utils.generic.infer_framework_from_repr", "transformers.src.transformers.utils.generic._get_frameworks_and_test_func", "transformers.src.transformers.image_processing_utils.get_size_dict", "transformers.src.transformers.image_transforms.resize", "transformers.src.transformers.models.flava.image_processing_flava.FlavaImageProcessor::resize"], "project": "transformers", "origin_file": ["transformers/utils/generic.py", "transformers/utils/generic.py", "transformers/image_processing_utils.py", "transformers/image_transforms.py", "transformers/models/flava/image_processing_flava.py"], "test_list": ["tests/models/flava/test_image_processing_flava.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 856, "func_start_lineno": 80, "func_end_lineno": 95, "func_code": "def infer_framework_from_repr(x):\n \"\"\"\n Tries to guess the framework of an object `x` from its repr (brittle but will help in `is_tensor` to try the\n frameworks in a smart order, without the need to import the frameworks).\n \"\"\"\n representation = str(type(x))\n if representation.startswith(\" dict:\n \"\"\"\n Converts the old size parameter in the config into the new dict expected in the config. This is to ensure backwards\n compatibility with the old image processor configs and removes ambiguity over whether the tuple is in (height,\n width) or (width, height) format.\n\n - If `size` is tuple, it is converted to `{\"height\": size[0], \"width\": size[1]}` or `{\"height\": size[1], \"width\":\n size[0]}` if `height_width_order` is `False`.\n - If `size` is an int, and `default_to_square` is `True`, it is converted to `{\"height\": size, \"width\": size}`.\n - If `size` is an int and `default_to_square` is False, it is converted to `{\"shortest_edge\": size}`. If `max_size`\n is set, it is added to the dict as `{\"longest_edge\": max_size}`.\n\n Args:\n size (`Union[int, Iterable[int], Dict[str, int]]`, *optional*):\n The `size` parameter to be cast into a size dictionary.\n max_size (`Optional[int]`, *optional*):\n The `max_size` parameter to be cast into a size dictionary.\n height_width_order (`bool`, *optional*, defaults to `True`):\n If `size` is a tuple, whether it's in (height, width) or (width, height) order.\n default_to_square (`bool`, *optional*, defaults to `True`):\n If `size` is an int, whether to default to a square image or not.\n \"\"\"\n if not isinstance(size, dict):\n size_dict = convert_to_size_dict(size, max_size, default_to_square, height_width_order)\n logger.info(\n f\"{param_name} should be a dictionary on of the following set of keys: {VALID_SIZE_DICT_KEYS}, got {size}.\"\n f\" Converted to {size_dict}.\",\n )\n else:\n size_dict = size\n\n if not is_valid_size_dict(size_dict):\n raise ValueError(\n f\"{param_name} must have one of the following set of keys: {VALID_SIZE_DICT_KEYS}, got {size_dict.keys()}\"\n )\n return size_dict"}, {"class_start_lineno": 1, "class_end_lineno": 854, "func_start_lineno": 281, "func_end_lineno": 349, "func_code": "def resize(\n image: np.ndarray,\n size: Tuple[int, int],\n resample: \"PILImageResampling\" = None,\n reducing_gap: Optional[int] = None,\n data_format: Optional[ChannelDimension] = None,\n return_numpy: bool = True,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n) -> np.ndarray:\n \"\"\"\n Resizes `image` to `(height, width)` specified by `size` using the PIL library.\n\n Args:\n image (`np.ndarray`):\n The image to resize.\n size (`Tuple[int, int]`):\n The size to use for resizing the image.\n resample (`int`, *optional*, defaults to `PILImageResampling.BILINEAR`):\n The filter to user for resampling.\n reducing_gap (`int`, *optional*):\n Apply optimization by resizing the image in two steps. The bigger `reducing_gap`, the closer the result to\n the fair resampling. See corresponding Pillow documentation for more details.\n data_format (`ChannelDimension`, *optional*):\n The channel dimension format of the output image. If unset, will use the inferred format from the input.\n return_numpy (`bool`, *optional*, defaults to `True`):\n Whether or not to return the resized image as a numpy array. If False a `PIL.Image.Image` object is\n returned.\n input_data_format (`ChannelDimension`, *optional*):\n The channel dimension format of the input image. If unset, will use the inferred format from the input.\n\n Returns:\n `np.ndarray`: The resized image.\n \"\"\"\n requires_backends(resize, [\"vision\"])\n\n resample = resample if resample is not None else PILImageResampling.BILINEAR\n\n if not len(size) == 2:\n raise ValueError(\"size must have 2 elements\")\n\n # For all transformations, we want to keep the same data format as the input image unless otherwise specified.\n # The resized image from PIL will always have channels last, so find the input format first.\n if input_data_format is None:\n input_data_format = infer_channel_dimension_format(image)\n data_format = input_data_format if data_format is None else data_format\n\n # To maintain backwards compatibility with the resizing done in previous image feature extractors, we use\n # the pillow library to resize the image and then convert back to numpy\n do_rescale = False\n if not isinstance(image, PIL.Image.Image):\n do_rescale = _rescale_for_pil_conversion(image)\n image = to_pil_image(image, do_rescale=do_rescale, input_data_format=input_data_format)\n height, width = size\n # PIL images are in the format (width, height)\n resized_image = image.resize((width, height), resample=resample, reducing_gap=reducing_gap)\n\n if return_numpy:\n resized_image = np.array(resized_image)\n # If the input image channel dimension was of size 1, then it is dropped when converting to a PIL image\n # so we need to add it back if necessary.\n resized_image = np.expand_dims(resized_image, axis=-1) if resized_image.ndim == 2 else resized_image\n # The image is always in channels last format after converting from a PIL image\n resized_image = to_channel_dimension_format(\n resized_image, data_format, input_channel_dim=ChannelDimension.LAST\n )\n # If an image was rescaled to be in the range [0, 255] before converting to a PIL image, then we need to\n # rescale it back to the original range.\n resized_image = rescale(resized_image, 1 / 255) if do_rescale else resized_image\n return resized_image"}, {"class_start_lineno": 136, "class_end_lineno": 700, "func_start_lineno": 338, "func_end_lineno": 384, "func_code": " def resize(\n self,\n image: np.ndarray,\n size: Dict[str, int],\n resample: PILImageResampling = PILImageResampling.BICUBIC,\n data_format: Optional[Union[str, ChannelDimension]] = None,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n **kwargs,\n ) -> np.ndarray:\n \"\"\"\n Resize an image to `(size[\"height\"], size[\"width\"])`.\n\n Args:\n image (`np.ndarray`):\n Image to resize.\n size (`Dict[str, int]`):\n Dictionary in the format `{\"height\": int, \"width\": int}` specifying the size of the output image.\n resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):\n `PILImageResampling` filter to use when resizing the image e.g. `PILImageResampling.BICUBIC`.\n data_format (`ChannelDimension` or `str`, *optional*):\n The channel dimension format for the output image. If unset, the channel dimension format of the input\n image is used. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n - `\"none\"` or `ChannelDimension.NONE`: image in (height, width) format.\n input_data_format (`ChannelDimension` or `str`, *optional*):\n The channel dimension format for the input image. If unset, the channel dimension format is inferred\n from the input image. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n - `\"none\"` or `ChannelDimension.NONE`: image in (height, width) format.\n\n Returns:\n `np.ndarray`: The resized image.\n \"\"\"\n size = get_size_dict(size)\n if \"height\" not in size or \"width\" not in size:\n raise ValueError(f\"The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}\")\n output_size = (size[\"height\"], size[\"width\"])\n return resize(\n image,\n size=output_size,\n resample=resample,\n data_format=data_format,\n input_data_format=input_data_format,\n **kwargs,\n )"}], "type": ["function_empty", "TDD"], "node": ["transformers.utils.generic.infer_framework_from_repr", "transformers.utils.generic._get_frameworks_and_test_func", "transformers.image_processing_utils.get_size_dict", "transformers.image_transforms.resize", "transformers.models.flava.image_processing_flava.FlavaImageProcessor.resize"], "language": "Python", "toolfunc_count": 3, "func_count": 5, "pytest_info": {"total_num": 15, "base_passed_num": 6}} {"id": ["transformers.src.transformers.utils.generic.infer_framework_from_repr", "transformers.src.transformers.utils.generic._get_frameworks_and_test_func", "transformers.src.transformers.image_utils.infer_channel_dimension_format", "transformers.src.transformers.image_utils.get_image_size"], "project": "transformers", "origin_file": ["transformers/utils/generic.py", "transformers/utils/generic.py", "transformers/image_utils.py", "transformers/image_utils.py"], "test_list": ["tests/models/fuyu/test_image_processing_fuyu.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 856, "func_start_lineno": 80, "func_end_lineno": 95, "func_code": "def infer_framework_from_repr(x):\n \"\"\"\n Tries to guess the framework of an object `x` from its repr (brittle but will help in `is_tensor` to try the\n frameworks in a smart order, without the need to import the frameworks).\n \"\"\"\n representation = str(type(x))\n if representation.startswith(\" ChannelDimension:\n \"\"\"\n Infers the channel dimension format of `image`.\n\n Args:\n image (`np.ndarray`):\n The image to infer the channel dimension of.\n num_channels (`int` or `Tuple[int, ...]`, *optional*, defaults to `(1, 3)`):\n The number of channels of the image.\n\n Returns:\n The channel dimension of the image.\n \"\"\"\n num_channels = num_channels if num_channels is not None else (1, 3)\n num_channels = (num_channels,) if isinstance(num_channels, int) else num_channels\n\n if image.ndim == 3:\n first_dim, last_dim = 0, 2\n elif image.ndim == 4:\n first_dim, last_dim = 1, 3\n else:\n raise ValueError(f\"Unsupported number of image dimensions: {image.ndim}\")\n\n if image.shape[first_dim] in num_channels and image.shape[last_dim] in num_channels:\n logger.warning(\n f\"The channel dimension is ambiguous. Got image shape {image.shape}. Assuming channels are the first dimension.\"\n )\n return ChannelDimension.FIRST\n elif image.shape[first_dim] in num_channels:\n return ChannelDimension.FIRST\n elif image.shape[last_dim] in num_channels:\n return ChannelDimension.LAST\n raise ValueError(\"Unable to infer channel dimension format\")"}, {"class_start_lineno": 1, "class_end_lineno": 811, "func_start_lineno": 281, "func_end_lineno": 302, "func_code": "def get_image_size(image: np.ndarray, channel_dim: ChannelDimension = None) -> Tuple[int, int]:\n \"\"\"\n Returns the (height, width) dimensions of the image.\n\n Args:\n image (`np.ndarray`):\n The image to get the dimensions of.\n channel_dim (`ChannelDimension`, *optional*):\n Which dimension the channel dimension is in. If `None`, will infer the channel dimension from the image.\n\n Returns:\n A tuple of the image's height and width.\n \"\"\"\n if channel_dim is None:\n channel_dim = infer_channel_dimension_format(image)\n\n if channel_dim == ChannelDimension.FIRST:\n return image.shape[-2], image.shape[-1]\n elif channel_dim == ChannelDimension.LAST:\n return image.shape[-3], image.shape[-2]\n else:\n raise ValueError(f\"Unsupported data format: {channel_dim}\")"}], "type": ["function_empty", "TDD"], "node": ["transformers.utils.generic.infer_framework_from_repr", "transformers.utils.generic._get_frameworks_and_test_func", "transformers.image_utils.infer_channel_dimension_format", "transformers.image_utils.get_image_size"], "language": "Python", "toolfunc_count": 2, "func_count": 4, "pytest_info": {"total_num": 4, "base_passed_num": 1}} {"id": ["transformers.src.transformers.utils.backbone_utils.verify_out_features_out_indices", "transformers.src.transformers.utils.backbone_utils._align_output_features_output_indices", "transformers.src.transformers.utils.backbone_utils.get_aligned_output_features_output_indices", "transformers.src.transformers.utils.generic.infer_framework_from_repr", "transformers.src.transformers.utils.generic._get_frameworks_and_test_func", "transformers.src.transformers.utils.generic.is_tensor"], "project": "transformers", "origin_file": ["transformers/utils/backbone_utils.py", "transformers/utils/backbone_utils.py", "transformers/utils/backbone_utils.py", "transformers/models/rt_detr/configuration_rt_detr_resnet.py", "transformers/utils/generic.py", "transformers/utils/generic.py", "transformers/utils/generic.py"], "test_list": ["tests/models/rt_detr/test_modeling_rt_detr_resnet.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 377, "func_start_lineno": 32, "func_end_lineno": 74, "func_code": "def verify_out_features_out_indices(\n out_features: Optional[Iterable[str]], out_indices: Optional[Iterable[int]], stage_names: Optional[Iterable[str]]\n):\n \"\"\"\n Verify that out_indices and out_features are valid for the given stage_names.\n \"\"\"\n if stage_names is None:\n raise ValueError(\"Stage_names must be set for transformers backbones\")\n\n if out_features is not None:\n if not isinstance(out_features, (list,)):\n raise ValueError(f\"out_features must be a list got {type(out_features)}\")\n if any(feat not in stage_names for feat in out_features):\n raise ValueError(f\"out_features must be a subset of stage_names: {stage_names} got {out_features}\")\n if len(out_features) != len(set(out_features)):\n raise ValueError(f\"out_features must not contain any duplicates, got {out_features}\")\n if out_features != (sorted_feats := [feat for feat in stage_names if feat in out_features]):\n raise ValueError(\n f\"out_features must be in the same order as stage_names, expected {sorted_feats} got {out_features}\"\n )\n\n if out_indices is not None:\n if not isinstance(out_indices, list):\n raise ValueError(f\"out_indices must be a list, got {type(out_indices)}\")\n # Convert negative indices to their positive equivalent: [-1,] -> [len(stage_names) - 1,]\n positive_indices = tuple(idx % len(stage_names) if idx < 0 else idx for idx in out_indices)\n if any(idx for idx in positive_indices if idx not in range(len(stage_names))):\n raise ValueError(f\"out_indices must be valid indices for stage_names {stage_names}, got {out_indices}\")\n if len(positive_indices) != len(set(positive_indices)):\n msg = f\"out_indices must not contain any duplicates, got {out_indices}\"\n msg += f\"(equivalent to {positive_indices}))\" if positive_indices != out_indices else \"\"\n raise ValueError(msg)\n if positive_indices != tuple(sorted(positive_indices)):\n sorted_negative = [idx for _, idx in sorted(zip(positive_indices, out_indices), key=lambda x: x[0])]\n raise ValueError(\n f\"out_indices must be in the same order as stage_names, expected {sorted_negative} got {out_indices}\"\n )\n\n if out_features is not None and out_indices is not None:\n if len(out_features) != len(out_indices):\n raise ValueError(\"out_features and out_indices should have the same length if both are set\")\n if out_features != [stage_names[idx] for idx in out_indices]:\n raise ValueError(\"out_features and out_indices should correspond to the same stages if both are set\")"}, {"class_start_lineno": 1, "class_end_lineno": 377, "func_start_lineno": 77, "func_end_lineno": 105, "func_code": "def _align_output_features_output_indices(\n out_features: Optional[List[str]],\n out_indices: Optional[Union[List[int], Tuple[int]]],\n stage_names: List[str],\n):\n \"\"\"\n Finds the corresponding `out_features` and `out_indices` for the given `stage_names`.\n\n The logic is as follows:\n - `out_features` not set, `out_indices` set: `out_features` is set to the `out_features` corresponding to the\n `out_indices`.\n - `out_indices` not set, `out_features` set: `out_indices` is set to the `out_indices` corresponding to the\n `out_features`.\n - `out_indices` and `out_features` not set: `out_indices` and `out_features` are set to the last stage.\n - `out_indices` and `out_features` set: input `out_indices` and `out_features` are returned.\n\n Args:\n out_features (`List[str]`): The names of the features for the backbone to output.\n out_indices (`List[int]` or `Tuple[int]`): The indices of the features for the backbone to output.\n stage_names (`List[str]`): The names of the stages of the backbone.\n \"\"\"\n if out_indices is None and out_features is None:\n out_indices = [len(stage_names) - 1]\n out_features = [stage_names[-1]]\n elif out_indices is None and out_features is not None:\n out_indices = [stage_names.index(layer) for layer in out_features]\n elif out_features is None and out_indices is not None:\n out_features = [stage_names[idx] for idx in out_indices]\n return out_features, out_indices"}, {"class_start_lineno": 1, "class_end_lineno": 377, "func_start_lineno": 108, "func_end_lineno": 137, "func_code": "def get_aligned_output_features_output_indices(\n out_features: Optional[List[str]],\n out_indices: Optional[Union[List[int], Tuple[int]]],\n stage_names: List[str],\n) -> Tuple[List[str], List[int]]:\n \"\"\"\n Get the `out_features` and `out_indices` so that they are aligned.\n\n The logic is as follows:\n - `out_features` not set, `out_indices` set: `out_features` is set to the `out_features` corresponding to the\n `out_indices`.\n - `out_indices` not set, `out_features` set: `out_indices` is set to the `out_indices` corresponding to the\n `out_features`.\n - `out_indices` and `out_features` not set: `out_indices` and `out_features` are set to the last stage.\n - `out_indices` and `out_features` set: they are verified to be aligned.\n\n Args:\n out_features (`List[str]`): The names of the features for the backbone to output.\n out_indices (`List[int]` or `Tuple[int]`): The indices of the features for the backbone to output.\n stage_names (`List[str]`): The names of the stages of the backbone.\n \"\"\"\n out_indices = list(out_indices) if out_indices is not None else None\n # First verify that the out_features and out_indices are valid\n verify_out_features_out_indices(out_features=out_features, out_indices=out_indices, stage_names=stage_names)\n output_features, output_indices = _align_output_features_output_indices(\n out_features=out_features, out_indices=out_indices, stage_names=stage_names\n )\n # Verify that the aligned out_features and out_indices are valid\n verify_out_features_out_indices(out_features=output_features, out_indices=output_indices, stage_names=stage_names)\n return output_features, output_indices"}, {"class_start_lineno": 25, "class_end_lineno": 111, "func_start_lineno": 83, "func_end_lineno": 111, "func_code": " def __init__(\n self,\n num_channels=3,\n embedding_size=64,\n hidden_sizes=[256, 512, 1024, 2048],\n depths=[3, 4, 6, 3],\n layer_type=\"bottleneck\",\n hidden_act=\"relu\",\n downsample_in_first_stage=False,\n downsample_in_bottleneck=False,\n out_features=None,\n out_indices=None,\n **kwargs,\n ):\n super().__init__(**kwargs)\n if layer_type not in self.layer_types:\n raise ValueError(f\"layer_type={layer_type} is not one of {','.join(self.layer_types)}\")\n self.num_channels = num_channels\n self.embedding_size = embedding_size\n self.hidden_sizes = hidden_sizes\n self.depths = depths\n self.layer_type = layer_type\n self.hidden_act = hidden_act\n self.downsample_in_first_stage = downsample_in_first_stage\n self.downsample_in_bottleneck = downsample_in_bottleneck\n self.stage_names = [\"stem\"] + [f\"stage{idx}\" for idx in range(1, len(depths) + 1)]\n self._out_features, self._out_indices = get_aligned_output_features_output_indices(\n out_features=out_features, out_indices=out_indices, stage_names=self.stage_names\n )"}, {"class_start_lineno": 1, "class_end_lineno": 856, "func_start_lineno": 80, "func_end_lineno": 95, "func_code": "def infer_framework_from_repr(x):\n \"\"\"\n Tries to guess the framework of an object `x` from its repr (brittle but will help in `is_tensor` to try the\n frameworks in a smart order, without the need to import the frameworks).\n \"\"\"\n representation = str(type(x))\n if representation.startswith(\" Tuple[int, int]:\n \"\"\"\n Returns the (height, width) dimensions of the image.\n\n Args:\n image (`np.ndarray`):\n The image to get the dimensions of.\n channel_dim (`ChannelDimension`, *optional*):\n Which dimension the channel dimension is in. If `None`, will infer the channel dimension from the image.\n\n Returns:\n A tuple of the image's height and width.\n \"\"\"\n if channel_dim is None:\n channel_dim = infer_channel_dimension_format(image)\n\n if channel_dim == ChannelDimension.FIRST:\n return image.shape[-2], image.shape[-1]\n elif channel_dim == ChannelDimension.LAST:\n return image.shape[-3], image.shape[-2]\n else:\n raise ValueError(f\"Unsupported data format: {channel_dim}\")"}, {"class_start_lineno": 1, "class_end_lineno": 854, "func_start_lineno": 214, "func_end_lineno": 278, "func_code": "def get_resize_output_image_size(\n input_image: np.ndarray,\n size: Union[int, Tuple[int, int], List[int], Tuple[int]],\n default_to_square: bool = True,\n max_size: Optional[int] = None,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n) -> tuple:\n \"\"\"\n Find the target (height, width) dimension of the output image after resizing given the input image and the desired\n size.\n\n Args:\n input_image (`np.ndarray`):\n The image to resize.\n size (`int` or `Tuple[int, int]` or List[int] or `Tuple[int]`):\n The size to use for resizing the image. If `size` is a sequence like (h, w), output size will be matched to\n this.\n\n If `size` is an int and `default_to_square` is `True`, then image will be resized to (size, size). If\n `size` is an int and `default_to_square` is `False`, then smaller edge of the image will be matched to this\n number. i.e, if height > width, then image will be rescaled to (size * height / width, size).\n default_to_square (`bool`, *optional*, defaults to `True`):\n How to convert `size` when it is a single int. If set to `True`, the `size` will be converted to a square\n (`size`,`size`). If set to `False`, will replicate\n [`torchvision.transforms.Resize`](https://pytorch.org/vision/stable/transforms.html#torchvision.transforms.Resize)\n with support for resizing only the smallest edge and providing an optional `max_size`.\n max_size (`int`, *optional*):\n The maximum allowed for the longer edge of the resized image: if the longer edge of the image is greater\n than `max_size` after being resized according to `size`, then the image is resized again so that the longer\n edge is equal to `max_size`. As a result, `size` might be overruled, i.e the smaller edge may be shorter\n than `size`. Only used if `default_to_square` is `False`.\n input_data_format (`ChannelDimension`, *optional*):\n The channel dimension format of the input image. If unset, will use the inferred format from the input.\n\n Returns:\n `tuple`: The target (height, width) dimension of the output image after resizing.\n \"\"\"\n if isinstance(size, (tuple, list)):\n if len(size) == 2:\n return tuple(size)\n elif len(size) == 1:\n # Perform same logic as if size was an int\n size = size[0]\n else:\n raise ValueError(\"size must have 1 or 2 elements if it is a list or tuple\")\n\n if default_to_square:\n return (size, size)\n\n height, width = get_image_size(input_image, input_data_format)\n short, long = (width, height) if width <= height else (height, width)\n requested_new_short = size\n\n new_short, new_long = requested_new_short, int(requested_new_short * long / short)\n\n if max_size is not None:\n if max_size <= requested_new_short:\n raise ValueError(\n f\"max_size = {max_size} must be strictly greater than the requested \"\n f\"size for the smaller edge size = {size}\"\n )\n if new_long > max_size:\n new_short, new_long = int(max_size * new_short / new_long), max_size\n\n return (new_long, new_short) if width <= height else (new_short, new_long)"}, {"class_start_lineno": 1, "class_end_lineno": 854, "func_start_lineno": 281, "func_end_lineno": 349, "func_code": "def resize(\n image: np.ndarray,\n size: Tuple[int, int],\n resample: \"PILImageResampling\" = None,\n reducing_gap: Optional[int] = None,\n data_format: Optional[ChannelDimension] = None,\n return_numpy: bool = True,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n) -> np.ndarray:\n \"\"\"\n Resizes `image` to `(height, width)` specified by `size` using the PIL library.\n\n Args:\n image (`np.ndarray`):\n The image to resize.\n size (`Tuple[int, int]`):\n The size to use for resizing the image.\n resample (`int`, *optional*, defaults to `PILImageResampling.BILINEAR`):\n The filter to user for resampling.\n reducing_gap (`int`, *optional*):\n Apply optimization by resizing the image in two steps. The bigger `reducing_gap`, the closer the result to\n the fair resampling. See corresponding Pillow documentation for more details.\n data_format (`ChannelDimension`, *optional*):\n The channel dimension format of the output image. If unset, will use the inferred format from the input.\n return_numpy (`bool`, *optional*, defaults to `True`):\n Whether or not to return the resized image as a numpy array. If False a `PIL.Image.Image` object is\n returned.\n input_data_format (`ChannelDimension`, *optional*):\n The channel dimension format of the input image. If unset, will use the inferred format from the input.\n\n Returns:\n `np.ndarray`: The resized image.\n \"\"\"\n requires_backends(resize, [\"vision\"])\n\n resample = resample if resample is not None else PILImageResampling.BILINEAR\n\n if not len(size) == 2:\n raise ValueError(\"size must have 2 elements\")\n\n # For all transformations, we want to keep the same data format as the input image unless otherwise specified.\n # The resized image from PIL will always have channels last, so find the input format first.\n if input_data_format is None:\n input_data_format = infer_channel_dimension_format(image)\n data_format = input_data_format if data_format is None else data_format\n\n # To maintain backwards compatibility with the resizing done in previous image feature extractors, we use\n # the pillow library to resize the image and then convert back to numpy\n do_rescale = False\n if not isinstance(image, PIL.Image.Image):\n do_rescale = _rescale_for_pil_conversion(image)\n image = to_pil_image(image, do_rescale=do_rescale, input_data_format=input_data_format)\n height, width = size\n # PIL images are in the format (width, height)\n resized_image = image.resize((width, height), resample=resample, reducing_gap=reducing_gap)\n\n if return_numpy:\n resized_image = np.array(resized_image)\n # If the input image channel dimension was of size 1, then it is dropped when converting to a PIL image\n # so we need to add it back if necessary.\n resized_image = np.expand_dims(resized_image, axis=-1) if resized_image.ndim == 2 else resized_image\n # The image is always in channels last format after converting from a PIL image\n resized_image = to_channel_dimension_format(\n resized_image, data_format, input_channel_dim=ChannelDimension.LAST\n )\n # If an image was rescaled to be in the range [0, 255] before converting to a PIL image, then we need to\n # rescale it back to the original range.\n resized_image = rescale(resized_image, 1 / 255) if do_rescale else resized_image\n return resized_image"}, {"class_start_lineno": 69, "class_end_lineno": 404, "func_start_lineno": 143, "func_end_lineno": 190, "func_code": " def resize(\n self,\n image: np.ndarray,\n size: Dict[str, int],\n resample: PILImageResampling = PILImageResampling.BICUBIC,\n data_format: Optional[Union[str, ChannelDimension]] = None,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n **kwargs,\n ) -> np.ndarray:\n \"\"\"\n Resize an image. The shortest edge of the image is resized to size[\"shortest_edge\"], with the longest edge\n resized to keep the input aspect ratio.\n\n Args:\n image (`np.ndarray`):\n Image to resize.\n size (`Dict[str, int]`):\n Size of the output image.\n resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):\n Resampling filter to use when resiizing the image.\n data_format (`str` or `ChannelDimension`, *optional*):\n The channel dimension format of the image. If not provided, it will be the same as the input image.\n input_data_format (`ChannelDimension` or `str`, *optional*):\n The channel dimension format of the input image. If not provided, it will be inferred.\n \"\"\"\n default_to_square = True\n if \"shortest_edge\" in size:\n size = size[\"shortest_edge\"]\n default_to_square = False\n elif \"height\" in size and \"width\" in size:\n size = (size[\"height\"], size[\"width\"])\n else:\n raise ValueError(\"Size must contain either 'shortest_edge' or 'height' and 'width'.\")\n\n output_size = get_resize_output_image_size(\n image,\n size=size,\n default_to_square=default_to_square,\n input_data_format=input_data_format,\n )\n return resize(\n image,\n size=output_size,\n resample=resample,\n data_format=data_format,\n input_data_format=input_data_format,\n **kwargs,\n )"}], "type": ["function_empty"], "node": ["transformers.image_utils.get_image_size", "transformers.image_transforms.get_resize_output_image_size", "transformers.image_transforms.resize", "transformers.models.video_llava.image_processing_video_llava.VideoLlavaImageProcessor.resize"], "language": "Python", "toolfunc_count": 4, "func_count": 4, "pytest_info": {"total_num": 18, "base_passed_num": 8}} {"id": ["transformers.src.transformers.utils.generic.infer_framework_from_repr", "transformers.src.transformers.utils.generic._get_frameworks_and_test_func", "transformers.src.transformers.image_processing_utils.get_size_dict", "transformers.src.transformers.image_utils.get_image_size", "transformers.src.transformers.image_transforms.get_resize_output_image_size", "transformers.src.transformers.models.videomae.image_processing_videomae.VideoMAEImageProcessor::resize"], "project": "transformers", "origin_file": ["transformers/utils/generic.py", "transformers/utils/generic.py", "transformers/image_processing_utils.py", "transformers/image_utils.py", "transformers/image_transforms.py", "transformers/models/videomae/image_processing_videomae.py"], "test_list": ["tests/models/videomae/test_image_processing_videomae.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 856, "func_start_lineno": 80, "func_end_lineno": 95, "func_code": "def infer_framework_from_repr(x):\n \"\"\"\n Tries to guess the framework of an object `x` from its repr (brittle but will help in `is_tensor` to try the\n frameworks in a smart order, without the need to import the frameworks).\n \"\"\"\n representation = str(type(x))\n if representation.startswith(\" dict:\n \"\"\"\n Converts the old size parameter in the config into the new dict expected in the config. This is to ensure backwards\n compatibility with the old image processor configs and removes ambiguity over whether the tuple is in (height,\n width) or (width, height) format.\n\n - If `size` is tuple, it is converted to `{\"height\": size[0], \"width\": size[1]}` or `{\"height\": size[1], \"width\":\n size[0]}` if `height_width_order` is `False`.\n - If `size` is an int, and `default_to_square` is `True`, it is converted to `{\"height\": size, \"width\": size}`.\n - If `size` is an int and `default_to_square` is False, it is converted to `{\"shortest_edge\": size}`. If `max_size`\n is set, it is added to the dict as `{\"longest_edge\": max_size}`.\n\n Args:\n size (`Union[int, Iterable[int], Dict[str, int]]`, *optional*):\n The `size` parameter to be cast into a size dictionary.\n max_size (`Optional[int]`, *optional*):\n The `max_size` parameter to be cast into a size dictionary.\n height_width_order (`bool`, *optional*, defaults to `True`):\n If `size` is a tuple, whether it's in (height, width) or (width, height) order.\n default_to_square (`bool`, *optional*, defaults to `True`):\n If `size` is an int, whether to default to a square image or not.\n \"\"\"\n if not isinstance(size, dict):\n size_dict = convert_to_size_dict(size, max_size, default_to_square, height_width_order)\n logger.info(\n f\"{param_name} should be a dictionary on of the following set of keys: {VALID_SIZE_DICT_KEYS}, got {size}.\"\n f\" Converted to {size_dict}.\",\n )\n else:\n size_dict = size\n\n if not is_valid_size_dict(size_dict):\n raise ValueError(\n f\"{param_name} must have one of the following set of keys: {VALID_SIZE_DICT_KEYS}, got {size_dict.keys()}\"\n )\n return size_dict"}, {"class_start_lineno": 1, "class_end_lineno": 811, "func_start_lineno": 281, "func_end_lineno": 302, "func_code": "def get_image_size(image: np.ndarray, channel_dim: ChannelDimension = None) -> Tuple[int, int]:\n \"\"\"\n Returns the (height, width) dimensions of the image.\n\n Args:\n image (`np.ndarray`):\n The image to get the dimensions of.\n channel_dim (`ChannelDimension`, *optional*):\n Which dimension the channel dimension is in. If `None`, will infer the channel dimension from the image.\n\n Returns:\n A tuple of the image's height and width.\n \"\"\"\n if channel_dim is None:\n channel_dim = infer_channel_dimension_format(image)\n\n if channel_dim == ChannelDimension.FIRST:\n return image.shape[-2], image.shape[-1]\n elif channel_dim == ChannelDimension.LAST:\n return image.shape[-3], image.shape[-2]\n else:\n raise ValueError(f\"Unsupported data format: {channel_dim}\")"}, {"class_start_lineno": 1, "class_end_lineno": 854, "func_start_lineno": 214, "func_end_lineno": 278, "func_code": "def get_resize_output_image_size(\n input_image: np.ndarray,\n size: Union[int, Tuple[int, int], List[int], Tuple[int]],\n default_to_square: bool = True,\n max_size: Optional[int] = None,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n) -> tuple:\n \"\"\"\n Find the target (height, width) dimension of the output image after resizing given the input image and the desired\n size.\n\n Args:\n input_image (`np.ndarray`):\n The image to resize.\n size (`int` or `Tuple[int, int]` or List[int] or `Tuple[int]`):\n The size to use for resizing the image. If `size` is a sequence like (h, w), output size will be matched to\n this.\n\n If `size` is an int and `default_to_square` is `True`, then image will be resized to (size, size). If\n `size` is an int and `default_to_square` is `False`, then smaller edge of the image will be matched to this\n number. i.e, if height > width, then image will be rescaled to (size * height / width, size).\n default_to_square (`bool`, *optional*, defaults to `True`):\n How to convert `size` when it is a single int. If set to `True`, the `size` will be converted to a square\n (`size`,`size`). If set to `False`, will replicate\n [`torchvision.transforms.Resize`](https://pytorch.org/vision/stable/transforms.html#torchvision.transforms.Resize)\n with support for resizing only the smallest edge and providing an optional `max_size`.\n max_size (`int`, *optional*):\n The maximum allowed for the longer edge of the resized image: if the longer edge of the image is greater\n than `max_size` after being resized according to `size`, then the image is resized again so that the longer\n edge is equal to `max_size`. As a result, `size` might be overruled, i.e the smaller edge may be shorter\n than `size`. Only used if `default_to_square` is `False`.\n input_data_format (`ChannelDimension`, *optional*):\n The channel dimension format of the input image. If unset, will use the inferred format from the input.\n\n Returns:\n `tuple`: The target (height, width) dimension of the output image after resizing.\n \"\"\"\n if isinstance(size, (tuple, list)):\n if len(size) == 2:\n return tuple(size)\n elif len(size) == 1:\n # Perform same logic as if size was an int\n size = size[0]\n else:\n raise ValueError(\"size must have 1 or 2 elements if it is a list or tuple\")\n\n if default_to_square:\n return (size, size)\n\n height, width = get_image_size(input_image, input_data_format)\n short, long = (width, height) if width <= height else (height, width)\n requested_new_short = size\n\n new_short, new_long = requested_new_short, int(requested_new_short * long / short)\n\n if max_size is not None:\n if max_size <= requested_new_short:\n raise ValueError(\n f\"max_size = {max_size} must be strictly greater than the requested \"\n f\"size for the smaller edge size = {size}\"\n )\n if new_long > max_size:\n new_short, new_long = int(max_size * new_short / new_long), max_size\n\n return (new_long, new_short) if width <= height else (new_short, new_long)"}, {"class_start_lineno": 63, "class_end_lineno": 345, "func_start_lineno": 134, "func_end_lineno": 176, "func_code": " def resize(\n self,\n image: np.ndarray,\n size: Dict[str, int],\n resample: PILImageResampling = PILImageResampling.BILINEAR,\n data_format: Optional[Union[str, ChannelDimension]] = None,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n **kwargs,\n ) -> np.ndarray:\n \"\"\"\n Resize an image.\n\n Args:\n image (`np.ndarray`):\n Image to resize.\n size (`Dict[str, int]`):\n Size of the output image. If `size` is of the form `{\"height\": h, \"width\": w}`, the output image will\n have the size `(h, w)`. If `size` is of the form `{\"shortest_edge\": s}`, the output image will have its\n shortest edge of length `s` while keeping the aspect ratio of the original image.\n resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):\n Resampling filter to use when resiizing the image.\n data_format (`str` or `ChannelDimension`, *optional*):\n The channel dimension format of the image. If not provided, it will be the same as the input image.\n input_data_format (`str` or `ChannelDimension`, *optional*):\n The channel dimension format of the input image. If not provided, it will be inferred.\n \"\"\"\n size = get_size_dict(size, default_to_square=False)\n if \"shortest_edge\" in size:\n output_size = get_resize_output_image_size(\n image, size[\"shortest_edge\"], default_to_square=False, input_data_format=input_data_format\n )\n elif \"height\" in size and \"width\" in size:\n output_size = (size[\"height\"], size[\"width\"])\n else:\n raise ValueError(f\"Size must have 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}\")\n return resize(\n image,\n size=output_size,\n resample=resample,\n data_format=data_format,\n input_data_format=input_data_format,\n **kwargs,\n )"}], "type": ["function_empty", "TDD"], "node": ["transformers.utils.generic.infer_framework_from_repr", "transformers.utils.generic._get_frameworks_and_test_func", "transformers.image_processing_utils.get_size_dict", "transformers.image_utils.get_image_size", "transformers.image_transforms.get_resize_output_image_size", "transformers.models.videomae.image_processing_videomae.VideoMAEImageProcessor.resize"], "language": "Python", "toolfunc_count": 4, "func_count": 6, "pytest_info": {"total_num": 13, "base_passed_num": 6}} {"id": ["transformers.src.transformers.utils.generic.infer_framework_from_repr", "transformers.src.transformers.utils.generic._get_frameworks_and_test_func", "transformers.src.transformers.image_processing_utils.get_size_dict", "transformers.src.transformers.image_utils.get_image_size", "transformers.src.transformers.image_transforms.get_resize_output_image_size", "transformers.src.transformers.models.vivit.image_processing_vivit.VivitImageProcessor::resize"], "project": "transformers", "origin_file": ["transformers/utils/generic.py", "transformers/utils/generic.py", "transformers/image_processing_utils.py", "transformers/image_utils.py", "transformers/image_transforms.py", "transformers/models/vivit/image_processing_vivit.py"], "test_list": ["tests/models/vivit/test_image_processing_vivit.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 856, "func_start_lineno": 80, "func_end_lineno": 95, "func_code": "def infer_framework_from_repr(x):\n \"\"\"\n Tries to guess the framework of an object `x` from its repr (brittle but will help in `is_tensor` to try the\n frameworks in a smart order, without the need to import the frameworks).\n \"\"\"\n representation = str(type(x))\n if representation.startswith(\" dict:\n \"\"\"\n Converts the old size parameter in the config into the new dict expected in the config. This is to ensure backwards\n compatibility with the old image processor configs and removes ambiguity over whether the tuple is in (height,\n width) or (width, height) format.\n\n - If `size` is tuple, it is converted to `{\"height\": size[0], \"width\": size[1]}` or `{\"height\": size[1], \"width\":\n size[0]}` if `height_width_order` is `False`.\n - If `size` is an int, and `default_to_square` is `True`, it is converted to `{\"height\": size, \"width\": size}`.\n - If `size` is an int and `default_to_square` is False, it is converted to `{\"shortest_edge\": size}`. If `max_size`\n is set, it is added to the dict as `{\"longest_edge\": max_size}`.\n\n Args:\n size (`Union[int, Iterable[int], Dict[str, int]]`, *optional*):\n The `size` parameter to be cast into a size dictionary.\n max_size (`Optional[int]`, *optional*):\n The `max_size` parameter to be cast into a size dictionary.\n height_width_order (`bool`, *optional*, defaults to `True`):\n If `size` is a tuple, whether it's in (height, width) or (width, height) order.\n default_to_square (`bool`, *optional*, defaults to `True`):\n If `size` is an int, whether to default to a square image or not.\n \"\"\"\n if not isinstance(size, dict):\n size_dict = convert_to_size_dict(size, max_size, default_to_square, height_width_order)\n logger.info(\n f\"{param_name} should be a dictionary on of the following set of keys: {VALID_SIZE_DICT_KEYS}, got {size}.\"\n f\" Converted to {size_dict}.\",\n )\n else:\n size_dict = size\n\n if not is_valid_size_dict(size_dict):\n raise ValueError(\n f\"{param_name} must have one of the following set of keys: {VALID_SIZE_DICT_KEYS}, got {size_dict.keys()}\"\n )\n return size_dict"}, {"class_start_lineno": 1, "class_end_lineno": 811, "func_start_lineno": 281, "func_end_lineno": 302, "func_code": "def get_image_size(image: np.ndarray, channel_dim: ChannelDimension = None) -> Tuple[int, int]:\n \"\"\"\n Returns the (height, width) dimensions of the image.\n\n Args:\n image (`np.ndarray`):\n The image to get the dimensions of.\n channel_dim (`ChannelDimension`, *optional*):\n Which dimension the channel dimension is in. If `None`, will infer the channel dimension from the image.\n\n Returns:\n A tuple of the image's height and width.\n \"\"\"\n if channel_dim is None:\n channel_dim = infer_channel_dimension_format(image)\n\n if channel_dim == ChannelDimension.FIRST:\n return image.shape[-2], image.shape[-1]\n elif channel_dim == ChannelDimension.LAST:\n return image.shape[-3], image.shape[-2]\n else:\n raise ValueError(f\"Unsupported data format: {channel_dim}\")"}, {"class_start_lineno": 1, "class_end_lineno": 854, "func_start_lineno": 214, "func_end_lineno": 278, "func_code": "def get_resize_output_image_size(\n input_image: np.ndarray,\n size: Union[int, Tuple[int, int], List[int], Tuple[int]],\n default_to_square: bool = True,\n max_size: Optional[int] = None,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n) -> tuple:\n \"\"\"\n Find the target (height, width) dimension of the output image after resizing given the input image and the desired\n size.\n\n Args:\n input_image (`np.ndarray`):\n The image to resize.\n size (`int` or `Tuple[int, int]` or List[int] or `Tuple[int]`):\n The size to use for resizing the image. If `size` is a sequence like (h, w), output size will be matched to\n this.\n\n If `size` is an int and `default_to_square` is `True`, then image will be resized to (size, size). If\n `size` is an int and `default_to_square` is `False`, then smaller edge of the image will be matched to this\n number. i.e, if height > width, then image will be rescaled to (size * height / width, size).\n default_to_square (`bool`, *optional*, defaults to `True`):\n How to convert `size` when it is a single int. If set to `True`, the `size` will be converted to a square\n (`size`,`size`). If set to `False`, will replicate\n [`torchvision.transforms.Resize`](https://pytorch.org/vision/stable/transforms.html#torchvision.transforms.Resize)\n with support for resizing only the smallest edge and providing an optional `max_size`.\n max_size (`int`, *optional*):\n The maximum allowed for the longer edge of the resized image: if the longer edge of the image is greater\n than `max_size` after being resized according to `size`, then the image is resized again so that the longer\n edge is equal to `max_size`. As a result, `size` might be overruled, i.e the smaller edge may be shorter\n than `size`. Only used if `default_to_square` is `False`.\n input_data_format (`ChannelDimension`, *optional*):\n The channel dimension format of the input image. If unset, will use the inferred format from the input.\n\n Returns:\n `tuple`: The target (height, width) dimension of the output image after resizing.\n \"\"\"\n if isinstance(size, (tuple, list)):\n if len(size) == 2:\n return tuple(size)\n elif len(size) == 1:\n # Perform same logic as if size was an int\n size = size[0]\n else:\n raise ValueError(\"size must have 1 or 2 elements if it is a list or tuple\")\n\n if default_to_square:\n return (size, size)\n\n height, width = get_image_size(input_image, input_data_format)\n short, long = (width, height) if width <= height else (height, width)\n requested_new_short = size\n\n new_short, new_long = requested_new_short, int(requested_new_short * long / short)\n\n if max_size is not None:\n if max_size <= requested_new_short:\n raise ValueError(\n f\"max_size = {max_size} must be strictly greater than the requested \"\n f\"size for the smaller edge size = {size}\"\n )\n if new_long > max_size:\n new_short, new_long = int(max_size * new_short / new_long), max_size\n\n return (new_long, new_short) if width <= height else (new_short, new_long)"}, {"class_start_lineno": 66, "class_end_lineno": 404, "func_start_lineno": 142, "func_end_lineno": 184, "func_code": " def resize(\n self,\n image: np.ndarray,\n size: Dict[str, int],\n resample: PILImageResampling = PILImageResampling.BILINEAR,\n data_format: Optional[Union[str, ChannelDimension]] = None,\n input_data_format: Optional[Union[str, ChannelDimension]] = None,\n **kwargs,\n ) -> np.ndarray:\n \"\"\"\n Resize an image.\n\n Args:\n image (`np.ndarray`):\n Image to resize.\n size (`Dict[str, int]`):\n Size of the output image. If `size` is of the form `{\"height\": h, \"width\": w}`, the output image will\n have the size `(h, w)`. If `size` is of the form `{\"shortest_edge\": s}`, the output image will have its\n shortest edge of length `s` while keeping the aspect ratio of the original image.\n resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):\n Resampling filter to use when resiizing the image.\n data_format (`str` or `ChannelDimension`, *optional*):\n The channel dimension format of the image. If not provided, it will be the same as the input image.\n input_data_format (`str` or `ChannelDimension`, *optional*):\n The channel dimension format of the input image. If not provided, it will be inferred.\n \"\"\"\n size = get_size_dict(size, default_to_square=False)\n if \"shortest_edge\" in size:\n output_size = get_resize_output_image_size(\n image, size[\"shortest_edge\"], default_to_square=False, input_data_format=input_data_format\n )\n elif \"height\" in size and \"width\" in size:\n output_size = (size[\"height\"], size[\"width\"])\n else:\n raise ValueError(f\"Size must have 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}\")\n return resize(\n image,\n size=output_size,\n resample=resample,\n data_format=data_format,\n input_data_format=input_data_format,\n **kwargs,\n )"}], "type": ["function_empty", "TDD"], "node": ["transformers.utils.generic.infer_framework_from_repr", "transformers.utils.generic._get_frameworks_and_test_func", "transformers.image_processing_utils.get_size_dict", "transformers.image_utils.get_image_size", "transformers.image_transforms.get_resize_output_image_size", "transformers.models.vivit.image_processing_vivit.VivitImageProcessor.resize"], "language": "Python", "toolfunc_count": 4, "func_count": 6, "pytest_info": {"total_num": 14, "base_passed_num": 7}} {"id": ["transformers.src.transformers.utils.logging._configure_library_root_logger", "transformers.src.transformers.utils.logging.get_logger", "transformers.src.transformers.utils.generic.to_py_obj", "transformers.src.transformers.utils.generic.infer_framework_from_repr", "transformers.src.transformers.utils.generic._get_frameworks_and_test_func", "transformers.src.transformers.models.wav2vec2.tokenization_wav2vec2.Wav2Vec2CTCTokenizer::decode"], "project": "transformers", "origin_file": ["transformers/utils/logging.py", "transformers/utils/logging.py", "transformers/utils/generic.py", "transformers/utils/generic.py", "transformers/utils/generic.py", "transformers/models/wav2vec2/tokenization_wav2vec2.py"], "test_list": ["tests/models/wav2vec2/test_tokenization_wav2vec2.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 410, "func_start_lineno": 81, "func_end_lineno": 104, "func_code": "def _configure_library_root_logger() -> None:\n global _default_handler\n\n with _lock:\n if _default_handler:\n # This library has already configured the library root logger.\n return\n _default_handler = logging.StreamHandler() # Set sys.stderr as stream.\n # set defaults based on https://github.com/pyinstaller/pyinstaller/issues/7334#issuecomment-1357447176\n if sys.stderr is None:\n sys.stderr = open(os.devnull, \"w\")\n\n _default_handler.flush = sys.stderr.flush\n\n # Apply our default configuration to the library root logger.\n library_root_logger = _get_library_root_logger()\n library_root_logger.addHandler(_default_handler)\n library_root_logger.setLevel(_get_default_logging_level())\n # if logging level is debug, we add pathname and lineno to formatter for easy debugging\n if os.getenv(\"TRANSFORMERS_VERBOSITY\", None) == \"detail\":\n formatter = logging.Formatter(\"[%(levelname)s|%(pathname)s:%(lineno)s] %(asctime)s >> %(message)s\")\n _default_handler.setFormatter(formatter)\n\n library_root_logger.propagate = False"}, {"class_start_lineno": 1, "class_end_lineno": 410, "func_start_lineno": 147, "func_end_lineno": 158, "func_code": "def get_logger(name: Optional[str] = None) -> logging.Logger:\n \"\"\"\n Return a logger with the specified name.\n\n This function is not supposed to be directly accessed unless you are writing a custom transformers module.\n \"\"\"\n\n if name is None:\n name = _get_library_name()\n\n _configure_library_root_logger()\n return logging.getLogger(name)"}, {"class_start_lineno": 1, "class_end_lineno": 856, "func_start_lineno": 254, "func_end_lineno": 281, "func_code": "def to_py_obj(obj):\n \"\"\"\n Convert a TensorFlow tensor, PyTorch tensor, Numpy array or python list to a python list.\n \"\"\"\n\n framework_to_py_obj = {\n \"pt\": lambda obj: obj.detach().cpu().tolist(),\n \"tf\": lambda obj: obj.numpy().tolist(),\n \"jax\": lambda obj: np.asarray(obj).tolist(),\n \"np\": lambda obj: obj.tolist(),\n }\n\n if isinstance(obj, (dict, UserDict)):\n return {k: to_py_obj(v) for k, v in obj.items()}\n elif isinstance(obj, (list, tuple)):\n return [to_py_obj(o) for o in obj]\n\n # This gives us a smart order to test the frameworks with the corresponding tests.\n framework_to_test_func = _get_frameworks_and_test_func(obj)\n for framework, test_func in framework_to_test_func.items():\n if test_func(obj):\n return framework_to_py_obj[framework](obj)\n\n # tolist also works on 0d np arrays\n if isinstance(obj, np.number):\n return obj.tolist()\n else:\n return obj"}, {"class_start_lineno": 1, "class_end_lineno": 856, "func_start_lineno": 80, "func_end_lineno": 95, "func_code": "def infer_framework_from_repr(x):\n \"\"\"\n Tries to guess the framework of an object `x` from its repr (brittle but will help in `is_tensor` to try the\n frameworks in a smart order, without the need to import the frameworks).\n \"\"\"\n representation = str(type(x))\n if representation.startswith(\" str:\n \"\"\"\n Converts a sequence of ids in a string, using the tokenizer and vocabulary with options to remove special\n tokens and clean up tokenization spaces.\n\n Similar to doing `self.convert_tokens_to_string(self.convert_ids_to_tokens(token_ids))`.\n\n Args:\n token_ids (`Union[int, List[int], np.ndarray, torch.Tensor, tf.Tensor]`):\n List of tokenized input ids. Can be obtained using the `__call__` method.\n skip_special_tokens (`bool`, *optional*, defaults to `False`):\n Whether or not to remove special tokens in the decoding.\n clean_up_tokenization_spaces (`bool`, *optional*):\n Whether or not to clean up the tokenization spaces.\n output_char_offsets (`bool`, *optional*, defaults to `False`):\n Whether or not to output character offsets. Character offsets can be used in combination with the\n sampling rate and model downsampling rate to compute the time-stamps of transcribed characters.\n\n \n\n Please take a look at the example below to better understand how to make use of `output_char_offsets`.\n\n \n\n output_word_offsets (`bool`, *optional*, defaults to `False`):\n Whether or not to output word offsets. Word offsets can be used in combination with the sampling rate\n and model downsampling rate to compute the time-stamps of transcribed words.\n\n \n\n Please take a look at the example below to better understand how to make use of `output_word_offsets`.\n\n \n\n kwargs (additional keyword arguments, *optional*):\n Will be passed to the underlying model specific decode method.\n\n Returns:\n `str` or [`~models.wav2vec2.tokenization_wav2vec2.Wav2Vec2CTCTokenizerOutput`]: The list of decoded\n sentences. Will be a [`~models.wav2vec2.tokenization_wav2vec2.Wav2Vec2CTCTokenizerOutput`] when\n `output_char_offsets == True` or `output_word_offsets == True`.\n\n Example:\n\n ```python\n >>> # Let's see how to retrieve time steps for a model\n >>> from transformers import AutoTokenizer, AutoFeatureExtractor, AutoModelForCTC\n >>> from datasets import load_dataset\n >>> import datasets\n >>> import torch\n\n >>> # import model, feature extractor, tokenizer\n >>> model = AutoModelForCTC.from_pretrained(\"facebook/wav2vec2-base-960h\")\n >>> tokenizer = AutoTokenizer.from_pretrained(\"facebook/wav2vec2-base-960h\")\n >>> feature_extractor = AutoFeatureExtractor.from_pretrained(\"facebook/wav2vec2-base-960h\")\n\n >>> # load first sample of English common_voice\n >>> dataset = load_dataset(\"mozilla-foundation/common_voice_11_0\", \"en\", split=\"train\", streaming=True, trust_remote_code=True)\n >>> dataset = dataset.cast_column(\"audio\", datasets.Audio(sampling_rate=16_000))\n >>> dataset_iter = iter(dataset)\n >>> sample = next(dataset_iter)\n\n >>> # forward sample through model to get greedily predicted transcription ids\n >>> input_values = feature_extractor(sample[\"audio\"][\"array\"], return_tensors=\"pt\").input_values\n >>> logits = model(input_values).logits[0]\n >>> pred_ids = torch.argmax(logits, axis=-1)\n\n >>> # retrieve word stamps (analogous commands for `output_char_offsets`)\n >>> outputs = tokenizer.decode(pred_ids, output_word_offsets=True)\n >>> # compute `time_offset` in seconds as product of downsampling ratio and sampling_rate\n >>> time_offset = model.config.inputs_to_logits_ratio / feature_extractor.sampling_rate\n\n >>> word_offsets = [\n ... {\n ... \"word\": d[\"word\"],\n ... \"start_time\": round(d[\"start_offset\"] * time_offset, 2),\n ... \"end_time\": round(d[\"end_offset\"] * time_offset, 2),\n ... }\n ... for d in outputs.word_offsets\n ... ]\n >>> # compare word offsets with audio `en_train_0/common_voice_en_19121553.mp3` online on the dataset viewer:\n >>> # https://huggingface.co/datasets/mozilla-foundation/common_voice_11_0/viewer/en\n >>> word_offsets[:3]\n [{'word': 'THE', 'start_time': 0.7, 'end_time': 0.78}, {'word': 'TRICK', 'start_time': 0.88, 'end_time': 1.08}, {'word': 'APPEARS', 'start_time': 1.2, 'end_time': 1.64}]\n ```\"\"\"\n # Convert inputs to python lists\n token_ids = to_py_obj(token_ids)\n\n return self._decode(\n token_ids=token_ids,\n skip_special_tokens=skip_special_tokens,\n clean_up_tokenization_spaces=clean_up_tokenization_spaces,\n output_char_offsets=output_char_offsets,\n output_word_offsets=output_word_offsets,\n **kwargs,\n )"}], "type": ["function_empty", "TDD"], "node": ["transformers.utils.logging._configure_library_root_logger", "transformers.utils.logging.get_logger", "transformers.utils.generic.to_py_obj", "transformers.utils.generic.infer_framework_from_repr", "transformers.utils.generic._get_frameworks_and_test_func", "transformers.models.wav2vec2.tokenization_wav2vec2.Wav2Vec2CTCTokenizer.decode"], "language": "Python", "toolfunc_count": 1, "func_count": 6, "pytest_info": {"total_num": 102, "base_passed_num": 0}} {"id": ["transformers.src.transformers.utils.logging._configure_library_root_logger", "transformers.src.transformers.utils.logging.get_logger", "transformers.src.transformers.utils.import_utils.create_import_structure_from_path", "transformers.src.transformers.utils.import_utils.define_import_structure"], "project": "transformers", "origin_file": ["transformers/utils/logging.py", "transformers/utils/logging.py", "transformers/utils/import_utils.py", "transformers/utils/import_utils.py"], "test_list": ["tests/utils/test_dynamic_module_utils.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 410, "func_start_lineno": 81, "func_end_lineno": 104, "func_code": "def _configure_library_root_logger() -> None:\n global _default_handler\n\n with _lock:\n if _default_handler:\n # This library has already configured the library root logger.\n return\n _default_handler = logging.StreamHandler() # Set sys.stderr as stream.\n # set defaults based on https://github.com/pyinstaller/pyinstaller/issues/7334#issuecomment-1357447176\n if sys.stderr is None:\n sys.stderr = open(os.devnull, \"w\")\n\n _default_handler.flush = sys.stderr.flush\n\n # Apply our default configuration to the library root logger.\n library_root_logger = _get_library_root_logger()\n library_root_logger.addHandler(_default_handler)\n library_root_logger.setLevel(_get_default_logging_level())\n # if logging level is debug, we add pathname and lineno to formatter for easy debugging\n if os.getenv(\"TRANSFORMERS_VERBOSITY\", None) == \"detail\":\n formatter = logging.Formatter(\"[%(levelname)s|%(pathname)s:%(lineno)s] %(asctime)s >> %(message)s\")\n _default_handler.setFormatter(formatter)\n\n library_root_logger.propagate = False"}, {"class_start_lineno": 1, "class_end_lineno": 410, "func_start_lineno": 147, "func_end_lineno": 158, "func_code": "def get_logger(name: Optional[str] = None) -> logging.Logger:\n \"\"\"\n Return a logger with the specified name.\n\n This function is not supposed to be directly accessed unless you are writing a custom transformers module.\n \"\"\"\n\n if name is None:\n name = _get_library_name()\n\n _configure_library_root_logger()\n return logging.getLogger(name)"}, {"class_start_lineno": 1, "class_end_lineno": 2158, "func_start_lineno": 1846, "func_end_lineno": 2037, "func_code": "def create_import_structure_from_path(module_path):\n \"\"\"\n This method takes the path to a file/a folder and returns the import structure.\n If a file is given, it will return the import structure of the parent folder.\n\n Import structures are designed to be digestible by `_LazyModule` objects. They are\n created from the __all__ definitions in each files as well as the `@export` decorators\n above methods and objects.\n\n The import structure allows explicit display of the required backends for a given object.\n These backends are specified in two ways:\n\n 1. Through their `@export`, if they are exported with that decorator. This `@export` decorator\n accepts a `backend` tuple kwarg mentioning which backends are required to run this object.\n\n 2. If an object is defined in a file with \"default\" backends, it will have, at a minimum, this\n backend specified. The default backends are defined according to the filename:\n\n - If a file is named like `modeling_*.py`, it will have a `torch` backend\n - If a file is named like `modeling_tf_*.py`, it will have a `tf` backend\n - If a file is named like `modeling_flax_*.py`, it will have a `flax` backend\n - If a file is named like `tokenization_*_fast.py`, it will have a `tokenizers` backend\n\n Backends serve the purpose of displaying a clear error message to the user in case the backends are not installed.\n Should an object be imported without its required backends being in the environment, any attempt to use the\n object will raise an error mentioning which backend(s) should be added to the environment in order to use\n that object.\n\n Here's an example of an input import structure at the src.transformers.models level:\n\n {\n 'albert': {\n frozenset(): {\n 'configuration_albert': {'AlbertConfig', 'AlbertOnnxConfig'}\n },\n frozenset({'tokenizers'}): {\n 'tokenization_albert_fast': {'AlbertTokenizerFast'}\n },\n },\n 'align': {\n frozenset(): {\n 'configuration_align': {'AlignConfig', 'AlignTextConfig', 'AlignVisionConfig'},\n 'processing_align': {'AlignProcessor'}\n },\n },\n 'altclip': {\n frozenset(): {\n 'configuration_altclip': {'AltCLIPConfig', 'AltCLIPTextConfig', 'AltCLIPVisionConfig'},\n 'processing_altclip': {'AltCLIPProcessor'},\n }\n }\n }\n \"\"\"\n import_structure = {}\n if os.path.isdir(module_path):\n directory = module_path\n adjacent_modules = []\n\n for f in os.listdir(module_path):\n if f != \"__pycache__\" and os.path.isdir(os.path.join(module_path, f)):\n import_structure[f] = create_import_structure_from_path(os.path.join(module_path, f))\n\n elif not os.path.isdir(os.path.join(directory, f)):\n adjacent_modules.append(f)\n\n else:\n directory = os.path.dirname(module_path)\n adjacent_modules = [f for f in os.listdir(directory) if not os.path.isdir(os.path.join(directory, f))]\n\n # We're only taking a look at files different from __init__.py\n # We could theoretically export things directly from the __init__.py\n # files, but this is not supported at this time.\n if \"__init__.py\" in adjacent_modules:\n adjacent_modules.remove(\"__init__.py\")\n\n module_requirements = {}\n for module_name in adjacent_modules:\n # Only modules ending in `.py` are accepted here.\n if not module_name.endswith(\".py\"):\n continue\n\n with open(os.path.join(directory, module_name)) as f:\n file_content = f.read()\n\n # Remove the .py suffix\n module_name = module_name[:-3]\n\n previous_line = \"\"\n previous_index = 0\n\n # Some files have some requirements by default.\n # For example, any file named `modeling_tf_xxx.py`\n # should have TensorFlow as a required backend.\n base_requirements = ()\n for string_check, requirements in BASE_FILE_REQUIREMENTS.items():\n if string_check(module_name):\n base_requirements = requirements\n break\n\n # Objects that have a `@export` assigned to them will get exported\n # with the backends specified in the decorator as well as the file backends.\n exported_objects = set()\n if \"@export\" in file_content:\n lines = file_content.split(\"\\n\")\n for index, line in enumerate(lines):\n # This allows exporting items with other decorators. We'll take a look\n # at the line that follows at the same indentation level.\n if line.startswith((\" \", \"\\t\", \"@\", \")\")) and not line.startswith(\"@export\"):\n continue\n\n # Skipping line enables putting whatever we want between the\n # export() call and the actual class/method definition.\n # This is what enables having # Copied from statements, docs, etc.\n skip_line = False\n\n if \"@export\" in previous_line:\n skip_line = False\n\n # Backends are defined on the same line as export\n if \"backends\" in previous_line:\n backends_string = previous_line.split(\"backends=\")[1].split(\"(\")[1].split(\")\")[0]\n backends = tuple(sorted([b.strip(\"'\\\",\") for b in backends_string.split(\", \") if b]))\n\n # Backends are defined in the lines following export, for example such as:\n # @export(\n # backends=(\n # \"sentencepiece\",\n # \"torch\",\n # \"tf\",\n # )\n # )\n #\n # or\n #\n # @export(\n # backends=(\n # \"sentencepiece\", \"tf\"\n # )\n # )\n elif \"backends\" in lines[previous_index + 1]:\n backends = []\n for backend_line in lines[previous_index:index]:\n if \"backends\" in backend_line:\n backend_line = backend_line.split(\"=\")[1]\n if '\"' in backend_line or \"'\" in backend_line:\n if \", \" in backend_line:\n backends.extend(backend.strip(\"()\\\"', \") for backend in backend_line.split(\", \"))\n else:\n backends.append(backend_line.strip(\"()\\\"', \"))\n\n # If the line is only a ')', then we reached the end of the backends and we break.\n if backend_line.strip() == \")\":\n break\n backends = tuple(backends)\n\n # No backends are registered for export\n else:\n backends = ()\n\n backends = frozenset(backends + base_requirements)\n if backends not in module_requirements:\n module_requirements[backends] = {}\n if module_name not in module_requirements[backends]:\n module_requirements[backends][module_name] = set()\n\n if not line.startswith(\"class\") and not line.startswith(\"def\"):\n skip_line = True\n else:\n start_index = 6 if line.startswith(\"class\") else 4\n object_name = line[start_index:].split(\"(\")[0].strip(\":\")\n module_requirements[backends][module_name].add(object_name)\n exported_objects.add(object_name)\n\n if not skip_line:\n previous_line = line\n previous_index = index\n\n # All objects that are in __all__ should be exported by default.\n # These objects are exported with the file backends.\n if \"__all__\" in file_content:\n for _all_object in fetch__all__(file_content):\n if _all_object not in exported_objects:\n backends = frozenset(base_requirements)\n if backends not in module_requirements:\n module_requirements[backends] = {}\n if module_name not in module_requirements[backends]:\n module_requirements[backends][module_name] = set()\n\n module_requirements[backends][module_name].add(_all_object)\n\n import_structure = {**module_requirements, **import_structure}\n return import_structure"}, {"class_start_lineno": 1, "class_end_lineno": 2158, "func_start_lineno": 2136, "func_end_lineno": 2158, "func_code": "def define_import_structure(module_path: str) -> IMPORT_STRUCTURE_T:\n \"\"\"\n This method takes a module_path as input and creates an import structure digestible by a _LazyModule.\n\n Here's an example of an output import structure at the src.transformers.models level:\n\n {\n frozenset({'tokenizers'}): {\n 'albert.tokenization_albert_fast': {'AlbertTokenizerFast'}\n },\n frozenset(): {\n 'albert.configuration_albert': {'AlbertConfig', 'AlbertOnnxConfig'},\n 'align.processing_align': {'AlignProcessor'},\n 'align.configuration_align': {'AlignConfig', 'AlignTextConfig', 'AlignVisionConfig'},\n 'altclip.configuration_altclip': {'AltCLIPConfig', 'AltCLIPTextConfig', 'AltCLIPVisionConfig'},\n 'altclip.processing_altclip': {'AltCLIPProcessor'}\n }\n }\n\n The import structure is a dict defined with frozensets as keys, and dicts of strings to sets of objects.\n \"\"\"\n import_structure = create_import_structure_from_path(module_path)\n return spread_import_structure(import_structure)"}], "type": ["function_empty", "TDD"], "node": ["transformers.utils.logging._configure_library_root_logger", "transformers.utils.logging.get_logger", "transformers.utils.import_utils.create_import_structure_from_path", "transformers.utils.import_utils.define_import_structure"], "language": "Python", "toolfunc_count": 3, "func_count": 4, "pytest_info": {"total_num": 10, "base_passed_num": 0}} {"id": ["transformers.src.transformers.utils.generic.infer_framework", "transformers.src.transformers.utils.generic.find_labels"], "project": "transformers", "origin_file": ["transformers/utils/generic.py", "transformers/utils/generic.py"], "test_list": ["tests/utils/test_file_utils.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 856, "func_start_lineno": 738, "func_end_lineno": 753, "func_code": "def infer_framework(model_class):\n \"\"\"\n Infers the framework of a given model without using isinstance(), because we cannot guarantee that the relevant\n classes are imported or available.\n \"\"\"\n for base_class in inspect.getmro(model_class):\n module = base_class.__module__\n name = base_class.__name__\n if module.startswith(\"tensorflow\") or module.startswith(\"keras\") or name == \"TFPreTrainedModel\":\n return \"tf\"\n elif module.startswith(\"torch\") or name == \"PreTrainedModel\":\n return \"pt\"\n elif module.startswith(\"flax\") or module.startswith(\"jax\") or name == \"FlaxPreTrainedModel\":\n return \"flax\"\n else:\n raise TypeError(f\"Could not infer framework from class {model_class}.\")"}, {"class_start_lineno": 1, "class_end_lineno": 856, "func_start_lineno": 565, "func_end_lineno": 584, "func_code": "def find_labels(model_class):\n \"\"\"\n Find the labels used by a given model.\n\n Args:\n model_class (`type`): The class of the model.\n \"\"\"\n model_name = model_class.__name__\n framework = infer_framework(model_class)\n if framework == \"tf\":\n signature = inspect.signature(model_class.call) # TensorFlow models\n elif framework == \"pt\":\n signature = inspect.signature(model_class.forward) # PyTorch models\n else:\n signature = inspect.signature(model_class.__call__) # Flax models\n\n if \"QuestionAnswering\" in model_name:\n return [p for p in signature.parameters if \"label\" in p or p in (\"start_positions\", \"end_positions\")]\n else:\n return [p for p in signature.parameters if \"label\" in p]"}], "type": ["function_empty", "TDD"], "node": ["transformers.utils.generic.infer_framework", "transformers.utils.generic.find_labels"], "language": "Python", "toolfunc_count": 1, "func_count": 2, "pytest_info": {"total_num": 5, "base_passed_num": 4}} {"id": ["transformers.src.transformers.utils.logging._configure_library_root_logger", "transformers.src.transformers.utils.logging.get_logger", "transformers.src.transformers.utils.logging.get_verbosity", "transformers.src.transformers.utils.logging.set_verbosity"], "project": "transformers", "origin_file": ["transformers/utils/logging.py", "transformers/utils/logging.py", "transformers/utils/logging.py", "transformers/utils/logging.py", "transformers/utils/logging.py"], "test_list": ["tests/utils/test_logging.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 410, "func_start_lineno": 81, "func_end_lineno": 104, "func_code": "def _configure_library_root_logger() -> None:\n global _default_handler\n\n with _lock:\n if _default_handler:\n # This library has already configured the library root logger.\n return\n _default_handler = logging.StreamHandler() # Set sys.stderr as stream.\n # set defaults based on https://github.com/pyinstaller/pyinstaller/issues/7334#issuecomment-1357447176\n if sys.stderr is None:\n sys.stderr = open(os.devnull, \"w\")\n\n _default_handler.flush = sys.stderr.flush\n\n # Apply our default configuration to the library root logger.\n library_root_logger = _get_library_root_logger()\n library_root_logger.addHandler(_default_handler)\n library_root_logger.setLevel(_get_default_logging_level())\n # if logging level is debug, we add pathname and lineno to formatter for easy debugging\n if os.getenv(\"TRANSFORMERS_VERBOSITY\", None) == \"detail\":\n formatter = logging.Formatter(\"[%(levelname)s|%(pathname)s:%(lineno)s] %(asctime)s >> %(message)s\")\n _default_handler.setFormatter(formatter)\n\n library_root_logger.propagate = False"}, {"class_start_lineno": 1, "class_end_lineno": 410, "func_start_lineno": 147, "func_end_lineno": 158, "func_code": "def get_logger(name: Optional[str] = None) -> logging.Logger:\n \"\"\"\n Return a logger with the specified name.\n\n This function is not supposed to be directly accessed unless you are writing a custom transformers module.\n \"\"\"\n\n if name is None:\n name = _get_library_name()\n\n _configure_library_root_logger()\n return logging.getLogger(name)"}, {"class_start_lineno": 1, "class_end_lineno": 410, "func_start_lineno": 161, "func_end_lineno": 181, "func_code": "def get_verbosity() -> int:\n \"\"\"\n Return the current level for the 🤗 Transformers's root logger as an int.\n\n Returns:\n `int`: The logging level.\n\n \n\n 🤗 Transformers has following logging levels:\n\n - 50: `transformers.logging.CRITICAL` or `transformers.logging.FATAL`\n - 40: `transformers.logging.ERROR`\n - 30: `transformers.logging.WARNING` or `transformers.logging.WARN`\n - 20: `transformers.logging.INFO`\n - 10: `transformers.logging.DEBUG`\n\n \"\"\"\n\n _configure_library_root_logger()\n return _get_library_root_logger().getEffectiveLevel()"}, {"class_start_lineno": 1, "class_end_lineno": 410, "func_start_lineno": 184, "func_end_lineno": 200, "func_code": "def set_verbosity(verbosity: int) -> None:\n \"\"\"\n Set the verbosity level for the 🤗 Transformers's root logger.\n\n Args:\n verbosity (`int`):\n Logging level, e.g., one of:\n\n - `transformers.logging.CRITICAL` or `transformers.logging.FATAL`\n - `transformers.logging.ERROR`\n - `transformers.logging.WARNING` or `transformers.logging.WARN`\n - `transformers.logging.INFO`\n - `transformers.logging.DEBUG`\n \"\"\"\n\n _configure_library_root_logger()\n _get_library_root_logger().setLevel(verbosity)"}, {"class_start_lineno": 1, "class_end_lineno": 410, "func_start_lineno": 218, "func_end_lineno": 220, "func_code": "def set_verbosity_error():\n \"\"\"Set the verbosity to the `ERROR` level.\"\"\"\n return set_verbosity(ERROR)"}], "type": ["function_empty", "TDD"], "node": ["transformers.utils.logging._configure_library_root_logger", "transformers.utils.logging.get_logger", "transformers.utils.logging.get_verbosity", "transformers.utils.logging.set_verbosity", "transformers.utils.logging.set_verbosity_error"], "language": "Python", "toolfunc_count": 3, "func_count": 4, "pytest_info": {"total_num": 6, "base_passed_num": 0}} {"id": ["transformers.src.transformers.modeling_rope_utils._compute_default_rope_parameters", "transformers.src.transformers.modeling_rope_utils._compute_linear_scaling_rope_parameters", "transformers.src.transformers.modeling_rope_utils._compute_llama3_parameters", "transformers.src.transformers.modeling_rope_utils._check_received_keys", "transformers.src.transformers.modeling_rope_utils.rope_config_validation"], "project": "transformers", "origin_file": ["transformers/modeling_rope_utils.py", "transformers/modeling_rope_utils.py", "transformers/modeling_rope_utils.py", "transformers/modeling_rope_utils.py", "transformers/modeling_rope_utils.py", "transformers/modeling_rope_utils.py"], "test_list": ["tests/utils/test_modeling_rope_utils.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 560, "func_start_lineno": 29, "func_end_lineno": 68, "func_code": "def _compute_default_rope_parameters(\n config: Optional[PretrainedConfig] = None,\n device: Optional[\"torch.device\"] = None,\n seq_len: Optional[int] = None,\n **rope_kwargs,\n) -> Tuple[\"torch.Tensor\", float]:\n \"\"\"\n Computes the inverse frequencies according to the original RoPE implementation\n Args:\n config ([`~transformers.PretrainedConfig`]):\n The model configuration.\n device (`torch.device`):\n The device to use for initialization of the inverse frequencies.\n seq_len (`int`, *optional*):\n The current sequence length. Unused for this type of RoPE.\n rope_kwargs (`Dict`, *optional*):\n BC compatibility with the previous RoPE class instantiation, will be removed in v4.45.\n Returns:\n Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the\n post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).\n \"\"\"\n if config is not None and len(rope_kwargs) > 0:\n raise ValueError(\n \"Unexpected arguments: `**rope_kwargs` and `config` are mutually exclusive in \"\n f\"`_compute_default_rope_parameters`, got `rope_kwargs`={rope_kwargs} and `config`={config}\"\n )\n if len(rope_kwargs) > 0:\n base = rope_kwargs[\"base\"]\n dim = rope_kwargs[\"dim\"]\n elif config is not None:\n base = config.rope_theta\n partial_rotary_factor = config.partial_rotary_factor if hasattr(config, \"partial_rotary_factor\") else 1.0\n head_dim = getattr(config, \"head_dim\", config.hidden_size // config.num_attention_heads)\n dim = int(head_dim * partial_rotary_factor)\n\n attention_factor = 1.0 # Unused in this type of RoPE\n\n # Compute the inverse frequencies\n inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.int64).float().to(device) / dim))\n return inv_freq, attention_factor"}, {"class_start_lineno": 1, "class_end_lineno": 560, "func_start_lineno": 71, "func_end_lineno": 109, "func_code": "def _compute_linear_scaling_rope_parameters(\n config: Optional[PretrainedConfig] = None,\n device: Optional[\"torch.device\"] = None,\n seq_len: Optional[int] = None,\n **rope_kwargs,\n) -> Tuple[\"torch.Tensor\", float]:\n \"\"\"\n Computes the inverse frequencies with linear scaling. Credits to the Reddit user /u/kaiokendev\n Args:\n config ([`~transformers.PretrainedConfig`]):\n The model configuration.\n device (`torch.device`):\n The device to use for initialization of the inverse frequencies.\n seq_len (`int`, *optional*):\n The current sequence length. Unused for this type of RoPE.\n rope_kwargs (`Dict`, *optional*):\n BC compatibility with the previous RoPE class instantiation, will be removed in v4.45.\n Returns:\n Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the\n post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).\n \"\"\"\n if config is not None and len(rope_kwargs) > 0:\n raise ValueError(\n \"Unexpected arguments: `**rope_kwargs` and `config` are mutually exclusive in \"\n f\"`_compute_linear_scaling_rope_parameters`, got `rope_kwargs`={rope_kwargs} and `config`={config}\"\n )\n if len(rope_kwargs) > 0:\n factor = rope_kwargs[\"factor\"]\n elif config is not None:\n factor = config.rope_scaling[\"factor\"]\n\n # Gets the default RoPE parameters\n inv_freq, attention_factor = _compute_default_rope_parameters(config, device, seq_len, **rope_kwargs)\n\n # Then applies linear scaling to the frequencies.\n # NOTE: originally, scaling was applied to the position_ids. However, we get `embs = inv_freq @ position_ids`, so\n # applying scaling to the inverse frequencies is equivalent.\n inv_freq /= factor\n return inv_freq, attention_factor"}, {"class_start_lineno": 1, "class_end_lineno": 560, "func_start_lineno": 307, "func_end_lineno": 347, "func_code": "def _compute_llama3_parameters(\n config: PretrainedConfig, device: \"torch.device\", seq_len: Optional[int] = None, **rope_kwargs\n) -> Tuple[\"torch.Tensor\", float]:\n \"\"\"\n Computes the inverse frequencies for llama 3.1.\n\n Args:\n config ([`~transformers.PretrainedConfig`]):\n The model configuration.\n device (`torch.device`):\n The device to use for initialization of the inverse frequencies.\n seq_len (`int`, *optional*):\n The current sequence length. Unused for this type of RoPE.\n rope_kwargs (`Dict`, *optional*):\n BC compatibility with the previous RoPE class instantiation, will be removed in v4.45.\n Returns:\n Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the\n post-processing scaling factor applied to the computed cos/sin.\n \"\"\"\n # Gets the default RoPE parameters\n inv_freq, attention_factor = _compute_default_rope_parameters(config, device, seq_len, **rope_kwargs)\n\n factor = config.rope_scaling[\"factor\"] # `8` in the original implementation\n low_freq_factor = config.rope_scaling[\"low_freq_factor\"] # `1` in the original implementation\n high_freq_factor = config.rope_scaling[\"high_freq_factor\"] # `4` in the original implementation\n old_context_len = config.rope_scaling[\"original_max_position_embeddings\"] # `8192` in the original implementation\n\n low_freq_wavelen = old_context_len / low_freq_factor\n high_freq_wavelen = old_context_len / high_freq_factor\n\n wavelen = 2 * math.pi / inv_freq\n # wavelen < high_freq_wavelen: do nothing\n # wavelen > low_freq_wavelen: divide by factor\n inv_freq_llama = torch.where(wavelen > low_freq_wavelen, inv_freq / factor, inv_freq)\n # otherwise: interpolate between the two, using a smooth factor\n smooth_factor = (old_context_len / wavelen - low_freq_factor) / (high_freq_factor - low_freq_factor)\n smoothed_inv_freq = (1 - smooth_factor) * inv_freq_llama / factor + smooth_factor * inv_freq_llama\n is_medium_freq = ~(wavelen < high_freq_wavelen) * ~(wavelen > low_freq_wavelen)\n inv_freq_llama = torch.where(is_medium_freq, smoothed_inv_freq, inv_freq_llama)\n\n return inv_freq_llama, attention_factor"}, {"class_start_lineno": 1, "class_end_lineno": 560, "func_start_lineno": 363, "func_end_lineno": 379, "func_code": "def _check_received_keys(rope_type: str, received_keys: set, required_keys: set, optional_keys: Optional[set] = None):\n \"\"\"Compare the received keys in `config.rope_scaling` against the expected and optional keys\"\"\"\n # BC: \"rope_type\" was originally \"type\" -- let's check for \"rope_type\" when \"type\" is present\n if \"type\" in received_keys:\n received_keys -= {\"type\"}\n required_keys.add(\"rope_type\")\n\n missing_keys = required_keys - received_keys\n if missing_keys:\n raise KeyError(f\"Missing required keys in `rope_scaling` for 'rope_type'='{rope_type}': {missing_keys}\")\n\n if optional_keys is not None:\n unused_keys = received_keys - required_keys - optional_keys\n else:\n unused_keys = received_keys - required_keys\n if unused_keys:\n logger.warning(f\"Unrecognized keys in `rope_scaling` for 'rope_type'='{rope_type}': {unused_keys}\")"}, {"class_start_lineno": 1, "class_end_lineno": 560, "func_start_lineno": 447, "func_end_lineno": 494, "func_code": "def _validate_longrope_parameters(config: PretrainedConfig):\n rope_scaling = config.rope_scaling\n rope_type = rope_scaling.get(\"rope_type\", rope_scaling.get(\"type\", None)) # BC: \"rope_type\" was originally \"type\"\n required_keys = {\"rope_type\", \"short_factor\", \"long_factor\"}\n # TODO (joao): update logic for the inclusion of `original_max_position_embeddings`\n optional_keys = {\"attention_factor\", \"factor\", \"original_max_position_embeddings\"}\n received_keys = set(rope_scaling.keys())\n _check_received_keys(rope_type, received_keys, required_keys, optional_keys)\n\n partial_rotary_factor = config.partial_rotary_factor if hasattr(config, \"partial_rotary_factor\") else 1.0\n head_dim = getattr(config, \"head_dim\", config.hidden_size // config.num_attention_heads)\n dim = int(head_dim * partial_rotary_factor)\n\n short_factor = rope_scaling.get(\"short_factor\")\n if not isinstance(short_factor, list) and all(isinstance(x, (int, float)) for x in short_factor):\n logger.warning(f\"`rope_scaling`'s short_factor field must be a list of numbers, got {short_factor}\")\n if not len(short_factor) == dim // 2:\n logger.warning(f\"`rope_scaling`'s short_factor field must have length {dim // 2}, got {len(short_factor)}\")\n\n long_factor = rope_scaling.get(\"long_factor\")\n if not isinstance(long_factor, list) and all(isinstance(x, (int, float)) for x in long_factor):\n logger.warning(f\"`rope_scaling`'s long_factor field must be a list of numbers, got {long_factor}\")\n if not len(long_factor) == dim // 2:\n logger.warning(f\"`rope_scaling`'s long_factor field must have length {dim // 2}, got {len(long_factor)}\")\n\n # Handle Phi3 divergence: prefer the use of `attention_factor` and/or `factor` over\n # `original_max_position_embeddings` to compute internal variables. The latter lives outside `rope_scaling` and is\n # unique to longrope (= undesirable)\n if hasattr(config, \"original_max_position_embeddings\"):\n logger.warning_once(\n \"This model has set a `original_max_position_embeddings` field, to be used together with \"\n \"`max_position_embeddings` to determine a scaling factor. Please set the `factor` field of `rope_scaling`\"\n \"with this ratio instead -- we recommend the use of this field over `original_max_position_embeddings`, \"\n \"as it is compatible with most model architectures.\"\n )\n else:\n factor = rope_scaling.get(\"factor\")\n if factor is None:\n logger.warning(\"Missing required keys in `rope_scaling`: 'factor'\")\n elif not isinstance(factor, float) or factor < 1.0:\n logger.warning(f\"`rope_scaling`'s factor field must be a float >= 1, got {factor}\")\n\n attention_factor = rope_scaling.get(\"attention_factor\")\n if attention_factor is not None:\n if not isinstance(attention_factor, float) or attention_factor < 0.0:\n logger.warning(\n f\"`rope_scaling`'s attention_factor field must be a float greater than 0, got {attention_factor}\"\n )"}, {"class_start_lineno": 1, "class_end_lineno": 560, "func_start_lineno": 544, "func_end_lineno": 560, "func_code": "def rope_config_validation(config: PretrainedConfig):\n \"\"\"\n Validate the RoPE config arguments, given a `PretrainedConfig` object\n \"\"\"\n rope_scaling = getattr(config, \"rope_scaling\", None) # not a default parameter in `PretrainedConfig`\n if rope_scaling is None:\n return\n\n # BC: \"rope_type\" was originally \"type\"\n rope_type = rope_scaling.get(\"rope_type\", rope_scaling.get(\"type\", \"default\"))\n validation_fn = ROPE_VALIDATION_FUNCTIONS.get(rope_type)\n if validation_fn is not None:\n validation_fn(config)\n else:\n logger.warning(\n f\"Missing validation function mapping in `ROPE_VALIDATION_FUNCTIONS` for 'rope_type'='{rope_type}'\"\n )"}], "type": ["function_empty", "TDD"], "node": ["transformers.modeling_rope_utils._compute_default_rope_parameters", "transformers.modeling_rope_utils._compute_linear_scaling_rope_parameters", "transformers.modeling_rope_utils._compute_llama3_parameters", "transformers.modeling_rope_utils._check_received_keys", "transformers.modeling_rope_utils._validate_longrope_parameters", "transformers.modeling_rope_utils.rope_config_validation"], "language": "Python", "toolfunc_count": 4, "func_count": 5, "pytest_info": {"total_num": 10, "base_passed_num": 1}} {"id": ["langchain_core.libs.core.langchain_core.load.dump.dumps", "langchain_core.libs.core.langchain_core.load.dump.default", "langchain_core.libs.core.langchain_core.load.dump.dumpd"], "project": "langchain_core", "origin_file": ["langchain_core/load/dump.py", "langchain_core/load/dump.py", "langchain_core/load/dump.py"], "test_list": ["libs/core/tests/unit_tests/load/test_serializable.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 70, "func_start_lineno": 23, "func_end_lineno": 53, "func_code": "def dumps(obj: Any, *, pretty: bool = False, **kwargs: Any) -> str:\n \"\"\"Return a json string representation of an object.\n\n Args:\n obj: The object to dump.\n pretty: Whether to pretty print the json. If true, the json will be\n indented with 2 spaces (if no indent is provided as part of kwargs).\n Default is False.\n kwargs: Additional arguments to pass to json.dumps\n\n Returns:\n A json string representation of the object.\n\n Raises:\n ValueError: If `default` is passed as a kwarg.\n \"\"\"\n if \"default\" in kwargs:\n msg = \"`default` should not be passed to dumps\"\n raise ValueError(msg)\n try:\n if pretty:\n indent = kwargs.pop(\"indent\", 2)\n return json.dumps(obj, default=default, indent=indent, **kwargs)\n else:\n return json.dumps(obj, default=default, **kwargs)\n except TypeError:\n if pretty:\n indent = kwargs.pop(\"indent\", 2)\n return json.dumps(to_json_not_implemented(obj), indent=indent, **kwargs)\n else:\n return json.dumps(to_json_not_implemented(obj), **kwargs)"}, {"class_start_lineno": 1, "class_end_lineno": 70, "func_start_lineno": 7, "func_end_lineno": 20, "func_code": "def default(obj: Any) -> Any:\n \"\"\"Return a default value for a Serializable object or\n a SerializedNotImplemented object.\n\n Args:\n obj: The object to serialize to json if it is a Serializable object.\n\n Returns:\n A json serializable object or a SerializedNotImplemented object.\n \"\"\"\n if isinstance(obj, Serializable):\n return obj.to_json()\n else:\n return to_json_not_implemented(obj)"}, {"class_start_lineno": 1, "class_end_lineno": 70, "func_start_lineno": 56, "func_end_lineno": 70, "func_code": "def dumpd(obj: Any) -> Any:\n \"\"\"Return a dict representation of an object.\n\n Note:\n Unfortunately this function is not as efficient as it could be\n because it first dumps the object to a json string and then loads it\n back into a dictionary.\n\n Args:\n obj: The object to dump.\n\n Returns:\n dictionary that can be serialized to json using json.dumps\n \"\"\"\n return json.loads(dumps(obj))"}], "type": ["function_empty"], "node": ["langchain_core.load.dump.dumps", "langchain_core.load.dump.default", "langchain_core.load.dump.dumpd"], "language": "Python", "toolfunc_count": 3, "func_count": 3, "pytest_info": {"total_num": 8, "base_passed_num": 3}} {"id": ["langchain_core.libs.core.langchain_core.load.dump.dumps", "langchain_core.libs.core.langchain_core.load.dump.default", "langchain_core.libs.core.langchain_core.load.dump.dumpd", "langchain_core.libs.core.langchain_core.utils.json.parse_partial_json", "langchain_core.libs.core.langchain_core.messages.ai.AIMessageChunk::init_tool_calls"], "project": "langchain_core", "origin_file": ["langchain_core/load/dump.py", "langchain_core/load/dump.py", "langchain_core/load/dump.py", "langchain_core/utils/json.py", "langchain_core/messages/ai.py"], "test_list": ["libs/core/tests/unit_tests/messages/test_ai.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 70, "func_start_lineno": 23, "func_end_lineno": 53, "func_code": "def dumps(obj: Any, *, pretty: bool = False, **kwargs: Any) -> str:\n \"\"\"Return a json string representation of an object.\n\n Args:\n obj: The object to dump.\n pretty: Whether to pretty print the json. If true, the json will be\n indented with 2 spaces (if no indent is provided as part of kwargs).\n Default is False.\n kwargs: Additional arguments to pass to json.dumps\n\n Returns:\n A json string representation of the object.\n\n Raises:\n ValueError: If `default` is passed as a kwarg.\n \"\"\"\n if \"default\" in kwargs:\n msg = \"`default` should not be passed to dumps\"\n raise ValueError(msg)\n try:\n if pretty:\n indent = kwargs.pop(\"indent\", 2)\n return json.dumps(obj, default=default, indent=indent, **kwargs)\n else:\n return json.dumps(obj, default=default, **kwargs)\n except TypeError:\n if pretty:\n indent = kwargs.pop(\"indent\", 2)\n return json.dumps(to_json_not_implemented(obj), indent=indent, **kwargs)\n else:\n return json.dumps(to_json_not_implemented(obj), **kwargs)"}, {"class_start_lineno": 1, "class_end_lineno": 70, "func_start_lineno": 7, "func_end_lineno": 20, "func_code": "def default(obj: Any) -> Any:\n \"\"\"Return a default value for a Serializable object or\n a SerializedNotImplemented object.\n\n Args:\n obj: The object to serialize to json if it is a Serializable object.\n\n Returns:\n A json serializable object or a SerializedNotImplemented object.\n \"\"\"\n if isinstance(obj, Serializable):\n return obj.to_json()\n else:\n return to_json_not_implemented(obj)"}, {"class_start_lineno": 1, "class_end_lineno": 70, "func_start_lineno": 56, "func_end_lineno": 70, "func_code": "def dumpd(obj: Any) -> Any:\n \"\"\"Return a dict representation of an object.\n\n Note:\n Unfortunately this function is not as efficient as it could be\n because it first dumps the object to a json string and then loads it\n back into a dictionary.\n\n Args:\n obj: The object to dump.\n\n Returns:\n dictionary that can be serialized to json using json.dumps\n \"\"\"\n return json.loads(dumps(obj))"}, {"class_start_lineno": 1, "class_end_lineno": 191, "func_start_lineno": 43, "func_end_lineno": 119, "func_code": "def parse_partial_json(s: str, *, strict: bool = False) -> Any:\n \"\"\"Parse a JSON string that may be missing closing braces.\n\n Args:\n s: The JSON string to parse.\n strict: Whether to use strict parsing. Defaults to False.\n\n Returns:\n The parsed JSON object as a Python dictionary.\n \"\"\"\n # Attempt to parse the string as-is.\n try:\n return json.loads(s, strict=strict)\n except json.JSONDecodeError:\n pass\n\n # Initialize variables.\n new_chars = []\n stack = []\n is_inside_string = False\n escaped = False\n\n # Process each character in the string one at a time.\n for char in s:\n if is_inside_string:\n if char == '\"' and not escaped:\n is_inside_string = False\n elif char == \"\\n\" and not escaped:\n char = \"\\\\n\" # Replace the newline character with the escape sequence.\n elif char == \"\\\\\":\n escaped = not escaped\n else:\n escaped = False\n else:\n if char == '\"':\n is_inside_string = True\n escaped = False\n elif char == \"{\":\n stack.append(\"}\")\n elif char == \"[\":\n stack.append(\"]\")\n elif char == \"}\" or char == \"]\":\n if stack and stack[-1] == char:\n stack.pop()\n else:\n # Mismatched closing character; the input is malformed.\n return None\n\n # Append the processed character to the new string.\n new_chars.append(char)\n\n # If we're still inside a string at the end of processing,\n # we need to close the string.\n if is_inside_string:\n if escaped: # Remoe unterminated escape character\n new_chars.pop()\n new_chars.append('\"')\n\n # Reverse the stack to get the closing characters.\n stack.reverse()\n\n # Try to parse mods of string until we succeed or run out of characters.\n while new_chars:\n # Close any remaining open structures in the reverse\n # order that they were opened.\n # Attempt to parse the modified string as JSON.\n try:\n return json.loads(\"\".join(new_chars + stack), strict=strict)\n except json.JSONDecodeError:\n # If we still can't parse the string as JSON,\n # try removing the last character\n new_chars.pop()\n\n # If we got here, we ran out of characters to remove\n # and still couldn't parse the string as JSON, so return the parse error\n # for the original string.\n return json.loads(s, strict=strict)"}, {"class_start_lineno": 296, "class_end_lineno": 403, "func_start_lineno": 328, "func_end_lineno": 394, "func_code": " def init_tool_calls(self) -> Self:\n \"\"\"Initialize tool calls from tool call chunks.\n\n Args:\n values: The values to validate.\n\n Returns:\n The values with tool calls initialized.\n\n Raises:\n ValueError: If the tool call chunks are malformed.\n \"\"\"\n if not self.tool_call_chunks:\n if self.tool_calls:\n self.tool_call_chunks = [\n create_tool_call_chunk(\n name=tc[\"name\"],\n args=json.dumps(tc[\"args\"]),\n id=tc[\"id\"],\n index=None,\n )\n for tc in self.tool_calls\n ]\n if self.invalid_tool_calls:\n tool_call_chunks = self.tool_call_chunks\n tool_call_chunks.extend(\n [\n create_tool_call_chunk(\n name=tc[\"name\"], args=tc[\"args\"], id=tc[\"id\"], index=None\n )\n for tc in self.invalid_tool_calls\n ]\n )\n self.tool_call_chunks = tool_call_chunks\n\n return self\n tool_calls = []\n invalid_tool_calls = []\n\n def add_chunk_to_invalid_tool_calls(chunk: ToolCallChunk) -> None:\n invalid_tool_calls.append(\n create_invalid_tool_call(\n name=chunk[\"name\"],\n args=chunk[\"args\"],\n id=chunk[\"id\"],\n error=None,\n )\n )\n\n for chunk in self.tool_call_chunks:\n try:\n args_ = parse_partial_json(chunk[\"args\"]) if chunk[\"args\"] != \"\" else {} # type: ignore[arg-type]\n if isinstance(args_, dict):\n tool_calls.append(\n create_tool_call(\n name=chunk[\"name\"] or \"\",\n args=args_,\n id=chunk[\"id\"],\n )\n )\n else:\n add_chunk_to_invalid_tool_calls(chunk)\n except Exception:\n add_chunk_to_invalid_tool_calls(chunk)\n self.tool_calls = tool_calls\n self.invalid_tool_calls = invalid_tool_calls\n return self"}], "type": ["function_empty"], "node": ["langchain_core.load.dump.dumps", "langchain_core.load.dump.default", "langchain_core.load.dump.dumpd", "langchain_core.utils.json.parse_partial_json", "langchain_core.messages.ai.AIMessageChunk.init_tool_calls"], "language": "Python", "toolfunc_count": 5, "func_count": 5, "pytest_info": {"total_num": 11, "base_passed_num": 9}} {"id": ["langchain_core.libs.core.langchain_core.runnables.config.ensure_config", "langchain_core.libs.core.langchain_core.runnables.config.patch_config", "langchain_core.libs.core.langchain_core.utils.json.parse_json_markdown", "langchain_core.libs.core.langchain_core.output_parsers.json.JsonOutputParser::parse_result"], "project": "langchain_core", "origin_file": ["langchain_core/runnables/config.py", "langchain_core/runnables/config.py", "langchain_core/utils/json.py", "langchain_core/output_parsers/json.py"], "test_list": ["libs/core/tests/unit_tests/output_parsers/test_json.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 593, "func_start_lineno": 149, "func_end_lineno": 199, "func_code": "def ensure_config(config: Optional[RunnableConfig] = None) -> RunnableConfig:\n \"\"\"Ensure that a config is a dict with all keys present.\n\n Args:\n config (Optional[RunnableConfig], optional): The config to ensure.\n Defaults to None.\n\n Returns:\n RunnableConfig: The ensured config.\n \"\"\"\n empty = RunnableConfig(\n tags=[],\n metadata={},\n callbacks=None,\n recursion_limit=DEFAULT_RECURSION_LIMIT,\n configurable={},\n )\n if var_config := var_child_runnable_config.get():\n empty.update(\n cast(\n RunnableConfig,\n {\n k: v.copy() if k in COPIABLE_KEYS else v # type: ignore[attr-defined]\n for k, v in var_config.items()\n if v is not None\n },\n )\n )\n if config is not None:\n empty.update(\n cast(\n RunnableConfig,\n {\n k: v.copy() if k in COPIABLE_KEYS else v # type: ignore[attr-defined]\n for k, v in config.items()\n if v is not None and k in CONFIG_KEYS\n },\n )\n )\n if config is not None:\n for k, v in config.items():\n if k not in CONFIG_KEYS and v is not None:\n empty[\"configurable\"][k] = v\n for key, value in empty.get(\"configurable\", {}).items():\n if (\n not key.startswith(\"__\")\n and isinstance(value, (str, int, float, bool))\n and key not in empty[\"metadata\"]\n ):\n empty[\"metadata\"][key] = value\n return empty"}, {"class_start_lineno": 1, "class_end_lineno": 593, "func_start_lineno": 249, "func_end_lineno": 292, "func_code": "def patch_config(\n config: Optional[RunnableConfig],\n *,\n callbacks: Optional[BaseCallbackManager] = None,\n recursion_limit: Optional[int] = None,\n max_concurrency: Optional[int] = None,\n run_name: Optional[str] = None,\n configurable: Optional[dict[str, Any]] = None,\n) -> RunnableConfig:\n \"\"\"Patch a config with new values.\n\n Args:\n config (Optional[RunnableConfig]): The config to patch.\n callbacks (Optional[BaseCallbackManager], optional): The callbacks to set.\n Defaults to None.\n recursion_limit (Optional[int], optional): The recursion limit to set.\n Defaults to None.\n max_concurrency (Optional[int], optional): The max concurrency to set.\n Defaults to None.\n run_name (Optional[str], optional): The run name to set. Defaults to None.\n configurable (Optional[Dict[str, Any]], optional): The configurable to set.\n Defaults to None.\n\n Returns:\n RunnableConfig: The patched config.\n \"\"\"\n config = ensure_config(config)\n if callbacks is not None:\n # If we're replacing callbacks, we need to unset run_name\n # As that should apply only to the same run as the original callbacks\n config[\"callbacks\"] = callbacks\n if \"run_name\" in config:\n del config[\"run_name\"]\n if \"run_id\" in config:\n del config[\"run_id\"]\n if recursion_limit is not None:\n config[\"recursion_limit\"] = recursion_limit\n if max_concurrency is not None:\n config[\"max_concurrency\"] = max_concurrency\n if run_name is not None:\n config[\"run_name\"] = run_name\n if configurable is not None:\n config[\"configurable\"] = {**config.get(\"configurable\", {}), **configurable}\n return config"}, {"class_start_lineno": 1, "class_end_lineno": 191, "func_start_lineno": 125, "func_end_lineno": 145, "func_code": "def parse_json_markdown(\n json_string: str, *, parser: Callable[[str], Any] = parse_partial_json\n) -> dict:\n \"\"\"Parse a JSON string from a Markdown string.\n\n Args:\n json_string: The Markdown string.\n\n Returns:\n The parsed JSON object as a Python dictionary.\n \"\"\"\n try:\n return _parse_json(json_string, parser=parser)\n except json.JSONDecodeError:\n # Try to find JSON string within triple backticks\n match = _json_markdown_re.search(json_string)\n\n # If no match found, assume the entire string is a JSON string\n # Else, use the content within the backticks\n json_str = json_string if match is None else match.group(2)\n return _parse_json(json_str, parser=parser)"}, {"class_start_lineno": 34, "class_end_lineno": 123, "func_start_lineno": 57, "func_end_lineno": 86, "func_code": " def parse_result(self, result: list[Generation], *, partial: bool = False) -> Any:\n \"\"\"Parse the result of an LLM call to a JSON object.\n\n Args:\n result: The result of the LLM call.\n partial: Whether to parse partial JSON objects.\n If True, the output will be a JSON object containing\n all the keys that have been returned so far.\n If False, the output will be the full JSON object.\n Default is False.\n\n Returns:\n The parsed JSON object.\n\n Raises:\n OutputParserException: If the output is not valid JSON.\n \"\"\"\n text = result[0].text\n text = text.strip()\n if partial:\n try:\n return parse_json_markdown(text)\n except JSONDecodeError:\n return None\n else:\n try:\n return parse_json_markdown(text)\n except JSONDecodeError as e:\n msg = f\"Invalid json output: {text}\"\n raise OutputParserException(msg, llm_output=text) from e"}], "type": ["function_empty"], "node": ["langchain_core.runnables.config.ensure_config", "langchain_core.runnables.config.patch_config", "langchain_core.utils.json.parse_json_markdown", "langchain_core.output_parsers.json.JsonOutputParser.parse_result"], "language": "Python", "toolfunc_count": 4, "func_count": 4, "pytest_info": {"total_num": 36, "base_passed_num": 11}} {"id": ["langchain_core.libs.core.langchain_core.utils.json.parse_partial_json", "langchain_core.libs.core.langchain_core.messages.ai.AIMessageChunk::init_tool_calls", "langchain_core.libs.core.langchain_core.utils._merge.merge_lists", "langchain_core.libs.core.langchain_core.utils._merge.merge_dicts"], "project": "langchain_core", "origin_file": ["langchain_core/utils/json.py", "langchain_core/messages/ai.py", "langchain_core/utils/_merge.py", "langchain_core/utils/_merge.py", "langchain_core/runnables/base.py"], "test_list": ["libs/core/tests/unit_tests/output_parsers/test_openai_tools.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 191, "func_start_lineno": 43, "func_end_lineno": 119, "func_code": "def parse_partial_json(s: str, *, strict: bool = False) -> Any:\n \"\"\"Parse a JSON string that may be missing closing braces.\n\n Args:\n s: The JSON string to parse.\n strict: Whether to use strict parsing. Defaults to False.\n\n Returns:\n The parsed JSON object as a Python dictionary.\n \"\"\"\n # Attempt to parse the string as-is.\n try:\n return json.loads(s, strict=strict)\n except json.JSONDecodeError:\n pass\n\n # Initialize variables.\n new_chars = []\n stack = []\n is_inside_string = False\n escaped = False\n\n # Process each character in the string one at a time.\n for char in s:\n if is_inside_string:\n if char == '\"' and not escaped:\n is_inside_string = False\n elif char == \"\\n\" and not escaped:\n char = \"\\\\n\" # Replace the newline character with the escape sequence.\n elif char == \"\\\\\":\n escaped = not escaped\n else:\n escaped = False\n else:\n if char == '\"':\n is_inside_string = True\n escaped = False\n elif char == \"{\":\n stack.append(\"}\")\n elif char == \"[\":\n stack.append(\"]\")\n elif char == \"}\" or char == \"]\":\n if stack and stack[-1] == char:\n stack.pop()\n else:\n # Mismatched closing character; the input is malformed.\n return None\n\n # Append the processed character to the new string.\n new_chars.append(char)\n\n # If we're still inside a string at the end of processing,\n # we need to close the string.\n if is_inside_string:\n if escaped: # Remoe unterminated escape character\n new_chars.pop()\n new_chars.append('\"')\n\n # Reverse the stack to get the closing characters.\n stack.reverse()\n\n # Try to parse mods of string until we succeed or run out of characters.\n while new_chars:\n # Close any remaining open structures in the reverse\n # order that they were opened.\n # Attempt to parse the modified string as JSON.\n try:\n return json.loads(\"\".join(new_chars + stack), strict=strict)\n except json.JSONDecodeError:\n # If we still can't parse the string as JSON,\n # try removing the last character\n new_chars.pop()\n\n # If we got here, we ran out of characters to remove\n # and still couldn't parse the string as JSON, so return the parse error\n # for the original string.\n return json.loads(s, strict=strict)"}, {"class_start_lineno": 296, "class_end_lineno": 403, "func_start_lineno": 328, "func_end_lineno": 394, "func_code": " def init_tool_calls(self) -> Self:\n \"\"\"Initialize tool calls from tool call chunks.\n\n Args:\n values: The values to validate.\n\n Returns:\n The values with tool calls initialized.\n\n Raises:\n ValueError: If the tool call chunks are malformed.\n \"\"\"\n if not self.tool_call_chunks:\n if self.tool_calls:\n self.tool_call_chunks = [\n create_tool_call_chunk(\n name=tc[\"name\"],\n args=json.dumps(tc[\"args\"]),\n id=tc[\"id\"],\n index=None,\n )\n for tc in self.tool_calls\n ]\n if self.invalid_tool_calls:\n tool_call_chunks = self.tool_call_chunks\n tool_call_chunks.extend(\n [\n create_tool_call_chunk(\n name=tc[\"name\"], args=tc[\"args\"], id=tc[\"id\"], index=None\n )\n for tc in self.invalid_tool_calls\n ]\n )\n self.tool_call_chunks = tool_call_chunks\n\n return self\n tool_calls = []\n invalid_tool_calls = []\n\n def add_chunk_to_invalid_tool_calls(chunk: ToolCallChunk) -> None:\n invalid_tool_calls.append(\n create_invalid_tool_call(\n name=chunk[\"name\"],\n args=chunk[\"args\"],\n id=chunk[\"id\"],\n error=None,\n )\n )\n\n for chunk in self.tool_call_chunks:\n try:\n args_ = parse_partial_json(chunk[\"args\"]) if chunk[\"args\"] != \"\" else {} # type: ignore[arg-type]\n if isinstance(args_, dict):\n tool_calls.append(\n create_tool_call(\n name=chunk[\"name\"] or \"\",\n args=args_,\n id=chunk[\"id\"],\n )\n )\n else:\n add_chunk_to_invalid_tool_calls(chunk)\n except Exception:\n add_chunk_to_invalid_tool_calls(chunk)\n self.tool_calls = tool_calls\n self.invalid_tool_calls = invalid_tool_calls\n return self"}, {"class_start_lineno": 1, "class_end_lineno": 148, "func_start_lineno": 72, "func_end_lineno": 106, "func_code": "def merge_lists(left: Optional[list], *others: Optional[list]) -> Optional[list]:\n \"\"\"Add many lists, handling None.\n\n Args:\n left: The first list to merge.\n others: The other lists to merge.\n\n Returns:\n The merged list.\n \"\"\"\n merged = left.copy() if left is not None else None\n for other in others:\n if other is None:\n continue\n elif merged is None:\n merged = other.copy()\n else:\n for e in other:\n if isinstance(e, dict) and \"index\" in e and isinstance(e[\"index\"], int):\n to_merge = [\n i\n for i, e_left in enumerate(merged)\n if e_left[\"index\"] == e[\"index\"]\n ]\n if to_merge:\n # TODO: Remove this once merge_dict is updated with special\n # handling for 'type'.\n if \"type\" in e:\n e = {k: v for k, v in e.items() if k != \"type\"}\n merged[to_merge[0]] = merge_dicts(merged[to_merge[0]], e)\n else:\n merged.append(e)\n else:\n merged.append(e)\n return merged"}, {"class_start_lineno": 1, "class_end_lineno": 148, "func_start_lineno": 6, "func_end_lineno": 69, "func_code": "def merge_dicts(left: dict[str, Any], *others: dict[str, Any]) -> dict[str, Any]:\n \"\"\"Merge many dicts, handling specific scenarios where a key exists in both\n dictionaries but has a value of None in 'left'. In such cases, the method uses the\n value from 'right' for that key in the merged dictionary.\n\n Args:\n left: The first dictionary to merge.\n others: The other dictionaries to merge.\n\n Returns:\n The merged dictionary.\n\n Raises:\n TypeError: If the key exists in both dictionaries but has a different type.\n TypeError: If the value has an unsupported type.\n\n Example:\n If left = {\"function_call\": {\"arguments\": None}} and\n right = {\"function_call\": {\"arguments\": \"{\\n\"}}\n then, after merging, for the key \"function_call\",\n the value from 'right' is used,\n resulting in merged = {\"function_call\": {\"arguments\": \"{\\n\"}}.\n \"\"\"\n merged = left.copy()\n for right in others:\n for right_k, right_v in right.items():\n if right_k not in merged or right_v is not None and merged[right_k] is None:\n merged[right_k] = right_v\n elif right_v is None:\n continue\n elif type(merged[right_k]) is not type(right_v):\n msg = (\n f'additional_kwargs[\"{right_k}\"] already exists in this message,'\n \" but with a different type.\"\n )\n raise TypeError(msg)\n elif isinstance(merged[right_k], str):\n # TODO: Add below special handling for 'type' key in 0.3 and remove\n # merge_lists 'type' logic.\n #\n # if right_k == \"type\":\n # if merged[right_k] == right_v:\n # continue\n # else:\n # raise ValueError(\n # \"Unable to merge. Two different values seen for special \"\n # f\"key 'type': {merged[right_k]} and {right_v}. 'type' \"\n # \"should either occur once or have the same value across \"\n # \"all dicts.\"\n # )\n merged[right_k] += right_v\n elif isinstance(merged[right_k], dict):\n merged[right_k] = merge_dicts(merged[right_k], right_v)\n elif isinstance(merged[right_k], list):\n merged[right_k] = merge_lists(merged[right_k], right_v)\n elif merged[right_k] == right_v:\n continue\n else:\n msg = (\n f\"Additional kwargs key {right_k} already exists in left dict and \"\n f\"value has unsupported type {type(merged[right_k])}.\"\n )\n raise TypeError(msg)\n return merged"}, {"class_start_lineno": 2659, "class_end_lineno": 3435, "func_start_lineno": 3403, "func_end_lineno": 3409, "func_code": " def stream(\n self,\n input: Input,\n config: Optional[RunnableConfig] = None,\n **kwargs: Optional[Any],\n ) -> Iterator[Output]:\n yield from self.transform(iter([input]), config, **kwargs)"}], "type": ["function_empty"], "node": ["langchain_core.utils.json.parse_partial_json", "langchain_core.messages.ai.AIMessageChunk.init_tool_calls", "langchain_core.utils._merge.merge_lists", "langchain_core.utils._merge.merge_dicts", "langchain_core.runnables.base.RunnableSequence.stream"], "language": "Python", "toolfunc_count": 4, "func_count": 4, "pytest_info": {"total_num": 11, "base_passed_num": 2}} {"id": ["langchain_core.libs.core.langchain_core.utils.formatting.StrictFormatter::validate_input_variables", "langchain_core.libs.core.langchain_core.prompts.string.check_valid_template"], "project": "langchain_core", "origin_file": ["langchain_core/utils/formatting.py", "langchain_core/prompts/string.py", "langchain_core/prompts/few_shot.py"], "test_list": ["libs/core/tests/unit_tests/prompts/test_few_shot.py"], "prob_info": [{"class_start_lineno": 8, "class_end_lineno": 48, "func_start_lineno": 35, "func_end_lineno": 48, "func_code": " def validate_input_variables(\n self, format_string: str, input_variables: list[str]\n ) -> None:\n \"\"\"Check that all input variables are used in the format string.\n\n Args:\n format_string: The format string.\n input_variables: The input variables.\n\n Raises:\n ValueError: If any input variables are not used in the format string.\n \"\"\"\n dummy_inputs = dict.fromkeys(input_variables, \"foo\")\n super().format(format_string, **dummy_inputs)"}, {"class_start_lineno": 1, "class_end_lineno": 319, "func_start_lineno": 207, "func_end_lineno": 236, "func_code": "def check_valid_template(\n template: str, template_format: str, input_variables: list[str]\n) -> None:\n \"\"\"Check that template string is valid.\n\n Args:\n template: The template string.\n template_format: The template format. Should be one of \"f-string\" or \"jinja2\".\n input_variables: The input variables.\n\n Raises:\n ValueError: If the template format is not supported.\n ValueError: If the prompt schema is invalid.\n \"\"\"\n try:\n validator_func = DEFAULT_VALIDATOR_MAPPING[template_format]\n except KeyError as exc:\n msg = (\n f\"Invalid template format {template_format!r}, should be one of\"\n f\" {list(DEFAULT_FORMATTER_MAPPING)}.\"\n )\n raise ValueError(msg) from exc\n try:\n validator_func(template, input_variables)\n except (KeyError, IndexError) as exc:\n msg = (\n \"Invalid prompt schema; check for mismatched or missing input parameters\"\n f\" from {input_variables}.\"\n )\n raise ValueError(msg) from exc"}, {"class_start_lineno": 115, "class_end_lineno": 244, "func_start_lineno": 148, "func_end_lineno": 164, "func_code": " def template_is_valid(self) -> Self:\n \"\"\"Check that prefix, suffix, and input variables are consistent.\"\"\"\n if self.validate_template:\n check_valid_template(\n self.prefix + self.suffix,\n self.template_format,\n self.input_variables + list(self.partial_variables),\n )\n elif self.template_format or None:\n self.input_variables = [\n var\n for var in get_template_variables(\n self.prefix + self.suffix, self.template_format\n )\n if var not in self.partial_variables\n ]\n return self"}], "type": ["function_empty"], "node": ["langchain_core.utils.formatting.StrictFormatter.validate_input_variables", "langchain_core.prompts.string.check_valid_template", "langchain_core.prompts.few_shot.FewShotPromptTemplate.template_is_valid"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 16, "base_passed_num": 13}} {"id": ["langchain_core.libs.core.langchain_core.prompts.loading.load_prompt_from_config", "langchain_core.libs.core.langchain_core.prompts.loading.load_prompt"], "project": "langchain_core", "origin_file": ["langchain_core/prompts/loading.py", "langchain_core/prompts/loading.py", "langchain_core/prompts/loading.py"], "test_list": ["libs/core/tests/unit_tests/prompts/test_loading.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 203, "func_start_lineno": 20, "func_end_lineno": 41, "func_code": "def load_prompt_from_config(config: dict) -> BasePromptTemplate:\n \"\"\"Load prompt from Config Dict.\n\n Args:\n config: Dict containing the prompt configuration.\n\n Returns:\n A PromptTemplate object.\n\n Raises:\n ValueError: If the prompt type is not supported.\n \"\"\"\n if \"_type\" not in config:\n logger.warning(\"No `_type` key found, defaulting to `prompt`.\")\n config_type = config.pop(\"_type\", \"prompt\")\n\n if config_type not in type_to_loader_dict:\n msg = f\"Loading {config_type} prompt not supported\"\n raise ValueError(msg)\n\n prompt_loader = type_to_loader_dict[config_type]\n return prompt_loader(config)"}, {"class_start_lineno": 1, "class_end_lineno": 203, "func_start_lineno": 141, "func_end_lineno": 163, "func_code": "def load_prompt(\n path: Union[str, Path], encoding: Optional[str] = None\n) -> BasePromptTemplate:\n \"\"\"Unified method for loading a prompt from LangChainHub or local fs.\n\n Args:\n path: Path to the prompt file.\n encoding: Encoding of the file. Defaults to None.\n\n Returns:\n A PromptTemplate object.\n\n Raises:\n RuntimeError: If the path is a Lang Chain Hub path.\n \"\"\"\n if isinstance(path, str) and path.startswith(\"lc://\"):\n msg = (\n \"Loading from the deprecated github-based Hub is no longer supported. \"\n \"Please use the new LangChain Hub at https://smith.langchain.com/hub \"\n \"instead.\"\n )\n raise RuntimeError(msg)\n return _load_prompt_from_file(path, encoding)"}, {"class_start_lineno": 1, "class_end_lineno": 203, "func_start_lineno": 99, "func_end_lineno": 118, "func_code": "def _load_few_shot_prompt(config: dict) -> FewShotPromptTemplate:\n \"\"\"Load the \"few shot\" prompt from the config.\"\"\"\n # Load the suffix and prefix templates.\n config = _load_template(\"suffix\", config)\n config = _load_template(\"prefix\", config)\n # Load the example prompt.\n if \"example_prompt_path\" in config:\n if \"example_prompt\" in config:\n msg = (\n \"Only one of example_prompt and example_prompt_path should \"\n \"be specified.\"\n )\n raise ValueError(msg)\n config[\"example_prompt\"] = load_prompt(config.pop(\"example_prompt_path\"))\n else:\n config[\"example_prompt\"] = load_prompt_from_config(config[\"example_prompt\"])\n # Load the examples.\n config = _load_examples(config)\n config = _load_output_parser(config)\n return FewShotPromptTemplate(**config)"}], "type": ["function_empty"], "node": ["langchain_core.prompts.loading.load_prompt_from_config", "langchain_core.prompts.loading.load_prompt", "langchain_core.prompts.loading._load_few_shot_prompt"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 10, "base_passed_num": 0}} {"id": ["langchain_core.libs.core.langchain_core.runnables.base.RunnableLambda::deps", "langchain_core.libs.core.langchain_core.beta.runnables.context.config_with_context", "langchain_core.libs.core.langchain_core.runnables.config.ensure_config", "langchain_core.libs.core.langchain_core.runnables.config.patch_config"], "project": "langchain_core", "origin_file": ["langchain_core/runnables/base.py", "langchain_core/runnables/base.py", "langchain_core/beta/runnables/context.py", "langchain_core/runnables/config.py", "langchain_core/runnables/config.py"], "test_list": ["libs/core/tests/unit_tests/prompts/test_structured.py"], "prob_info": [{"class_start_lineno": 4230, "class_end_lineno": 4967, "func_start_lineno": 4471, "func_end_lineno": 4491, "func_code": " def deps(self) -> list[Runnable]:\n \"\"\"The dependencies of this Runnable.\n\n Returns:\n The dependencies of this Runnable. If the function has nonlocal\n variables that are Runnables, they are considered dependencies.\n \"\"\"\n if hasattr(self, \"func\"):\n objects = get_function_nonlocals(self.func)\n elif hasattr(self, \"afunc\"):\n objects = get_function_nonlocals(self.afunc)\n else:\n objects = []\n\n deps: list[Runnable] = []\n for obj in objects:\n if isinstance(obj, Runnable):\n deps.append(obj)\n elif isinstance(getattr(obj, \"__self__\", None), Runnable):\n deps.append(obj.__self__)\n return deps"}, {"class_start_lineno": 4230, "class_end_lineno": 4967, "func_start_lineno": 4494, "func_end_lineno": 4497, "func_code": " def config_specs(self) -> list[ConfigurableFieldSpec]:\n return get_unique_config_specs(\n spec for dep in self.deps for spec in dep.config_specs\n )"}, {"class_start_lineno": 1, "class_end_lineno": 401, "func_start_lineno": 140, "func_end_lineno": 153, "func_code": "def config_with_context(\n config: RunnableConfig,\n steps: list[Runnable],\n) -> RunnableConfig:\n \"\"\"Patch a runnable config with context getters and setters.\n\n Args:\n config: The runnable config.\n steps: The runnable steps.\n\n Returns:\n The patched runnable config.\n \"\"\"\n return _config_with_context(config, steps, _setter, _getter, threading.Event)"}, {"class_start_lineno": 1, "class_end_lineno": 593, "func_start_lineno": 149, "func_end_lineno": 199, "func_code": "def ensure_config(config: Optional[RunnableConfig] = None) -> RunnableConfig:\n \"\"\"Ensure that a config is a dict with all keys present.\n\n Args:\n config (Optional[RunnableConfig], optional): The config to ensure.\n Defaults to None.\n\n Returns:\n RunnableConfig: The ensured config.\n \"\"\"\n empty = RunnableConfig(\n tags=[],\n metadata={},\n callbacks=None,\n recursion_limit=DEFAULT_RECURSION_LIMIT,\n configurable={},\n )\n if var_config := var_child_runnable_config.get():\n empty.update(\n cast(\n RunnableConfig,\n {\n k: v.copy() if k in COPIABLE_KEYS else v # type: ignore[attr-defined]\n for k, v in var_config.items()\n if v is not None\n },\n )\n )\n if config is not None:\n empty.update(\n cast(\n RunnableConfig,\n {\n k: v.copy() if k in COPIABLE_KEYS else v # type: ignore[attr-defined]\n for k, v in config.items()\n if v is not None and k in CONFIG_KEYS\n },\n )\n )\n if config is not None:\n for k, v in config.items():\n if k not in CONFIG_KEYS and v is not None:\n empty[\"configurable\"][k] = v\n for key, value in empty.get(\"configurable\", {}).items():\n if (\n not key.startswith(\"__\")\n and isinstance(value, (str, int, float, bool))\n and key not in empty[\"metadata\"]\n ):\n empty[\"metadata\"][key] = value\n return empty"}, {"class_start_lineno": 1, "class_end_lineno": 593, "func_start_lineno": 249, "func_end_lineno": 292, "func_code": "def patch_config(\n config: Optional[RunnableConfig],\n *,\n callbacks: Optional[BaseCallbackManager] = None,\n recursion_limit: Optional[int] = None,\n max_concurrency: Optional[int] = None,\n run_name: Optional[str] = None,\n configurable: Optional[dict[str, Any]] = None,\n) -> RunnableConfig:\n \"\"\"Patch a config with new values.\n\n Args:\n config (Optional[RunnableConfig]): The config to patch.\n callbacks (Optional[BaseCallbackManager], optional): The callbacks to set.\n Defaults to None.\n recursion_limit (Optional[int], optional): The recursion limit to set.\n Defaults to None.\n max_concurrency (Optional[int], optional): The max concurrency to set.\n Defaults to None.\n run_name (Optional[str], optional): The run name to set. Defaults to None.\n configurable (Optional[Dict[str, Any]], optional): The configurable to set.\n Defaults to None.\n\n Returns:\n RunnableConfig: The patched config.\n \"\"\"\n config = ensure_config(config)\n if callbacks is not None:\n # If we're replacing callbacks, we need to unset run_name\n # As that should apply only to the same run as the original callbacks\n config[\"callbacks\"] = callbacks\n if \"run_name\" in config:\n del config[\"run_name\"]\n if \"run_id\" in config:\n del config[\"run_id\"]\n if recursion_limit is not None:\n config[\"recursion_limit\"] = recursion_limit\n if max_concurrency is not None:\n config[\"max_concurrency\"] = max_concurrency\n if run_name is not None:\n config[\"run_name\"] = run_name\n if configurable is not None:\n config[\"configurable\"] = {**config.get(\"configurable\", {}), **configurable}\n return config"}], "type": ["function_empty"], "node": ["langchain_core.runnables.base.RunnableLambda.deps", "langchain_core.runnables.base.RunnableLambda.config_specs", "langchain_core.beta.runnables.context.config_with_context", "langchain_core.runnables.config.ensure_config", "langchain_core.runnables.config.patch_config"], "language": "Python", "toolfunc_count": 4, "func_count": 4, "pytest_info": {"total_num": 4, "base_passed_num": 0}} {"id": ["langchain_core.libs.core.langchain_core.runnables.config.ensure_config", "langchain_core.libs.core.langchain_core.runnables.config.patch_config", "langchain_core.libs.core.langchain_core.callbacks.manager.handle_event", "langchain_core.libs.core.langchain_core.callbacks.manager.CallbackManagerForChainRun::on_chain_end"], "project": "langchain_core", "origin_file": ["langchain_core/runnables/config.py", "langchain_core/runnables/config.py", "langchain_core/callbacks/manager.py", "langchain_core/callbacks/manager.py"], "test_list": ["libs/core/tests/unit_tests/runnables/test_context.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 593, "func_start_lineno": 149, "func_end_lineno": 199, "func_code": "def ensure_config(config: Optional[RunnableConfig] = None) -> RunnableConfig:\n \"\"\"Ensure that a config is a dict with all keys present.\n\n Args:\n config (Optional[RunnableConfig], optional): The config to ensure.\n Defaults to None.\n\n Returns:\n RunnableConfig: The ensured config.\n \"\"\"\n empty = RunnableConfig(\n tags=[],\n metadata={},\n callbacks=None,\n recursion_limit=DEFAULT_RECURSION_LIMIT,\n configurable={},\n )\n if var_config := var_child_runnable_config.get():\n empty.update(\n cast(\n RunnableConfig,\n {\n k: v.copy() if k in COPIABLE_KEYS else v # type: ignore[attr-defined]\n for k, v in var_config.items()\n if v is not None\n },\n )\n )\n if config is not None:\n empty.update(\n cast(\n RunnableConfig,\n {\n k: v.copy() if k in COPIABLE_KEYS else v # type: ignore[attr-defined]\n for k, v in config.items()\n if v is not None and k in CONFIG_KEYS\n },\n )\n )\n if config is not None:\n for k, v in config.items():\n if k not in CONFIG_KEYS and v is not None:\n empty[\"configurable\"][k] = v\n for key, value in empty.get(\"configurable\", {}).items():\n if (\n not key.startswith(\"__\")\n and isinstance(value, (str, int, float, bool))\n and key not in empty[\"metadata\"]\n ):\n empty[\"metadata\"][key] = value\n return empty"}, {"class_start_lineno": 1, "class_end_lineno": 593, "func_start_lineno": 249, "func_end_lineno": 292, "func_code": "def patch_config(\n config: Optional[RunnableConfig],\n *,\n callbacks: Optional[BaseCallbackManager] = None,\n recursion_limit: Optional[int] = None,\n max_concurrency: Optional[int] = None,\n run_name: Optional[str] = None,\n configurable: Optional[dict[str, Any]] = None,\n) -> RunnableConfig:\n \"\"\"Patch a config with new values.\n\n Args:\n config (Optional[RunnableConfig]): The config to patch.\n callbacks (Optional[BaseCallbackManager], optional): The callbacks to set.\n Defaults to None.\n recursion_limit (Optional[int], optional): The recursion limit to set.\n Defaults to None.\n max_concurrency (Optional[int], optional): The max concurrency to set.\n Defaults to None.\n run_name (Optional[str], optional): The run name to set. Defaults to None.\n configurable (Optional[Dict[str, Any]], optional): The configurable to set.\n Defaults to None.\n\n Returns:\n RunnableConfig: The patched config.\n \"\"\"\n config = ensure_config(config)\n if callbacks is not None:\n # If we're replacing callbacks, we need to unset run_name\n # As that should apply only to the same run as the original callbacks\n config[\"callbacks\"] = callbacks\n if \"run_name\" in config:\n del config[\"run_name\"]\n if \"run_id\" in config:\n del config[\"run_id\"]\n if recursion_limit is not None:\n config[\"recursion_limit\"] = recursion_limit\n if max_concurrency is not None:\n config[\"max_concurrency\"] = max_concurrency\n if run_name is not None:\n config[\"run_name\"] = run_name\n if configurable is not None:\n config[\"configurable\"] = {**config.get(\"configurable\", {}), **configurable}\n return config"}, {"class_start_lineno": 1, "class_end_lineno": 2606, "func_start_lineno": 236, "func_end_lineno": 312, "func_code": "def handle_event(\n handlers: list[BaseCallbackHandler],\n event_name: str,\n ignore_condition_name: Optional[str],\n *args: Any,\n **kwargs: Any,\n) -> None:\n \"\"\"Generic event handler for CallbackManager.\n\n Note: This function is used by LangServe to handle events.\n\n Args:\n handlers: The list of handlers that will handle the event.\n event_name: The name of the event (e.g., \"on_llm_start\").\n ignore_condition_name: Name of the attribute defined on handler\n that if True will cause the handler to be skipped for the given event.\n *args: The arguments to pass to the event handler.\n **kwargs: The keyword arguments to pass to the event handler\n \"\"\"\n coros: list[Coroutine[Any, Any, Any]] = []\n\n try:\n message_strings: Optional[list[str]] = None\n for handler in handlers:\n try:\n if ignore_condition_name is None or not getattr(\n handler, ignore_condition_name\n ):\n event = getattr(handler, event_name)(*args, **kwargs)\n if asyncio.iscoroutine(event):\n coros.append(event)\n except NotImplementedError as e:\n if event_name == \"on_chat_model_start\":\n if message_strings is None:\n message_strings = [get_buffer_string(m) for m in args[1]]\n handle_event(\n [handler],\n \"on_llm_start\",\n \"ignore_llm\",\n args[0],\n message_strings,\n *args[2:],\n **kwargs,\n )\n else:\n handler_name = handler.__class__.__name__\n logger.warning(\n f\"NotImplementedError in {handler_name}.{event_name}\"\n f\" callback: {repr(e)}\"\n )\n except Exception as e:\n logger.warning(\n f\"Error in {handler.__class__.__name__}.{event_name} callback:\"\n f\" {repr(e)}\"\n )\n if handler.raise_error:\n raise\n finally:\n if coros:\n try:\n # Raises RuntimeError if there is no current event loop.\n asyncio.get_running_loop()\n loop_running = True\n except RuntimeError:\n loop_running = False\n\n if loop_running:\n # If we try to submit this coroutine to the running loop\n # we end up in a deadlock, as we'd have gotten here from a\n # running coroutine, which we cannot interrupt to run this one.\n # The solution is to create a new loop in a new thread.\n with ThreadPoolExecutor(1) as executor:\n executor.submit(\n cast(Callable, copy_context().run), _run_coros, coros\n ).result()\n else:\n _run_coros(coros)"}, {"class_start_lineno": 817, "class_end_lineno": 900, "func_start_lineno": 820, "func_end_lineno": 836, "func_code": " def on_chain_end(self, outputs: Union[dict[str, Any], Any], **kwargs: Any) -> None:\n \"\"\"Run when chain ends running.\n\n Args:\n outputs (Union[Dict[str, Any], Any]): The outputs of the chain.\n **kwargs (Any): Additional keyword arguments.\n \"\"\"\n handle_event(\n self.handlers,\n \"on_chain_end\",\n \"ignore_chain\",\n outputs,\n run_id=self.run_id,\n parent_run_id=self.parent_run_id,\n tags=self.tags,\n **kwargs,\n )"}], "type": ["function_empty"], "node": ["langchain_core.runnables.config.ensure_config", "langchain_core.runnables.config.patch_config", "langchain_core.callbacks.manager.handle_event", "langchain_core.callbacks.manager.CallbackManagerForChainRun.on_chain_end"], "language": "Python", "toolfunc_count": 4, "func_count": 4, "pytest_info": {"total_num": 27, "base_passed_num": 0}} {"id": ["langchain_core.libs.core.langchain_core.runnables.config.ensure_config", "langchain_core.libs.core.langchain_core.runnables.config.patch_config", "langchain_core.libs.core.langchain_core.globals.get_llm_cache", "langchain_core.libs.core.langchain_core.language_models.llms.get_prompts"], "project": "langchain_core", "origin_file": ["langchain_core/runnables/config.py", "langchain_core/runnables/config.py", "langchain_core/globals.py", "langchain_core/language_models/llms.py"], "test_list": ["libs/core/tests/unit_tests/runnables/test_fallbacks.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 593, "func_start_lineno": 149, "func_end_lineno": 199, "func_code": "def ensure_config(config: Optional[RunnableConfig] = None) -> RunnableConfig:\n \"\"\"Ensure that a config is a dict with all keys present.\n\n Args:\n config (Optional[RunnableConfig], optional): The config to ensure.\n Defaults to None.\n\n Returns:\n RunnableConfig: The ensured config.\n \"\"\"\n empty = RunnableConfig(\n tags=[],\n metadata={},\n callbacks=None,\n recursion_limit=DEFAULT_RECURSION_LIMIT,\n configurable={},\n )\n if var_config := var_child_runnable_config.get():\n empty.update(\n cast(\n RunnableConfig,\n {\n k: v.copy() if k in COPIABLE_KEYS else v # type: ignore[attr-defined]\n for k, v in var_config.items()\n if v is not None\n },\n )\n )\n if config is not None:\n empty.update(\n cast(\n RunnableConfig,\n {\n k: v.copy() if k in COPIABLE_KEYS else v # type: ignore[attr-defined]\n for k, v in config.items()\n if v is not None and k in CONFIG_KEYS\n },\n )\n )\n if config is not None:\n for k, v in config.items():\n if k not in CONFIG_KEYS and v is not None:\n empty[\"configurable\"][k] = v\n for key, value in empty.get(\"configurable\", {}).items():\n if (\n not key.startswith(\"__\")\n and isinstance(value, (str, int, float, bool))\n and key not in empty[\"metadata\"]\n ):\n empty[\"metadata\"][key] = value\n return empty"}, {"class_start_lineno": 1, "class_end_lineno": 593, "func_start_lineno": 249, "func_end_lineno": 292, "func_code": "def patch_config(\n config: Optional[RunnableConfig],\n *,\n callbacks: Optional[BaseCallbackManager] = None,\n recursion_limit: Optional[int] = None,\n max_concurrency: Optional[int] = None,\n run_name: Optional[str] = None,\n configurable: Optional[dict[str, Any]] = None,\n) -> RunnableConfig:\n \"\"\"Patch a config with new values.\n\n Args:\n config (Optional[RunnableConfig]): The config to patch.\n callbacks (Optional[BaseCallbackManager], optional): The callbacks to set.\n Defaults to None.\n recursion_limit (Optional[int], optional): The recursion limit to set.\n Defaults to None.\n max_concurrency (Optional[int], optional): The max concurrency to set.\n Defaults to None.\n run_name (Optional[str], optional): The run name to set. Defaults to None.\n configurable (Optional[Dict[str, Any]], optional): The configurable to set.\n Defaults to None.\n\n Returns:\n RunnableConfig: The patched config.\n \"\"\"\n config = ensure_config(config)\n if callbacks is not None:\n # If we're replacing callbacks, we need to unset run_name\n # As that should apply only to the same run as the original callbacks\n config[\"callbacks\"] = callbacks\n if \"run_name\" in config:\n del config[\"run_name\"]\n if \"run_id\" in config:\n del config[\"run_id\"]\n if recursion_limit is not None:\n config[\"recursion_limit\"] = recursion_limit\n if max_concurrency is not None:\n config[\"max_concurrency\"] = max_concurrency\n if run_name is not None:\n config[\"run_name\"] = run_name\n if configurable is not None:\n config[\"configurable\"] = {**config.get(\"configurable\", {}), **configurable}\n return config"}, {"class_start_lineno": 1, "class_end_lineno": 222, "func_start_lineno": 186, "func_end_lineno": 222, "func_code": "def get_llm_cache() -> \"BaseCache\":\n \"\"\"Get the value of the `llm_cache` global setting.\n\n Returns:\n The value of the `llm_cache` global setting.\n \"\"\"\n try:\n import langchain # type: ignore[import]\n\n # We're about to run some deprecated code, don't report warnings from it.\n # The user called the correct (non-deprecated) code path and shouldn't get warnings.\n with warnings.catch_warnings():\n warnings.filterwarnings(\n \"ignore\",\n message=(\n \"Importing llm_cache from langchain root module is no longer supported\"\n ),\n )\n # N.B.: This is a workaround for an unfortunate quirk of Python's\n # module-level `__getattr__()` implementation:\n # https://github.com/langchain-ai/langchain/pull/11311#issuecomment-1743780004\n #\n # Remove it once `langchain.llm_cache` is no longer supported, and\n # once all users have migrated to using `set_llm_cache()` here.\n #\n # In the meantime, the `llm_cache` setting returns whichever of\n # its two backing sources is truthy (not `None` and non-empty),\n # or the old value if both are falsy. This accommodates users\n # who haven't migrated to using `set_llm_cache()` yet.\n # Those users are getting deprecation warnings directing them\n # to use `set_llm_cache()` when they import `langchain.llm_cache`.\n old_llm_cache = langchain.llm_cache\n except ImportError:\n old_llm_cache = None\n\n global _llm_cache\n return _llm_cache or old_llm_cache"}, {"class_start_lineno": 1, "class_end_lineno": 1547, "func_start_lineno": 151, "func_end_lineno": 184, "func_code": "def get_prompts(\n params: dict[str, Any],\n prompts: list[str],\n cache: Optional[Union[BaseCache, bool, None]] = None,\n) -> tuple[dict[int, list], str, list[int], list[str]]:\n \"\"\"Get prompts that are already cached.\n\n Args:\n params: Dictionary of parameters.\n prompts: List of prompts.\n cache: Cache object. Default is None.\n\n Returns:\n A tuple of existing prompts, llm_string, missing prompt indexes,\n and missing prompts.\n\n Raises:\n ValueError: If the cache is not set and cache is True.\n \"\"\"\n llm_string = str(sorted(params.items()))\n missing_prompts = []\n missing_prompt_idxs = []\n existing_prompts = {}\n\n llm_cache = _resolve_cache(cache)\n for i, prompt in enumerate(prompts):\n if llm_cache:\n cache_val = llm_cache.lookup(prompt, llm_string)\n if isinstance(cache_val, list):\n existing_prompts[i] = cache_val\n else:\n missing_prompts.append(prompt)\n missing_prompt_idxs.append(i)\n return existing_prompts, llm_string, missing_prompt_idxs, missing_prompts"}], "type": ["function_empty"], "node": ["langchain_core.runnables.config.ensure_config", "langchain_core.runnables.config.patch_config", "langchain_core.globals.get_llm_cache", "langchain_core.language_models.llms.get_prompts"], "language": "Python", "toolfunc_count": 4, "func_count": 4, "pytest_info": {"total_num": 16, "base_passed_num": 2}} {"id": ["langchain_core.libs.core.langchain_core.runnables.graph.is_uuid", "langchain_core.libs.core.langchain_core.runnables.graph.node_data_str", "langchain_core.libs.core.langchain_core.runnables.graph.Graph::add_node", "langchain_core.libs.core.langchain_core.runnables.graph_ascii.AsciiCanvas::point", "langchain_core.libs.core.langchain_core.runnables.graph_ascii.AsciiCanvas::line"], "project": "langchain_core", "origin_file": ["langchain_core/runnables/graph.py", "langchain_core/runnables/graph.py", "langchain_core/runnables/graph.py", "langchain_core/runnables/graph_ascii.py", "langchain_core/runnables/graph_ascii.py"], "test_list": ["libs/core/tests/unit_tests/runnables/test_graph.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 664, "func_start_lineno": 42, "func_end_lineno": 55, "func_code": "def is_uuid(value: str) -> bool:\n \"\"\"Check if a string is a valid UUID.\n\n Args:\n value: The string to check.\n\n Returns:\n True if the string is a valid UUID, False otherwise.\n \"\"\"\n try:\n UUID(value)\n except ValueError:\n return False\n return True"}, {"class_start_lineno": 1, "class_end_lineno": 664, "func_start_lineno": 178, "func_end_lineno": 196, "func_code": "def node_data_str(id: str, data: Union[type[BaseModel], RunnableType]) -> str:\n \"\"\"Convert the data of a node to a string.\n\n Args:\n id: The node id.\n data: The node data.\n\n Returns:\n A string representation of the data.\n \"\"\"\n from langchain_core.runnables.base import Runnable\n\n if not is_uuid(id):\n return id\n elif isinstance(data, Runnable):\n data_str = data.get_name()\n else:\n data_str = data.__name__\n return data_str if not data_str.startswith(\"Runnable\") else data_str[8:]"}, {"class_start_lineno": 256, "class_end_lineno": 636, "func_start_lineno": 313, "func_end_lineno": 339, "func_code": " def add_node(\n self,\n data: Union[type[BaseModel], RunnableType],\n id: Optional[str] = None,\n *,\n metadata: Optional[dict[str, Any]] = None,\n ) -> Node:\n \"\"\"Add a node to the graph and return it.\n\n Args:\n data: The data of the node.\n id: The id of the node. Defaults to None.\n metadata: Optional metadata for the node. Defaults to None.\n\n Returns:\n The node that was added to the graph.\n\n Raises:\n ValueError: If a node with the same id already exists.\n \"\"\"\n if id is not None and id in self.nodes:\n msg = f\"Node with id {id} already exists\"\n raise ValueError(msg)\n id = id or self.next_id()\n node = Node(id=id, data=data, metadata=metadata, name=node_data_str(id, data))\n self.nodes[node.id] = node\n return node"}, {"class_start_lineno": 39, "class_end_lineno": 157, "func_start_lineno": 64, "func_end_lineno": 85, "func_code": " def point(self, x: int, y: int, char: str) -> None:\n \"\"\"Create a point on ASCII canvas.\n\n Args:\n x (int): x coordinate. Should be >= 0 and < number of columns in\n the canvas.\n y (int): y coordinate. Should be >= 0 an < number of lines in the\n canvas.\n char (str): character to place in the specified point on the\n canvas.\n \"\"\"\n if len(char) != 1:\n msg = \"char should be a single character\"\n raise ValueError(msg)\n if x >= self.cols or x < 0:\n msg = \"x should be >= 0 and < number of columns\"\n raise ValueError(msg)\n if y >= self.lines or y < 0:\n msg = \"y should be >= 0 and < number of lines\"\n raise ValueError(msg)\n\n self.canvas[y][x] = char"}, {"class_start_lineno": 39, "class_end_lineno": 157, "func_start_lineno": 87, "func_end_lineno": 117, "func_code": " def line(self, x0: int, y0: int, x1: int, y1: int, char: str) -> None:\n \"\"\"Create a line on ASCII canvas.\n\n Args:\n x0 (int): x coordinate where the line should start.\n y0 (int): y coordinate where the line should start.\n x1 (int): x coordinate where the line should end.\n y1 (int): y coordinate where the line should end.\n char (str): character to draw the line with.\n \"\"\"\n if x0 > x1:\n x1, x0 = x0, x1\n y1, y0 = y0, y1\n\n dx = x1 - x0\n dy = y1 - y0\n\n if dx == 0 and dy == 0:\n self.point(x0, y0, char)\n elif abs(dx) >= abs(dy):\n for x in range(x0, x1 + 1):\n y = y0 if dx == 0 else y0 + int(round((x - x0) * dy / float(dx)))\n self.point(x, y, char)\n elif y0 < y1:\n for y in range(y0, y1 + 1):\n x = x0 if dy == 0 else x0 + int(round((y - y0) * dx / float(dy)))\n self.point(x, y, char)\n else:\n for y in range(y1, y0 + 1):\n x = x0 if dy == 0 else x1 + int(round((y - y1) * dx / float(dy)))\n self.point(x, y, char)"}], "type": ["function_empty"], "node": ["langchain_core.runnables.graph.is_uuid", "langchain_core.runnables.graph.node_data_str", "langchain_core.runnables.graph.Graph.add_node", "langchain_core.runnables.graph_ascii.AsciiCanvas.point", "langchain_core.runnables.graph_ascii.AsciiCanvas.line"], "language": "Python", "toolfunc_count": 5, "func_count": 5, "pytest_info": {"total_num": 11, "base_passed_num": 3}} {"id": ["langchain_core.libs.core.langchain_core.runnables.config.ensure_config", "langchain_core.libs.core.langchain_core.runnables.config.merge_configs", "langchain_core.libs.core.langchain_core.runnables.config.patch_config", "langchain_core.libs.core.langchain_core.runnables.base.RunnableLambda::invoke"], "project": "langchain_core", "origin_file": ["langchain_core/runnables/config.py", "langchain_core/runnables/config.py", "langchain_core/runnables/config.py", "langchain_core/runnables/base.py", "langchain_core/runnables/base.py"], "test_list": ["libs/core/tests/unit_tests/runnables/test_history.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 593, "func_start_lineno": 149, "func_end_lineno": 199, "func_code": "def ensure_config(config: Optional[RunnableConfig] = None) -> RunnableConfig:\n \"\"\"Ensure that a config is a dict with all keys present.\n\n Args:\n config (Optional[RunnableConfig], optional): The config to ensure.\n Defaults to None.\n\n Returns:\n RunnableConfig: The ensured config.\n \"\"\"\n empty = RunnableConfig(\n tags=[],\n metadata={},\n callbacks=None,\n recursion_limit=DEFAULT_RECURSION_LIMIT,\n configurable={},\n )\n if var_config := var_child_runnable_config.get():\n empty.update(\n cast(\n RunnableConfig,\n {\n k: v.copy() if k in COPIABLE_KEYS else v # type: ignore[attr-defined]\n for k, v in var_config.items()\n if v is not None\n },\n )\n )\n if config is not None:\n empty.update(\n cast(\n RunnableConfig,\n {\n k: v.copy() if k in COPIABLE_KEYS else v # type: ignore[attr-defined]\n for k, v in config.items()\n if v is not None and k in CONFIG_KEYS\n },\n )\n )\n if config is not None:\n for k, v in config.items():\n if k not in CONFIG_KEYS and v is not None:\n empty[\"configurable\"][k] = v\n for key, value in empty.get(\"configurable\", {}).items():\n if (\n not key.startswith(\"__\")\n and isinstance(value, (str, int, float, bool))\n and key not in empty[\"metadata\"]\n ):\n empty[\"metadata\"][key] = value\n return empty"}, {"class_start_lineno": 1, "class_end_lineno": 593, "func_start_lineno": 295, "func_end_lineno": 358, "func_code": "def merge_configs(*configs: Optional[RunnableConfig]) -> RunnableConfig:\n \"\"\"Merge multiple configs into one.\n\n Args:\n *configs (Optional[RunnableConfig]): The configs to merge.\n\n Returns:\n RunnableConfig: The merged config.\n \"\"\"\n base: RunnableConfig = {}\n # Even though the keys aren't literals, this is correct\n # because both dicts are the same type\n for config in (ensure_config(c) for c in configs if c is not None):\n for key in config:\n if key == \"metadata\":\n base[key] = { # type: ignore\n **base.get(key, {}), # type: ignore\n **(config.get(key) or {}), # type: ignore\n }\n elif key == \"tags\":\n base[key] = sorted( # type: ignore\n set(base.get(key, []) + (config.get(key) or [])), # type: ignore\n )\n elif key == \"configurable\":\n base[key] = { # type: ignore\n **base.get(key, {}), # type: ignore\n **(config.get(key) or {}), # type: ignore\n }\n elif key == \"callbacks\":\n base_callbacks = base.get(\"callbacks\")\n these_callbacks = config[\"callbacks\"]\n # callbacks can be either None, list[handler] or manager\n # so merging two callbacks values has 6 cases\n if isinstance(these_callbacks, list):\n if base_callbacks is None:\n base[\"callbacks\"] = these_callbacks.copy()\n elif isinstance(base_callbacks, list):\n base[\"callbacks\"] = base_callbacks + these_callbacks\n else:\n # base_callbacks is a manager\n mngr = base_callbacks.copy()\n for callback in these_callbacks:\n mngr.add_handler(callback, inherit=True)\n base[\"callbacks\"] = mngr\n elif these_callbacks is not None:\n # these_callbacks is a manager\n if base_callbacks is None:\n base[\"callbacks\"] = these_callbacks.copy()\n elif isinstance(base_callbacks, list):\n mngr = these_callbacks.copy()\n for callback in base_callbacks:\n mngr.add_handler(callback, inherit=True)\n base[\"callbacks\"] = mngr\n else:\n # base_callbacks is also a manager\n base[\"callbacks\"] = base_callbacks.merge(these_callbacks)\n elif key == \"recursion_limit\":\n if config[\"recursion_limit\"] != DEFAULT_RECURSION_LIMIT:\n base[\"recursion_limit\"] = config[\"recursion_limit\"]\n elif key in COPIABLE_KEYS and config[key] is not None: # type: ignore[literal-required]\n base[key] = config[key].copy() # type: ignore[literal-required]\n else:\n base[key] = config[key] or base.get(key) # type: ignore\n return base"}, {"class_start_lineno": 1, "class_end_lineno": 593, "func_start_lineno": 249, "func_end_lineno": 292, "func_code": "def patch_config(\n config: Optional[RunnableConfig],\n *,\n callbacks: Optional[BaseCallbackManager] = None,\n recursion_limit: Optional[int] = None,\n max_concurrency: Optional[int] = None,\n run_name: Optional[str] = None,\n configurable: Optional[dict[str, Any]] = None,\n) -> RunnableConfig:\n \"\"\"Patch a config with new values.\n\n Args:\n config (Optional[RunnableConfig]): The config to patch.\n callbacks (Optional[BaseCallbackManager], optional): The callbacks to set.\n Defaults to None.\n recursion_limit (Optional[int], optional): The recursion limit to set.\n Defaults to None.\n max_concurrency (Optional[int], optional): The max concurrency to set.\n Defaults to None.\n run_name (Optional[str], optional): The run name to set. Defaults to None.\n configurable (Optional[Dict[str, Any]], optional): The configurable to set.\n Defaults to None.\n\n Returns:\n RunnableConfig: The patched config.\n \"\"\"\n config = ensure_config(config)\n if callbacks is not None:\n # If we're replacing callbacks, we need to unset run_name\n # As that should apply only to the same run as the original callbacks\n config[\"callbacks\"] = callbacks\n if \"run_name\" in config:\n del config[\"run_name\"]\n if \"run_id\" in config:\n del config[\"run_id\"]\n if recursion_limit is not None:\n config[\"recursion_limit\"] = recursion_limit\n if max_concurrency is not None:\n config[\"max_concurrency\"] = max_concurrency\n if run_name is not None:\n config[\"run_name\"] = run_name\n if configurable is not None:\n config[\"configurable\"] = {**config.get(\"configurable\", {}), **configurable}\n return config"}, {"class_start_lineno": 4230, "class_end_lineno": 4967, "func_start_lineno": 4696, "func_end_lineno": 4699, "func_code": " def _config(\n self, config: Optional[RunnableConfig], callable: Callable[..., Any]\n ) -> RunnableConfig:\n return ensure_config(config)"}, {"class_start_lineno": 4230, "class_end_lineno": 4967, "func_start_lineno": 4701, "func_end_lineno": 4732, "func_code": " def invoke(\n self,\n input: Input,\n config: Optional[RunnableConfig] = None,\n **kwargs: Optional[Any],\n ) -> Output:\n \"\"\"Invoke this Runnable synchronously.\n\n Args:\n input: The input to this Runnable.\n config: The config to use. Defaults to None.\n kwargs: Additional keyword arguments.\n\n Returns:\n The output of this Runnable.\n\n Raises:\n TypeError: If the Runnable is a coroutine function.\n \"\"\"\n if hasattr(self, \"func\"):\n return self._call_with_config(\n self._invoke,\n input,\n self._config(config, self.func),\n **kwargs,\n )\n else:\n msg = (\n \"Cannot invoke a coroutine function synchronously.\"\n \"Use `ainvoke` instead.\"\n )\n raise TypeError(msg)"}], "type": ["function_empty"], "node": ["langchain_core.runnables.config.ensure_config", "langchain_core.runnables.config.merge_configs", "langchain_core.runnables.config.patch_config", "langchain_core.runnables.base.RunnableLambda._config", "langchain_core.runnables.base.RunnableLambda.invoke"], "language": "Python", "toolfunc_count": 4, "func_count": 4, "pytest_info": {"total_num": 23, "base_passed_num": 4}} {"id": ["langchain_core.libs.core.langchain_core.utils.env.get_from_env", "langchain_core.libs.core.langchain_core.utils.env.get_from_dict_or_env"], "project": "langchain_core", "origin_file": ["langchain_core/utils/env.py", "langchain_core/utils/env.py"], "test_list": ["libs/core/tests/unit_tests/utils/test_env.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 81, "func_start_lineno": 54, "func_end_lineno": 81, "func_code": "def get_from_env(key: str, env_key: str, default: Optional[str] = None) -> str:\n \"\"\"Get a value from a dictionary or an environment variable.\n\n Args:\n key: The key to look up in the dictionary.\n env_key: The environment variable to look up if the key is not\n in the dictionary.\n default: The default value to return if the key is not in the dictionary\n or the environment. Defaults to None.\n\n Returns:\n str: The value of the key.\n\n Raises:\n ValueError: If the key is not in the dictionary and no default value is\n provided or if the environment variable is not set.\n \"\"\"\n if env_key in os.environ and os.environ[env_key]:\n return os.environ[env_key]\n elif default is not None:\n return default\n else:\n msg = (\n f\"Did not find {key}, please add an environment variable\"\n f\" `{env_key}` which contains it, or pass\"\n f\" `{key}` as a named parameter.\"\n )\n raise ValueError(msg)"}, {"class_start_lineno": 1, "class_end_lineno": 81, "func_start_lineno": 24, "func_end_lineno": 51, "func_code": "def get_from_dict_or_env(\n data: dict[str, Any],\n key: Union[str, list[str]],\n env_key: str,\n default: Optional[str] = None,\n) -> str:\n \"\"\"Get a value from a dictionary or an environment variable.\n\n Args:\n data: The dictionary to look up the key in.\n key: The key to look up in the dictionary. This can be a list of keys to try\n in order.\n env_key: The environment variable to look up if the key is not\n in the dictionary.\n default: The default value to return if the key is not in the dictionary\n or the environment. Defaults to None.\n \"\"\"\n if isinstance(key, (list, tuple)):\n for k in key:\n if k in data and data[k]:\n return data[k]\n\n if isinstance(key, str) and key in data and data[key]:\n return data[key]\n\n key_for_err = key[0] if isinstance(key, (list, tuple)) else key\n\n return get_from_env(key_for_err, env_key, default=default)"}], "type": ["function_empty"], "node": ["langchain_core.utils.env.get_from_env", "langchain_core.utils.env.get_from_dict_or_env"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 1, "base_passed_num": 0}} {"id": ["langchain_core.libs.14core.langchain_core.tools.base.create_schema_from_function", "langchain_core.libs.core.langchain_core.utils.function_calling._convert_python_function_to_openai_function", "langchain_core.libs.core.langchain_core.tools.base._parse_python_function_docstring", "langchain_core.libs.core.langchain_core.tools.base._infer_arg_descriptions"], "project": "langchain_core", "origin_file": ["langchain_core/tools/base.py", "langchain_core/utils/function_calling.py", "langchain_core/tools/base.py", "langchain_core/tools/base.py"], "test_list": ["libs/core/tests/unit_tests/utils/test_function_calling.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 1112, "func_start_lineno": 210, "func_end_lineno": 307, "func_code": "def create_schema_from_function(\n model_name: str,\n func: Callable,\n *,\n filter_args: Optional[Sequence[str]] = None,\n parse_docstring: bool = False,\n error_on_invalid_docstring: bool = False,\n include_injected: bool = True,\n) -> type[BaseModel]:\n \"\"\"Create a pydantic schema from a function's signature.\n\n Args:\n model_name: Name to assign to the generated pydantic schema.\n func: Function to generate the schema from.\n filter_args: Optional list of arguments to exclude from the schema.\n Defaults to FILTERED_ARGS.\n parse_docstring: Whether to parse the function's docstring for descriptions\n for each argument. Defaults to False.\n error_on_invalid_docstring: if ``parse_docstring`` is provided, configure\n whether to raise ValueError on invalid Google Style docstrings.\n Defaults to False.\n include_injected: Whether to include injected arguments in the schema.\n Defaults to True, since we want to include them in the schema\n when *validating* tool inputs.\n\n Returns:\n A pydantic model with the same arguments as the function.\n \"\"\"\n sig = inspect.signature(func)\n\n if _function_annotations_are_pydantic_v1(sig, func):\n validated = validate_arguments_v1(func, config=_SchemaConfig) # type: ignore\n else:\n # https://docs.pydantic.dev/latest/usage/validation_decorator/\n with warnings.catch_warnings():\n # We are using deprecated functionality here.\n # This code should be re-written to simply construct a pydantic model\n # using inspect.signature and create_model.\n warnings.simplefilter(\"ignore\", category=PydanticDeprecationWarning)\n validated = validate_arguments(func, config=_SchemaConfig) # type: ignore\n\n # Let's ignore `self` and `cls` arguments for class and instance methods\n # If qualified name has a \".\", then it likely belongs in a class namespace\n in_class = bool(func.__qualname__ and \".\" in func.__qualname__)\n\n has_args = False\n has_kwargs = False\n\n for param in sig.parameters.values():\n if param.kind == param.VAR_POSITIONAL:\n has_args = True\n elif param.kind == param.VAR_KEYWORD:\n has_kwargs = True\n\n inferred_model = validated.model # type: ignore\n\n if filter_args:\n filter_args_ = filter_args\n else:\n # Handle classmethods and instance methods\n existing_params: list[str] = list(sig.parameters.keys())\n if existing_params and existing_params[0] in (\"self\", \"cls\") and in_class:\n filter_args_ = [existing_params[0]] + list(FILTERED_ARGS)\n else:\n filter_args_ = list(FILTERED_ARGS)\n\n for existing_param in existing_params:\n if not include_injected and _is_injected_arg_type(\n sig.parameters[existing_param].annotation\n ):\n filter_args_.append(existing_param)\n\n description, arg_descriptions = _infer_arg_descriptions(\n func,\n parse_docstring=parse_docstring,\n error_on_invalid_docstring=error_on_invalid_docstring,\n )\n # Pydantic adds placeholder virtual fields we need to strip\n valid_properties = []\n for field in get_fields(inferred_model):\n if not has_args and field == \"args\":\n continue\n if not has_kwargs and field == \"kwargs\":\n continue\n\n if field == \"v__duplicate_kwargs\": # Internal pydantic field\n continue\n\n if field not in filter_args_:\n valid_properties.append(field)\n\n return _create_subset_model(\n model_name,\n inferred_model,\n list(valid_properties),\n descriptions=arg_descriptions,\n fn_description=description,\n )"}, {"class_start_lineno": 1, "class_end_lineno": 704, "func_start_lineno": 160, "func_end_lineno": 190, "func_code": "def _convert_python_function_to_openai_function(\n function: Callable,\n) -> FunctionDescription:\n \"\"\"Convert a Python function to an OpenAI function-calling API compatible dict.\n\n Assumes the Python function has type hints and a docstring with a description. If\n the docstring has Google Python style argument descriptions, these will be\n included as well.\n\n Args:\n function: The Python function to convert.\n\n Returns:\n The OpenAI function description.\n \"\"\"\n from langchain_core.tools.base import create_schema_from_function\n\n func_name = _get_python_function_name(function)\n model = create_schema_from_function(\n func_name,\n function,\n filter_args=(),\n parse_docstring=True,\n error_on_invalid_docstring=False,\n include_injected=False,\n )\n return _convert_pydantic_to_openai_function(\n model,\n name=func_name,\n description=model.__doc__,\n )"}, {"class_start_lineno": 1, "class_end_lineno": 1112, "func_start_lineno": 110, "func_end_lineno": 122, "func_code": "def _parse_python_function_docstring(\n function: Callable, annotations: dict, error_on_invalid_docstring: bool = False\n) -> tuple[str, dict]:\n \"\"\"Parse the function and argument descriptions from the docstring of a function.\n\n Assumes the function docstring follows Google Python style guide.\n \"\"\"\n docstring = inspect.getdoc(function)\n return _parse_google_docstring(\n docstring,\n list(annotations),\n error_on_invalid_docstring=error_on_invalid_docstring,\n )"}, {"class_start_lineno": 1, "class_end_lineno": 1112, "func_start_lineno": 135, "func_end_lineno": 161, "func_code": "def _infer_arg_descriptions(\n fn: Callable,\n *,\n parse_docstring: bool = False,\n error_on_invalid_docstring: bool = False,\n) -> tuple[str, dict]:\n \"\"\"Infer argument descriptions from a function's docstring.\"\"\"\n if hasattr(inspect, \"get_annotations\"):\n # This is for python < 3.10\n annotations = inspect.get_annotations(fn) # type: ignore\n else:\n annotations = getattr(fn, \"__annotations__\", {})\n if parse_docstring:\n description, arg_descriptions = _parse_python_function_docstring(\n fn, annotations, error_on_invalid_docstring=error_on_invalid_docstring\n )\n else:\n description = inspect.getdoc(fn) or \"\"\n arg_descriptions = {}\n if parse_docstring:\n _validate_docstring_args_against_annotations(arg_descriptions, annotations)\n for arg, arg_type in annotations.items():\n if arg in arg_descriptions:\n continue\n if desc := _get_annotation_description(arg_type):\n arg_descriptions[arg] = desc\n return description, arg_descriptions"}], "type": ["function_empty"], "node": ["langchain_core.tools.base.create_schema_from_function", "langchain_core.utils.function_calling._convert_python_function_to_openai_function", "langchain_core.tools.base._parse_python_function_docstring", "langchain_core.tools.base._infer_arg_descriptions"], "language": "Python", "toolfunc_count": 4, "func_count": 4, "pytest_info": {"total_num": 20, "base_passed_num": 15}} {"id": ["langchain_core.libs.core.langchain_core.utils._merge.merge_lists", "langchain_core.libs.core.langchain_core.utils._merge.merge_dicts"], "project": "langchain_core", "origin_file": ["langchain_core/utils/_merge.py", "langchain_core/utils/_merge.py"], "test_list": ["libs/core/tests/unit_tests/utils/test_utils.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 148, "func_start_lineno": 72, "func_end_lineno": 106, "func_code": "def merge_lists(left: Optional[list], *others: Optional[list]) -> Optional[list]:\n \"\"\"Add many lists, handling None.\n\n Args:\n left: The first list to merge.\n others: The other lists to merge.\n\n Returns:\n The merged list.\n \"\"\"\n merged = left.copy() if left is not None else None\n for other in others:\n if other is None:\n continue\n elif merged is None:\n merged = other.copy()\n else:\n for e in other:\n if isinstance(e, dict) and \"index\" in e and isinstance(e[\"index\"], int):\n to_merge = [\n i\n for i, e_left in enumerate(merged)\n if e_left[\"index\"] == e[\"index\"]\n ]\n if to_merge:\n # TODO: Remove this once merge_dict is updated with special\n # handling for 'type'.\n if \"type\" in e:\n e = {k: v for k, v in e.items() if k != \"type\"}\n merged[to_merge[0]] = merge_dicts(merged[to_merge[0]], e)\n else:\n merged.append(e)\n else:\n merged.append(e)\n return merged"}, {"class_start_lineno": 1, "class_end_lineno": 148, "func_start_lineno": 6, "func_end_lineno": 69, "func_code": "def merge_dicts(left: dict[str, Any], *others: dict[str, Any]) -> dict[str, Any]:\n \"\"\"Merge many dicts, handling specific scenarios where a key exists in both\n dictionaries but has a value of None in 'left'. In such cases, the method uses the\n value from 'right' for that key in the merged dictionary.\n\n Args:\n left: The first dictionary to merge.\n others: The other dictionaries to merge.\n\n Returns:\n The merged dictionary.\n\n Raises:\n TypeError: If the key exists in both dictionaries but has a different type.\n TypeError: If the value has an unsupported type.\n\n Example:\n If left = {\"function_call\": {\"arguments\": None}} and\n right = {\"function_call\": {\"arguments\": \"{\\n\"}}\n then, after merging, for the key \"function_call\",\n the value from 'right' is used,\n resulting in merged = {\"function_call\": {\"arguments\": \"{\\n\"}}.\n \"\"\"\n merged = left.copy()\n for right in others:\n for right_k, right_v in right.items():\n if right_k not in merged or right_v is not None and merged[right_k] is None:\n merged[right_k] = right_v\n elif right_v is None:\n continue\n elif type(merged[right_k]) is not type(right_v):\n msg = (\n f'additional_kwargs[\"{right_k}\"] already exists in this message,'\n \" but with a different type.\"\n )\n raise TypeError(msg)\n elif isinstance(merged[right_k], str):\n # TODO: Add below special handling for 'type' key in 0.3 and remove\n # merge_lists 'type' logic.\n #\n # if right_k == \"type\":\n # if merged[right_k] == right_v:\n # continue\n # else:\n # raise ValueError(\n # \"Unable to merge. Two different values seen for special \"\n # f\"key 'type': {merged[right_k]} and {right_v}. 'type' \"\n # \"should either occur once or have the same value across \"\n # \"all dicts.\"\n # )\n merged[right_k] += right_v\n elif isinstance(merged[right_k], dict):\n merged[right_k] = merge_dicts(merged[right_k], right_v)\n elif isinstance(merged[right_k], list):\n merged[right_k] = merge_lists(merged[right_k], right_v)\n elif merged[right_k] == right_v:\n continue\n else:\n msg = (\n f\"Additional kwargs key {right_k} already exists in left dict and \"\n f\"value has unsupported type {type(merged[right_k])}.\"\n )\n raise TypeError(msg)\n return merged"}], "type": ["function_empty"], "node": ["langchain_core.utils._merge.merge_lists", "langchain_core.utils._merge.merge_dicts"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 47, "base_passed_num": 26}} {"id": ["finam.src.finam.data.grid_spec.NoGrid::compatible_with", "finam.src.finam.data.tools.mask.mask_specified", "finam.src.finam.data.tools.mask.masks_compatible", "finam.src.finam.data.tools.info.Info::accepts"], "project": "finam", "origin_file": ["finam/data/grid_spec.py", "finam/data/tools/mask.py", "finam/data/tools/info.py", "finam/data/tools/mask.py", "finam/data/tools/info.py"], "test_list": ["tests/adapters/test_probe.py", "tests/adapters/test_time.py", "tests/components/test_debug.py", "tests/core/test_pull_based_component.py"], "prob_info": [{"class_start_lineno": 30, "class_end_lineno": 90, "func_start_lineno": 71, "func_end_lineno": 87, "func_code": " def compatible_with(self, other, check_location=True):\n \"\"\"\n Check for compatibility with other Grid.\n\n Parameters\n ----------\n other : instance of Grid\n Other grid to compatibility with.\n check_location : bool, optional\n Whether to check location for equality, by default True\n\n Returns\n -------\n bool\n compatibility\n \"\"\"\n return isinstance(other, NoGrid) and self.data_shape == other.data_shape"}, {"class_start_lineno": 1, "class_end_lineno": 378, "func_start_lineno": 364, "func_end_lineno": 378, "func_code": "def mask_specified(mask):\n \"\"\"\n Determine whether given mask selection indicates a masked array.\n\n Parameters\n ----------\n mask : :any:`Mask` value or valid boolean mask for :any:`MaskedArray`\n mask to check\n\n Returns\n -------\n bool\n False if mask is Mask.FLEX or Mask.NONE, True otherwise\n \"\"\"\n return not any(mask is val for val in list(Mask))"}, {"class_start_lineno": 22, "class_end_lineno": 248, "func_start_lineno": 87, "func_end_lineno": 89, "func_code": " def mask(self):\n \"\"\"Mask or ndarray: data mask.\"\"\"\n return self._mask"}, {"class_start_lineno": 1, "class_end_lineno": 378, "func_start_lineno": 243, "func_end_lineno": 285, "func_code": "def masks_compatible(\n this, incoming, incoming_donwstream, this_grid=None, incoming_grid=None\n):\n \"\"\"\n Check if an incoming mask is compatible with a given mask.\n\n Parameters\n ----------\n this : :any:`Mask` value or valid boolean mask for :any:`MaskedArray` or None\n mask specification to check against\n incoming : :any:`Mask` value or valid boolean mask for :any:`MaskedArray` or None\n incoming mask to check for compatibility\n incoming_donwstream : bool\n Whether the incoming mask is from downstream data\n this_grid : Grid or NoGrid or None, optional\n grid for first mask (to check shape and value equality)\n incoming_grid : Grid or NoGrid or None, optional\n grid for second mask (to check shape and value equality)\n\n Returns\n -------\n bool\n mask compatibility\n \"\"\"\n if incoming_donwstream:\n upstream, downstream = this, incoming\n up_grid, down_grid = this_grid, incoming_grid\n else:\n upstream, downstream = incoming, this\n up_grid, down_grid = incoming_grid, this_grid\n # None is incompatible\n if upstream is None:\n return False\n # Mask.FLEX accepts anything, Mask.NONE only Mask.NONE\n if not mask_specified(downstream):\n if not mask_specified(upstream):\n return downstream == Mask.FLEX or upstream == Mask.NONE\n return downstream == Mask.FLEX\n # if mask is specified, upstream mask must also be specified\n if not mask_specified(upstream):\n return False\n # if both mask given, compare them\n return masks_equal(downstream, upstream, down_grid, up_grid)"}, {"class_start_lineno": 22, "class_end_lineno": 248, "func_start_lineno": 157, "func_end_lineno": 201, "func_code": " def accepts(self, incoming, fail_info, incoming_donwstream=False):\n \"\"\"\n Tests whether this info can accept/is compatible with an incoming info.\n\n Tested attributes are: \"grid\", \"mask\" and \"units\"\n\n Parameters\n ----------\n incoming : Info\n Incoming/source info to check. This is the info from upstream.\n fail_info : dict\n Dictionary that will be filled with failed properties; name: (source, target).\n incoming_donwstream : bool, optional\n Whether the incoming info is from downstream data. Default: False\n\n Returns\n -------\n bool\n Whether the incoming info is accepted\n \"\"\"\n if not isinstance(incoming, Info):\n fail_info[\"type\"] = (incoming.__class__, self.__class__)\n return False\n\n success = True\n if self.grid is not None and not self.grid.compatible_with(incoming.grid):\n if not (incoming_donwstream and incoming.grid is None):\n fail_info[\"grid\"] = (incoming.grid, self.grid)\n success = False\n\n if self.mask is not None and not masks_compatible(\n self.mask, incoming.mask, incoming_donwstream, self.grid, incoming.grid\n ):\n if not (incoming_donwstream and incoming.mask is None):\n fail_info[\"mask\"] = (incoming.mask, self.mask)\n success = False\n\n u1_none = (u1 := self.units) is None\n u2_none = (u2 := incoming.units) is None\n if not u1_none and (u2_none or not compatible_units(u1, u2)):\n if not (incoming_donwstream and u2_none):\n fail_info[\"units\"] = (u2, u1)\n success = False\n\n return success"}], "type": ["function_empty"], "node": ["finam.data.grid_spec.NoGrid.compatible_with", "finam.data.tools.mask.mask_specified", "finam.data.tools.info.Info.mask", "finam.data.tools.mask.masks_compatible", "finam.data.tools.info.Info.accepts"], "language": "Python", "toolfunc_count": 4, "func_count": 4, "pytest_info": {"total_num": 15, "base_passed_num": 2}} {"id": ["finam.src.finam.data.tools.mask.mask_specified", "finam.src.finam.data.tools.mask.masks_compatible", "finam.src.finam.data.tools.info.Info::accepts", "finam.src.finam.data.tools.mask.from_compressed"], "project": "finam", "origin_file": ["finam/data/tools/mask.py", "finam/data/tools/info.py", "finam/data/tools/mask.py", "finam/data/tools/info.py", "finam/data/tools/mask.py"], "test_list": ["tests/adapters/test_regrid.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 378, "func_start_lineno": 364, "func_end_lineno": 378, "func_code": "def mask_specified(mask):\n \"\"\"\n Determine whether given mask selection indicates a masked array.\n\n Parameters\n ----------\n mask : :any:`Mask` value or valid boolean mask for :any:`MaskedArray`\n mask to check\n\n Returns\n -------\n bool\n False if mask is Mask.FLEX or Mask.NONE, True otherwise\n \"\"\"\n return not any(mask is val for val in list(Mask))"}, {"class_start_lineno": 22, "class_end_lineno": 248, "func_start_lineno": 87, "func_end_lineno": 89, "func_code": " def mask(self):\n \"\"\"Mask or ndarray: data mask.\"\"\"\n return self._mask"}, {"class_start_lineno": 1, "class_end_lineno": 378, "func_start_lineno": 243, "func_end_lineno": 285, "func_code": "def masks_compatible(\n this, incoming, incoming_donwstream, this_grid=None, incoming_grid=None\n):\n \"\"\"\n Check if an incoming mask is compatible with a given mask.\n\n Parameters\n ----------\n this : :any:`Mask` value or valid boolean mask for :any:`MaskedArray` or None\n mask specification to check against\n incoming : :any:`Mask` value or valid boolean mask for :any:`MaskedArray` or None\n incoming mask to check for compatibility\n incoming_donwstream : bool\n Whether the incoming mask is from downstream data\n this_grid : Grid or NoGrid or None, optional\n grid for first mask (to check shape and value equality)\n incoming_grid : Grid or NoGrid or None, optional\n grid for second mask (to check shape and value equality)\n\n Returns\n -------\n bool\n mask compatibility\n \"\"\"\n if incoming_donwstream:\n upstream, downstream = this, incoming\n up_grid, down_grid = this_grid, incoming_grid\n else:\n upstream, downstream = incoming, this\n up_grid, down_grid = incoming_grid, this_grid\n # None is incompatible\n if upstream is None:\n return False\n # Mask.FLEX accepts anything, Mask.NONE only Mask.NONE\n if not mask_specified(downstream):\n if not mask_specified(upstream):\n return downstream == Mask.FLEX or upstream == Mask.NONE\n return downstream == Mask.FLEX\n # if mask is specified, upstream mask must also be specified\n if not mask_specified(upstream):\n return False\n # if both mask given, compare them\n return masks_equal(downstream, upstream, down_grid, up_grid)"}, {"class_start_lineno": 22, "class_end_lineno": 248, "func_start_lineno": 157, "func_end_lineno": 201, "func_code": " def accepts(self, incoming, fail_info, incoming_donwstream=False):\n \"\"\"\n Tests whether this info can accept/is compatible with an incoming info.\n\n Tested attributes are: \"grid\", \"mask\" and \"units\"\n\n Parameters\n ----------\n incoming : Info\n Incoming/source info to check. This is the info from upstream.\n fail_info : dict\n Dictionary that will be filled with failed properties; name: (source, target).\n incoming_donwstream : bool, optional\n Whether the incoming info is from downstream data. Default: False\n\n Returns\n -------\n bool\n Whether the incoming info is accepted\n \"\"\"\n if not isinstance(incoming, Info):\n fail_info[\"type\"] = (incoming.__class__, self.__class__)\n return False\n\n success = True\n if self.grid is not None and not self.grid.compatible_with(incoming.grid):\n if not (incoming_donwstream and incoming.grid is None):\n fail_info[\"grid\"] = (incoming.grid, self.grid)\n success = False\n\n if self.mask is not None and not masks_compatible(\n self.mask, incoming.mask, incoming_donwstream, self.grid, incoming.grid\n ):\n if not (incoming_donwstream and incoming.mask is None):\n fail_info[\"mask\"] = (incoming.mask, self.mask)\n success = False\n\n u1_none = (u1 := self.units) is None\n u2_none = (u2 := incoming.units) is None\n if not u1_none and (u2_none or not compatible_units(u1, u2)):\n if not (incoming_donwstream and u2_none):\n fail_info[\"units\"] = (u2, u1)\n success = False\n\n return success"}, {"class_start_lineno": 1, "class_end_lineno": 378, "func_start_lineno": 151, "func_end_lineno": 205, "func_code": "def from_compressed(xdata, shape, order=\"C\", mask=None, **kwargs):\n \"\"\"\n Fill a (masked) array following a given mask or shape with the provided data.\n\n This will only create a masked array if kwargs are given (especially a mask).\n Otherwise this is simply reshaping the given data.\n Filling is performed in the given array order.\n\n Parameters\n ----------\n data : :class:`pint.Quantity` or :class:`numpy.ndarray` or :class:`numpy.ma.MaskedArray`\n The reference object input.\n shape : str\n shape argument for :any:`numpy.reshape`\n order : str\n order argument for :any:`numpy.reshape`\n mask : :any:`Mask` value or valid boolean mask for :any:`MaskedArray`\n mask to use\n **kwargs\n keyword arguments forwarded to :any:`numpy.ma.array`\n\n Returns\n -------\n :class:`pint.Quantity` or :class:`numpy.ndarray` or :class:`numpy.ma.MaskedArray`\n New object with the desired shape and same type as input.\n Units will be taken from the input if present.\n Will only be a masked array if kwargs are given.\n\n See also\n --------\n to_compressed:\n Inverse operation.\n :any:`numpy.ma.array`:\n Routine consuming kwargs to create a masked array.\n :any:`numpy.reshape`:\n Equivalent routine if no mask is provided.\n\n Notes\n -----\n If both `mask` and `shape` are given, they need to match in size.\n \"\"\"\n if mask is None or mask is np.ma.nomask or not mask_specified(mask):\n if kwargs and mask is Mask.NONE:\n msg = \"from_compressed: Can't create masked array with mask=Mask.NONE\"\n raise FinamDataError(msg)\n data = np.reshape(xdata, shape, order=order)\n return to_masked(data, **kwargs) if kwargs or mask is np.ma.nomask else data\n if is_quantified(xdata):\n # pylint: disable-next=unexpected-keyword-arg\n data = quantify(np.empty_like(xdata, shape=np.prod(shape)), xdata.units)\n else:\n # pylint: disable-next=unexpected-keyword-arg\n data = np.empty_like(xdata, shape=np.prod(shape))\n data[np.logical_not(np.ravel(mask, order=order))] = xdata\n return to_masked(np.reshape(data, shape, order=order), mask=mask, **kwargs)"}], "type": ["function_empty"], "node": ["finam.data.tools.mask.mask_specified", "finam.data.tools.info.Info.mask", "finam.data.tools.mask.masks_compatible", "finam.data.tools.info.Info.accepts", "finam.data.tools.mask.from_compressed"], "language": "Python", "toolfunc_count": 4, "func_count": 4, "pytest_info": {"total_num": 11, "base_passed_num": 1}} {"id": ["finam.src.finam.data.tools.mask.mask_specified", "finam.src.finam.data.tools.mask.from_compressed", "finam.src.finam.data.tools.mask.masks_compatible", "finam.src.finam.data.tools.info.Info::accepts"], "project": "finam", "origin_file": ["finam/data/tools/mask.py", "finam/data/tools/mask.py", "finam/data/tools/info.py", "finam/data/tools/mask.py", "finam/data/tools/info.py"], "test_list": ["tests/adapters/test_regrid_mask.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 378, "func_start_lineno": 364, "func_end_lineno": 378, "func_code": "def mask_specified(mask):\n \"\"\"\n Determine whether given mask selection indicates a masked array.\n\n Parameters\n ----------\n mask : :any:`Mask` value or valid boolean mask for :any:`MaskedArray`\n mask to check\n\n Returns\n -------\n bool\n False if mask is Mask.FLEX or Mask.NONE, True otherwise\n \"\"\"\n return not any(mask is val for val in list(Mask))"}, {"class_start_lineno": 1, "class_end_lineno": 378, "func_start_lineno": 151, "func_end_lineno": 205, "func_code": "def from_compressed(xdata, shape, order=\"C\", mask=None, **kwargs):\n \"\"\"\n Fill a (masked) array following a given mask or shape with the provided data.\n\n This will only create a masked array if kwargs are given (especially a mask).\n Otherwise this is simply reshaping the given data.\n Filling is performed in the given array order.\n\n Parameters\n ----------\n data : :class:`pint.Quantity` or :class:`numpy.ndarray` or :class:`numpy.ma.MaskedArray`\n The reference object input.\n shape : str\n shape argument for :any:`numpy.reshape`\n order : str\n order argument for :any:`numpy.reshape`\n mask : :any:`Mask` value or valid boolean mask for :any:`MaskedArray`\n mask to use\n **kwargs\n keyword arguments forwarded to :any:`numpy.ma.array`\n\n Returns\n -------\n :class:`pint.Quantity` or :class:`numpy.ndarray` or :class:`numpy.ma.MaskedArray`\n New object with the desired shape and same type as input.\n Units will be taken from the input if present.\n Will only be a masked array if kwargs are given.\n\n See also\n --------\n to_compressed:\n Inverse operation.\n :any:`numpy.ma.array`:\n Routine consuming kwargs to create a masked array.\n :any:`numpy.reshape`:\n Equivalent routine if no mask is provided.\n\n Notes\n -----\n If both `mask` and `shape` are given, they need to match in size.\n \"\"\"\n if mask is None or mask is np.ma.nomask or not mask_specified(mask):\n if kwargs and mask is Mask.NONE:\n msg = \"from_compressed: Can't create masked array with mask=Mask.NONE\"\n raise FinamDataError(msg)\n data = np.reshape(xdata, shape, order=order)\n return to_masked(data, **kwargs) if kwargs or mask is np.ma.nomask else data\n if is_quantified(xdata):\n # pylint: disable-next=unexpected-keyword-arg\n data = quantify(np.empty_like(xdata, shape=np.prod(shape)), xdata.units)\n else:\n # pylint: disable-next=unexpected-keyword-arg\n data = np.empty_like(xdata, shape=np.prod(shape))\n data[np.logical_not(np.ravel(mask, order=order))] = xdata\n return to_masked(np.reshape(data, shape, order=order), mask=mask, **kwargs)"}, {"class_start_lineno": 22, "class_end_lineno": 248, "func_start_lineno": 87, "func_end_lineno": 89, "func_code": " def mask(self):\n \"\"\"Mask or ndarray: data mask.\"\"\"\n return self._mask"}, {"class_start_lineno": 1, "class_end_lineno": 378, "func_start_lineno": 243, "func_end_lineno": 285, "func_code": "def masks_compatible(\n this, incoming, incoming_donwstream, this_grid=None, incoming_grid=None\n):\n \"\"\"\n Check if an incoming mask is compatible with a given mask.\n\n Parameters\n ----------\n this : :any:`Mask` value or valid boolean mask for :any:`MaskedArray` or None\n mask specification to check against\n incoming : :any:`Mask` value or valid boolean mask for :any:`MaskedArray` or None\n incoming mask to check for compatibility\n incoming_donwstream : bool\n Whether the incoming mask is from downstream data\n this_grid : Grid or NoGrid or None, optional\n grid for first mask (to check shape and value equality)\n incoming_grid : Grid or NoGrid or None, optional\n grid for second mask (to check shape and value equality)\n\n Returns\n -------\n bool\n mask compatibility\n \"\"\"\n if incoming_donwstream:\n upstream, downstream = this, incoming\n up_grid, down_grid = this_grid, incoming_grid\n else:\n upstream, downstream = incoming, this\n up_grid, down_grid = incoming_grid, this_grid\n # None is incompatible\n if upstream is None:\n return False\n # Mask.FLEX accepts anything, Mask.NONE only Mask.NONE\n if not mask_specified(downstream):\n if not mask_specified(upstream):\n return downstream == Mask.FLEX or upstream == Mask.NONE\n return downstream == Mask.FLEX\n # if mask is specified, upstream mask must also be specified\n if not mask_specified(upstream):\n return False\n # if both mask given, compare them\n return masks_equal(downstream, upstream, down_grid, up_grid)"}, {"class_start_lineno": 22, "class_end_lineno": 248, "func_start_lineno": 157, "func_end_lineno": 201, "func_code": " def accepts(self, incoming, fail_info, incoming_donwstream=False):\n \"\"\"\n Tests whether this info can accept/is compatible with an incoming info.\n\n Tested attributes are: \"grid\", \"mask\" and \"units\"\n\n Parameters\n ----------\n incoming : Info\n Incoming/source info to check. This is the info from upstream.\n fail_info : dict\n Dictionary that will be filled with failed properties; name: (source, target).\n incoming_donwstream : bool, optional\n Whether the incoming info is from downstream data. Default: False\n\n Returns\n -------\n bool\n Whether the incoming info is accepted\n \"\"\"\n if not isinstance(incoming, Info):\n fail_info[\"type\"] = (incoming.__class__, self.__class__)\n return False\n\n success = True\n if self.grid is not None and not self.grid.compatible_with(incoming.grid):\n if not (incoming_donwstream and incoming.grid is None):\n fail_info[\"grid\"] = (incoming.grid, self.grid)\n success = False\n\n if self.mask is not None and not masks_compatible(\n self.mask, incoming.mask, incoming_donwstream, self.grid, incoming.grid\n ):\n if not (incoming_donwstream and incoming.mask is None):\n fail_info[\"mask\"] = (incoming.mask, self.mask)\n success = False\n\n u1_none = (u1 := self.units) is None\n u2_none = (u2 := incoming.units) is None\n if not u1_none and (u2_none or not compatible_units(u1, u2)):\n if not (incoming_donwstream and u2_none):\n fail_info[\"units\"] = (u2, u1)\n success = False\n\n return success"}], "type": ["function_empty"], "node": ["finam.data.tools.mask.mask_specified", "finam.data.tools.mask.from_compressed", "finam.data.tools.info.Info.mask", "finam.data.tools.mask.masks_compatible", "finam.data.tools.info.Info.accepts"], "language": "Python", "toolfunc_count": 4, "func_count": 4, "pytest_info": {"total_num": 6, "base_passed_num": 0}} {"id": ["finam.src.finam.data.tools.mask.mask_specified", "finam.src.finam.data.tools.mask.masks_compatible", "finam.src.finam.data.tools.info.Info::accepts", "finam.src.finam.data.tools.units.is_quantified", "finam.src.finam.data.tools.core.prepare"], "project": "finam", "origin_file": ["finam/data/tools/mask.py", "finam/data/tools/info.py", "finam/data/tools/mask.py", "finam/data/tools/info.py", "finam/data/tools/units.py", "finam/data/tools/core.py"], "test_list": ["tests/adapters/test_stats.py", "tests/components/test_simplex_noise.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 378, "func_start_lineno": 364, "func_end_lineno": 378, "func_code": "def mask_specified(mask):\n \"\"\"\n Determine whether given mask selection indicates a masked array.\n\n Parameters\n ----------\n mask : :any:`Mask` value or valid boolean mask for :any:`MaskedArray`\n mask to check\n\n Returns\n -------\n bool\n False if mask is Mask.FLEX or Mask.NONE, True otherwise\n \"\"\"\n return not any(mask is val for val in list(Mask))"}, {"class_start_lineno": 22, "class_end_lineno": 248, "func_start_lineno": 87, "func_end_lineno": 89, "func_code": " def mask(self):\n \"\"\"Mask or ndarray: data mask.\"\"\"\n return self._mask"}, {"class_start_lineno": 1, "class_end_lineno": 378, "func_start_lineno": 243, "func_end_lineno": 285, "func_code": "def masks_compatible(\n this, incoming, incoming_donwstream, this_grid=None, incoming_grid=None\n):\n \"\"\"\n Check if an incoming mask is compatible with a given mask.\n\n Parameters\n ----------\n this : :any:`Mask` value or valid boolean mask for :any:`MaskedArray` or None\n mask specification to check against\n incoming : :any:`Mask` value or valid boolean mask for :any:`MaskedArray` or None\n incoming mask to check for compatibility\n incoming_donwstream : bool\n Whether the incoming mask is from downstream data\n this_grid : Grid or NoGrid or None, optional\n grid for first mask (to check shape and value equality)\n incoming_grid : Grid or NoGrid or None, optional\n grid for second mask (to check shape and value equality)\n\n Returns\n -------\n bool\n mask compatibility\n \"\"\"\n if incoming_donwstream:\n upstream, downstream = this, incoming\n up_grid, down_grid = this_grid, incoming_grid\n else:\n upstream, downstream = incoming, this\n up_grid, down_grid = incoming_grid, this_grid\n # None is incompatible\n if upstream is None:\n return False\n # Mask.FLEX accepts anything, Mask.NONE only Mask.NONE\n if not mask_specified(downstream):\n if not mask_specified(upstream):\n return downstream == Mask.FLEX or upstream == Mask.NONE\n return downstream == Mask.FLEX\n # if mask is specified, upstream mask must also be specified\n if not mask_specified(upstream):\n return False\n # if both mask given, compare them\n return masks_equal(downstream, upstream, down_grid, up_grid)"}, {"class_start_lineno": 22, "class_end_lineno": 248, "func_start_lineno": 157, "func_end_lineno": 201, "func_code": " def accepts(self, incoming, fail_info, incoming_donwstream=False):\n \"\"\"\n Tests whether this info can accept/is compatible with an incoming info.\n\n Tested attributes are: \"grid\", \"mask\" and \"units\"\n\n Parameters\n ----------\n incoming : Info\n Incoming/source info to check. This is the info from upstream.\n fail_info : dict\n Dictionary that will be filled with failed properties; name: (source, target).\n incoming_donwstream : bool, optional\n Whether the incoming info is from downstream data. Default: False\n\n Returns\n -------\n bool\n Whether the incoming info is accepted\n \"\"\"\n if not isinstance(incoming, Info):\n fail_info[\"type\"] = (incoming.__class__, self.__class__)\n return False\n\n success = True\n if self.grid is not None and not self.grid.compatible_with(incoming.grid):\n if not (incoming_donwstream and incoming.grid is None):\n fail_info[\"grid\"] = (incoming.grid, self.grid)\n success = False\n\n if self.mask is not None and not masks_compatible(\n self.mask, incoming.mask, incoming_donwstream, self.grid, incoming.grid\n ):\n if not (incoming_donwstream and incoming.mask is None):\n fail_info[\"mask\"] = (incoming.mask, self.mask)\n success = False\n\n u1_none = (u1 := self.units) is None\n u2_none = (u2 := incoming.units) is None\n if not u1_none and (u2_none or not compatible_units(u1, u2)):\n if not (incoming_donwstream and u2_none):\n fail_info[\"units\"] = (u2, u1)\n success = False\n\n return success"}, {"class_start_lineno": 1, "class_end_lineno": 249, "func_start_lineno": 115, "func_end_lineno": 129, "func_code": "def is_quantified(xdata):\n \"\"\"\n Check if data is a quantified DataArray.\n\n Parameters\n ----------\n xdata : Any\n The given data array.\n\n Returns\n -------\n bool\n Whether the data is a quantified DataArray.\n \"\"\"\n return isinstance(xdata, pint.Quantity)"}, {"class_start_lineno": 1, "class_end_lineno": 363, "func_start_lineno": 26, "func_end_lineno": 113, "func_code": "def prepare(data, info, time_entries=1, force_copy=False, report_conversion=False):\n \"\"\"\n Prepares data in FINAM's internal transmission format.\n\n Checks tha shape of the data.\n Checks or adds units and time dimension.\n\n Parameters\n ----------\n data : arraylike\n The input data.\n info : Info\n Info associated with the data.\n time_entries : int, optional\n Number of time slices in the data. Default 1.\n force_copy : bool, optional\n Forces the result to be a copy of the passed data. Default ``False``.\n\n If not used, the result is a view of the data if no units conversion needs to be done.\n report_conversion : bool, optional\n If true, returns a tuple with the second element indicating the unit conversion if it was required.\n\n Returns\n -------\n pint.Quantity or tuple(pint.Quantity, tuple(pint.Unit, pint.Unit) or None)\n The prepared data as a numpy array, wrapped into a :class:`pint.Quantity`.\n\n If ``report_conversion`` is ``True``, a tuple is returned with the second element\n indicating the unit conversion if it was required.\n\n The second element is ``None`` if no conversion was required,\n and a tuple of two :class:`pint.Unit` objects otherwise.\n\n Raises\n ------\n FinamDataError\n If the data doesn't match its info.\n \"\"\"\n units_converted = None\n units = info.units\n if is_quantified(data):\n if not compatible_units(data.units, units):\n raise FinamDataError(\n f\"Given data has incompatible units. \"\n f\"Got {data.units}, expected {units}.\"\n )\n if info.is_masked and not np.ma.isarray(data.magnitude):\n data = UNITS.Quantity(\n np.ma.array(\n data=data.magnitude,\n mask=info.mask,\n shrink=False,\n fill_value=info.fill_value,\n ),\n data.units,\n )\n if not equivalent_units(data.units, units):\n units_converted = data.units, units\n data = data.to(units)\n elif force_copy:\n data = data.copy()\n else:\n if info.is_masked and not np.ma.isarray(data):\n data = UNITS.Quantity(\n np.ma.array(\n data=data,\n mask=info.mask,\n shrink=False,\n fill_value=info.fill_value,\n copy=force_copy,\n ),\n units,\n )\n # this covers masked arrays as well\n elif isinstance(data, np.ndarray):\n if force_copy:\n data = data.copy()\n data = UNITS.Quantity(data, units)\n else:\n if force_copy:\n data = copy.copy(data)\n data = UNITS.Quantity(np.asarray(data), units)\n\n data = _check_input_shape(data, info, time_entries)\n\n if report_conversion:\n return data, units_converted\n return data"}], "type": ["function_empty"], "node": ["finam.data.tools.mask.mask_specified", "finam.data.tools.info.Info.mask", "finam.data.tools.mask.masks_compatible", "finam.data.tools.info.Info.accepts", "finam.data.tools.units.is_quantified", "finam.data.tools.core.prepare"], "language": "Python", "toolfunc_count": 5, "func_count": 5, "pytest_info": {"total_num": 3, "base_passed_num": 0}} {"id": ["finam.src.finam.sdk.output.Output::push_info", "finam.src.finam.sdk.component.IOList::add", "finam.src.finam.data.grid_tools.gen_axes", "finam.src.finam.components.generators.CallbackGenerator::_connect"], "project": "finam", "origin_file": ["finam/sdk/output.py", "finam/sdk/output.py", "finam/sdk/component.py", "finam/data/grid_tools.py", "finam/data/grid_spec.py", "finam/components/generators.py"], "test_list": ["tests/adapters/test_time_integration.py"], "prob_info": [{"class_start_lineno": 25, "class_end_lineno": 461, "func_start_lineno": 204, "func_end_lineno": 216, "func_code": " def push_info(self, info):\n \"\"\"Push data info into the output.\n\n Parameters\n ----------\n info : :class:`.Info`\n Delivered data info\n \"\"\"\n self.logger.trace(\"push info\")\n if not isinstance(info, Info):\n with ErrorLogger(self.logger):\n raise FinamMetaDataError(\"Metadata must be of type Info\")\n self._output_info = info"}, {"class_start_lineno": 25, "class_end_lineno": 461, "func_start_lineno": 28, "func_end_lineno": 53, "func_code": " def __init__(self, name=None, info=None, static=False, **info_kwargs):\n Loggable.__init__(self)\n self._targets = []\n self.data = []\n self._output_info = None\n self.base_logger_name = None\n if name is None:\n raise ValueError(\"Output: needs a name.\")\n self._name = name\n self._static = static\n\n if info_kwargs:\n if info is not None:\n raise ValueError(\"Output: can't use **kwargs in combination with info\")\n info = Info(**info_kwargs)\n if info is not None:\n self.push_info(info)\n\n self._connected_inputs = {}\n self._out_infos_exchanged = 0\n\n self._time = None\n self._mem_limit = None\n self._mem_location = None\n self._total_mem = 0\n self._mem_counter = 0"}, {"class_start_lineno": 572, "class_end_lineno": 711, "func_start_lineno": 602, "func_end_lineno": 635, "func_code": " def add(self, io=None, *, name=None, info=None, static=False, **info_kwargs):\n \"\"\"\n Add a new IO object either directly ob by attributes.\n\n Parameters\n ----------\n io : :class:`.IInput` or :class:`.IOutput`, optional\n IO object to add, by default None\n name : str, optional\n Name of the new IO object to add, by default None\n info : :class:`.Info`, optional\n Info of the new IO object to add, by default None\n static : bool, optional\n Whether the new IO object in static, by default False\n **info_kwargs\n Optional keyword arguments to instantiate an Info object\n\n Raises\n ------\n ValueError\n If io is not of the correct type.\n \"\"\"\n if self.frozen:\n raise ValueError(\"IO.add: list is frozen.\")\n io = (\n self.cls(name=name, info=info, static=static, **info_kwargs)\n if io is None\n else io\n )\n if not isinstance(io, self.icls):\n raise ValueError(f\"IO.add: {self.name} is not of type {self.iname}\")\n if io.name in self._dict:\n raise ValueError(f\"IO.add: {self.name} '{io.name}' already exists.\")\n self._dict[io.name] = io"}, {"class_start_lineno": 1, "class_end_lineno": 526, "func_start_lineno": 78, "func_end_lineno": 107, "func_code": "def gen_axes(dims, spacing, origin, axes_increase=None):\n \"\"\"\n Generate uniform axes.\n\n Parameters\n ----------\n dims : iterable\n Dimensions of the uniform grid for each direction.\n spacing : iterable\n Spacing of the uniform in each dimension. Must be positive.\n origin : iterable\n Origin of the uniform grid.\n axes_increase : arraylike or None, optional\n False to indicate a bottom up axis (in xyz order), by default None\n\n Returns\n -------\n list of np.ndarray\n Axes of the uniform grid.\n \"\"\"\n if axes_increase is None:\n axes_increase = np.full(len(dims), True, dtype=bool)\n if len(axes_increase) != len(dims):\n raise ValueError(\"gen_axes: wrong length of 'axes_increase'\")\n axes = []\n for i, d in enumerate(dims):\n axes.append(np.arange(d) * spacing[i] + origin[i])\n if not axes_increase[i]:\n axes[i] = axes[i][::-1]\n return axes"}, {"class_start_lineno": 236, "class_end_lineno": 364, "func_start_lineno": 267, "func_end_lineno": 296, "func_code": " def __init__(\n self,\n dims,\n spacing=(1.0, 1.0, 1.0),\n origin=(0.0, 0.0, 0.0),\n data_location=Location.CELLS,\n order=\"F\",\n axes_reversed=False,\n axes_increase=None,\n axes_attributes=None,\n axes_names=None,\n crs=None,\n ):\n # at most 3 axes\n dims = tuple(dims)[:3]\n self.spacing = tuple(spacing)[: len(dims)]\n if len(self.spacing) < len(dims):\n raise ValueError(\"UniformGrid: wrong length of 'spacing'\")\n self.origin = tuple(origin)[: len(dims)]\n if len(self.origin) < len(dims):\n raise ValueError(\"UniformGrid: wrong length of 'origin'\")\n super().__init__(\n axes=gen_axes(dims, self.spacing, self.origin, axes_increase),\n data_location=data_location,\n order=order,\n axes_reversed=axes_reversed,\n axes_attributes=axes_attributes,\n axes_names=axes_names,\n crs=crs,\n )"}, {"class_start_lineno": 11, "class_end_lineno": 127, "func_start_lineno": 82, "func_end_lineno": 102, "func_code": " def _connect(self, start_time):\n \"\"\"Push initial values to outputs.\n\n After the method call, the component should have status CONNECTED.\n \"\"\"\n if self._initial_data is None:\n self._initial_data = {\n key: callback(self._time)\n for key, (callback, _) in self._callbacks.items()\n }\n\n push_data = {}\n for name, req in self.connector.data_required.items():\n if req:\n push_data[name] = self._initial_data[name]\n\n self.try_connect(start_time, push_data=push_data)\n\n if self.status == ComponentStatus.CONNECTED:\n del self._initial_data\n del self._connector"}], "type": ["function_empty", "TDD"], "node": ["finam.sdk.output.Output.push_info", "finam.sdk.output.Output.__init__", "finam.sdk.component.IOList.add", "finam.data.grid_tools.gen_axes", "finam.data.grid_spec.UniformGrid.__init__", "finam.components.generators.CallbackGenerator._connect"], "language": "Python", "toolfunc_count": 3, "func_count": 4, "pytest_info": {"total_num": 5, "base_passed_num": 0}} {"id": ["finam.src.finam.sdk.output.Output::push_info", "finam.src.finam.sdk.component.IOList::add", "finam.src.finam.data.grid_spec.NoGrid::compatible_with", "finam.src.finam.data.tools.mask.mask_specified", "finam.src.finam.data.tools.info.Info::accepts"], "project": "finam", "origin_file": ["finam/sdk/output.py", "finam/sdk/output.py", "finam/sdk/component.py", "finam/data/grid_spec.py", "finam/data/tools/mask.py", "finam/data/tools/info.py", "finam/data/tools/info.py"], "test_list": ["tests/components/test_callback.py", "tests/components/test_noise.py", "tests/core/test_propagate_info.py", "tests/core/test_schedule.py"], "prob_info": [{"class_start_lineno": 25, "class_end_lineno": 461, "func_start_lineno": 204, "func_end_lineno": 216, "func_code": " def push_info(self, info):\n \"\"\"Push data info into the output.\n\n Parameters\n ----------\n info : :class:`.Info`\n Delivered data info\n \"\"\"\n self.logger.trace(\"push info\")\n if not isinstance(info, Info):\n with ErrorLogger(self.logger):\n raise FinamMetaDataError(\"Metadata must be of type Info\")\n self._output_info = info"}, {"class_start_lineno": 25, "class_end_lineno": 461, "func_start_lineno": 28, "func_end_lineno": 53, "func_code": " def __init__(self, name=None, info=None, static=False, **info_kwargs):\n Loggable.__init__(self)\n self._targets = []\n self.data = []\n self._output_info = None\n self.base_logger_name = None\n if name is None:\n raise ValueError(\"Output: needs a name.\")\n self._name = name\n self._static = static\n\n if info_kwargs:\n if info is not None:\n raise ValueError(\"Output: can't use **kwargs in combination with info\")\n info = Info(**info_kwargs)\n if info is not None:\n self.push_info(info)\n\n self._connected_inputs = {}\n self._out_infos_exchanged = 0\n\n self._time = None\n self._mem_limit = None\n self._mem_location = None\n self._total_mem = 0\n self._mem_counter = 0"}, {"class_start_lineno": 572, "class_end_lineno": 711, "func_start_lineno": 602, "func_end_lineno": 635, "func_code": " def add(self, io=None, *, name=None, info=None, static=False, **info_kwargs):\n \"\"\"\n Add a new IO object either directly ob by attributes.\n\n Parameters\n ----------\n io : :class:`.IInput` or :class:`.IOutput`, optional\n IO object to add, by default None\n name : str, optional\n Name of the new IO object to add, by default None\n info : :class:`.Info`, optional\n Info of the new IO object to add, by default None\n static : bool, optional\n Whether the new IO object in static, by default False\n **info_kwargs\n Optional keyword arguments to instantiate an Info object\n\n Raises\n ------\n ValueError\n If io is not of the correct type.\n \"\"\"\n if self.frozen:\n raise ValueError(\"IO.add: list is frozen.\")\n io = (\n self.cls(name=name, info=info, static=static, **info_kwargs)\n if io is None\n else io\n )\n if not isinstance(io, self.icls):\n raise ValueError(f\"IO.add: {self.name} is not of type {self.iname}\")\n if io.name in self._dict:\n raise ValueError(f\"IO.add: {self.name} '{io.name}' already exists.\")\n self._dict[io.name] = io"}, {"class_start_lineno": 30, "class_end_lineno": 90, "func_start_lineno": 71, "func_end_lineno": 87, "func_code": " def compatible_with(self, other, check_location=True):\n \"\"\"\n Check for compatibility with other Grid.\n\n Parameters\n ----------\n other : instance of Grid\n Other grid to compatibility with.\n check_location : bool, optional\n Whether to check location for equality, by default True\n\n Returns\n -------\n bool\n compatibility\n \"\"\"\n return isinstance(other, NoGrid) and self.data_shape == other.data_shape"}, {"class_start_lineno": 1, "class_end_lineno": 378, "func_start_lineno": 364, "func_end_lineno": 378, "func_code": "def mask_specified(mask):\n \"\"\"\n Determine whether given mask selection indicates a masked array.\n\n Parameters\n ----------\n mask : :any:`Mask` value or valid boolean mask for :any:`MaskedArray`\n mask to check\n\n Returns\n -------\n bool\n False if mask is Mask.FLEX or Mask.NONE, True otherwise\n \"\"\"\n return not any(mask is val for val in list(Mask))"}, {"class_start_lineno": 22, "class_end_lineno": 248, "func_start_lineno": 87, "func_end_lineno": 89, "func_code": " def mask(self):\n \"\"\"Mask or ndarray: data mask.\"\"\"\n return self._mask"}, {"class_start_lineno": 22, "class_end_lineno": 248, "func_start_lineno": 157, "func_end_lineno": 201, "func_code": " def accepts(self, incoming, fail_info, incoming_donwstream=False):\n \"\"\"\n Tests whether this info can accept/is compatible with an incoming info.\n\n Tested attributes are: \"grid\", \"mask\" and \"units\"\n\n Parameters\n ----------\n incoming : Info\n Incoming/source info to check. This is the info from upstream.\n fail_info : dict\n Dictionary that will be filled with failed properties; name: (source, target).\n incoming_donwstream : bool, optional\n Whether the incoming info is from downstream data. Default: False\n\n Returns\n -------\n bool\n Whether the incoming info is accepted\n \"\"\"\n if not isinstance(incoming, Info):\n fail_info[\"type\"] = (incoming.__class__, self.__class__)\n return False\n\n success = True\n if self.grid is not None and not self.grid.compatible_with(incoming.grid):\n if not (incoming_donwstream and incoming.grid is None):\n fail_info[\"grid\"] = (incoming.grid, self.grid)\n success = False\n\n if self.mask is not None and not masks_compatible(\n self.mask, incoming.mask, incoming_donwstream, self.grid, incoming.grid\n ):\n if not (incoming_donwstream and incoming.mask is None):\n fail_info[\"mask\"] = (incoming.mask, self.mask)\n success = False\n\n u1_none = (u1 := self.units) is None\n u2_none = (u2 := incoming.units) is None\n if not u1_none and (u2_none or not compatible_units(u1, u2)):\n if not (incoming_donwstream and u2_none):\n fail_info[\"units\"] = (u2, u1)\n success = False\n\n return success"}], "type": ["function_empty"], "node": ["finam.sdk.output.Output.push_info", "finam.sdk.output.Output.__init__", "finam.sdk.component.IOList.add", "finam.data.grid_spec.NoGrid.compatible_with", "finam.data.tools.mask.mask_specified", "finam.data.tools.info.Info.mask", "finam.data.tools.info.Info.accepts"], "language": "Python", "toolfunc_count": 5, "func_count": 5, "pytest_info": {"total_num": 46, "base_passed_num": 7}} {"id": ["finam.src.finam.sdk.output.Output::push_info", "finam.src.finam.sdk.component.IOList::add", "finam.src.finam.data.tools.mask.mask_specified", "finam.src.finam.data.tools.mask.masks_compatible", "finam.src.finam.data.tools.info.Info::accepts"], "project": "finam", "origin_file": ["finam/sdk/output.py", "finam/sdk/output.py", "finam/sdk/component.py", "finam/data/tools/mask.py", "finam/data/tools/info.py", "finam/data/tools/mask.py", "finam/data/tools/info.py"], "test_list": ["tests/components/test_control.py", "tests/components/test_parametric.py", "tests/core/test_units.py"], "prob_info": [{"class_start_lineno": 25, "class_end_lineno": 461, "func_start_lineno": 204, "func_end_lineno": 216, "func_code": " def push_info(self, info):\n \"\"\"Push data info into the output.\n\n Parameters\n ----------\n info : :class:`.Info`\n Delivered data info\n \"\"\"\n self.logger.trace(\"push info\")\n if not isinstance(info, Info):\n with ErrorLogger(self.logger):\n raise FinamMetaDataError(\"Metadata must be of type Info\")\n self._output_info = info"}, {"class_start_lineno": 25, "class_end_lineno": 461, "func_start_lineno": 28, "func_end_lineno": 53, "func_code": " def __init__(self, name=None, info=None, static=False, **info_kwargs):\n Loggable.__init__(self)\n self._targets = []\n self.data = []\n self._output_info = None\n self.base_logger_name = None\n if name is None:\n raise ValueError(\"Output: needs a name.\")\n self._name = name\n self._static = static\n\n if info_kwargs:\n if info is not None:\n raise ValueError(\"Output: can't use **kwargs in combination with info\")\n info = Info(**info_kwargs)\n if info is not None:\n self.push_info(info)\n\n self._connected_inputs = {}\n self._out_infos_exchanged = 0\n\n self._time = None\n self._mem_limit = None\n self._mem_location = None\n self._total_mem = 0\n self._mem_counter = 0"}, {"class_start_lineno": 572, "class_end_lineno": 711, "func_start_lineno": 602, "func_end_lineno": 635, "func_code": " def add(self, io=None, *, name=None, info=None, static=False, **info_kwargs):\n \"\"\"\n Add a new IO object either directly ob by attributes.\n\n Parameters\n ----------\n io : :class:`.IInput` or :class:`.IOutput`, optional\n IO object to add, by default None\n name : str, optional\n Name of the new IO object to add, by default None\n info : :class:`.Info`, optional\n Info of the new IO object to add, by default None\n static : bool, optional\n Whether the new IO object in static, by default False\n **info_kwargs\n Optional keyword arguments to instantiate an Info object\n\n Raises\n ------\n ValueError\n If io is not of the correct type.\n \"\"\"\n if self.frozen:\n raise ValueError(\"IO.add: list is frozen.\")\n io = (\n self.cls(name=name, info=info, static=static, **info_kwargs)\n if io is None\n else io\n )\n if not isinstance(io, self.icls):\n raise ValueError(f\"IO.add: {self.name} is not of type {self.iname}\")\n if io.name in self._dict:\n raise ValueError(f\"IO.add: {self.name} '{io.name}' already exists.\")\n self._dict[io.name] = io"}, {"class_start_lineno": 1, "class_end_lineno": 378, "func_start_lineno": 364, "func_end_lineno": 378, "func_code": "def mask_specified(mask):\n \"\"\"\n Determine whether given mask selection indicates a masked array.\n\n Parameters\n ----------\n mask : :any:`Mask` value or valid boolean mask for :any:`MaskedArray`\n mask to check\n\n Returns\n -------\n bool\n False if mask is Mask.FLEX or Mask.NONE, True otherwise\n \"\"\"\n return not any(mask is val for val in list(Mask))"}, {"class_start_lineno": 22, "class_end_lineno": 248, "func_start_lineno": 87, "func_end_lineno": 89, "func_code": " def mask(self):\n \"\"\"Mask or ndarray: data mask.\"\"\"\n return self._mask"}, {"class_start_lineno": 1, "class_end_lineno": 378, "func_start_lineno": 243, "func_end_lineno": 285, "func_code": "def masks_compatible(\n this, incoming, incoming_donwstream, this_grid=None, incoming_grid=None\n):\n \"\"\"\n Check if an incoming mask is compatible with a given mask.\n\n Parameters\n ----------\n this : :any:`Mask` value or valid boolean mask for :any:`MaskedArray` or None\n mask specification to check against\n incoming : :any:`Mask` value or valid boolean mask for :any:`MaskedArray` or None\n incoming mask to check for compatibility\n incoming_donwstream : bool\n Whether the incoming mask is from downstream data\n this_grid : Grid or NoGrid or None, optional\n grid for first mask (to check shape and value equality)\n incoming_grid : Grid or NoGrid or None, optional\n grid for second mask (to check shape and value equality)\n\n Returns\n -------\n bool\n mask compatibility\n \"\"\"\n if incoming_donwstream:\n upstream, downstream = this, incoming\n up_grid, down_grid = this_grid, incoming_grid\n else:\n upstream, downstream = incoming, this\n up_grid, down_grid = incoming_grid, this_grid\n # None is incompatible\n if upstream is None:\n return False\n # Mask.FLEX accepts anything, Mask.NONE only Mask.NONE\n if not mask_specified(downstream):\n if not mask_specified(upstream):\n return downstream == Mask.FLEX or upstream == Mask.NONE\n return downstream == Mask.FLEX\n # if mask is specified, upstream mask must also be specified\n if not mask_specified(upstream):\n return False\n # if both mask given, compare them\n return masks_equal(downstream, upstream, down_grid, up_grid)"}, {"class_start_lineno": 22, "class_end_lineno": 248, "func_start_lineno": 157, "func_end_lineno": 201, "func_code": " def accepts(self, incoming, fail_info, incoming_donwstream=False):\n \"\"\"\n Tests whether this info can accept/is compatible with an incoming info.\n\n Tested attributes are: \"grid\", \"mask\" and \"units\"\n\n Parameters\n ----------\n incoming : Info\n Incoming/source info to check. This is the info from upstream.\n fail_info : dict\n Dictionary that will be filled with failed properties; name: (source, target).\n incoming_donwstream : bool, optional\n Whether the incoming info is from downstream data. Default: False\n\n Returns\n -------\n bool\n Whether the incoming info is accepted\n \"\"\"\n if not isinstance(incoming, Info):\n fail_info[\"type\"] = (incoming.__class__, self.__class__)\n return False\n\n success = True\n if self.grid is not None and not self.grid.compatible_with(incoming.grid):\n if not (incoming_donwstream and incoming.grid is None):\n fail_info[\"grid\"] = (incoming.grid, self.grid)\n success = False\n\n if self.mask is not None and not masks_compatible(\n self.mask, incoming.mask, incoming_donwstream, self.grid, incoming.grid\n ):\n if not (incoming_donwstream and incoming.mask is None):\n fail_info[\"mask\"] = (incoming.mask, self.mask)\n success = False\n\n u1_none = (u1 := self.units) is None\n u2_none = (u2 := incoming.units) is None\n if not u1_none and (u2_none or not compatible_units(u1, u2)):\n if not (incoming_donwstream and u2_none):\n fail_info[\"units\"] = (u2, u1)\n success = False\n\n return success"}], "type": ["function_empty"], "node": ["finam.sdk.output.Output.push_info", "finam.sdk.output.Output.__init__", "finam.sdk.component.IOList.add", "finam.data.tools.mask.mask_specified", "finam.data.tools.info.Info.mask", "finam.data.tools.mask.masks_compatible", "finam.data.tools.info.Info.accepts"], "language": "Python", "toolfunc_count": 5, "func_count": 5, "pytest_info": {"total_num": 16, "base_passed_num": 1}} {"id": ["finam.src.finam.data.grid_tools.gen_axes", "finam.src.finam.data.grid_spec.EsriGrid::to_uniform", "finam.src.finam.data.grid_tools.prepare_vtk_data", "finam.src.finam.data.grid_tools.prepare_vtk_kwargs", "finam.src.finam.data.grid_spec.UniformGrid::export_vtk"], "project": "finam", "origin_file": ["finam/data/grid_tools.py", "finam/data/grid_spec.py", "finam/data/grid_spec.py", "finam/data/grid_tools.py", "finam/data/grid_tools.py", "finam/data/grid_spec.py"], "test_list": ["tests/data/test_grid_spec.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 526, "func_start_lineno": 78, "func_end_lineno": 107, "func_code": "def gen_axes(dims, spacing, origin, axes_increase=None):\n \"\"\"\n Generate uniform axes.\n\n Parameters\n ----------\n dims : iterable\n Dimensions of the uniform grid for each direction.\n spacing : iterable\n Spacing of the uniform in each dimension. Must be positive.\n origin : iterable\n Origin of the uniform grid.\n axes_increase : arraylike or None, optional\n False to indicate a bottom up axis (in xyz order), by default None\n\n Returns\n -------\n list of np.ndarray\n Axes of the uniform grid.\n \"\"\"\n if axes_increase is None:\n axes_increase = np.full(len(dims), True, dtype=bool)\n if len(axes_increase) != len(dims):\n raise ValueError(\"gen_axes: wrong length of 'axes_increase'\")\n axes = []\n for i, d in enumerate(dims):\n axes.append(np.arange(d) * spacing[i] + origin[i])\n if not axes_increase[i]:\n axes[i] = axes[i][::-1]\n return axes"}, {"class_start_lineno": 236, "class_end_lineno": 364, "func_start_lineno": 267, "func_end_lineno": 296, "func_code": " def __init__(\n self,\n dims,\n spacing=(1.0, 1.0, 1.0),\n origin=(0.0, 0.0, 0.0),\n data_location=Location.CELLS,\n order=\"F\",\n axes_reversed=False,\n axes_increase=None,\n axes_attributes=None,\n axes_names=None,\n crs=None,\n ):\n # at most 3 axes\n dims = tuple(dims)[:3]\n self.spacing = tuple(spacing)[: len(dims)]\n if len(self.spacing) < len(dims):\n raise ValueError(\"UniformGrid: wrong length of 'spacing'\")\n self.origin = tuple(origin)[: len(dims)]\n if len(self.origin) < len(dims):\n raise ValueError(\"UniformGrid: wrong length of 'origin'\")\n super().__init__(\n axes=gen_axes(dims, self.spacing, self.origin, axes_increase),\n data_location=data_location,\n order=order,\n axes_reversed=axes_reversed,\n axes_attributes=axes_attributes,\n axes_names=axes_names,\n crs=crs,\n )"}, {"class_start_lineno": 367, "class_end_lineno": 471, "func_start_lineno": 451, "func_end_lineno": 471, "func_code": " def to_uniform(self):\n \"\"\"\n Cast grid to an uniform grid.\n\n Returns\n -------\n UniformGrid\n Grid as uniform grid.\n \"\"\"\n return UniformGrid(\n dims=self.dims,\n spacing=self.spacing,\n origin=self.origin,\n data_location=self.data_location,\n order=self.order,\n axes_reversed=self.axes_reversed,\n axes_increase=self.axes_increase,\n axes_attributes=self.axes_attributes,\n axes_names=self.axes_names,\n crs=self.crs,\n )"}, {"class_start_lineno": 1, "class_end_lineno": 526, "func_start_lineno": 332, "func_end_lineno": 363, "func_code": "def prepare_vtk_data(\n data, axes_reversed=False, axes_increase=None, flat=False, order=\"F\"\n):\n \"\"\"\n Prepare data dictionary for VTK export.\n\n Parameters\n ----------\n data : dict or None\n Dictionary containing data arrays by name.\n axes_reversed : bool, optional\n Indicate reversed axes order for the associated data, by default False\n axes_increase : arraylike or None, optional\n False to indicate a bottom up axis (xyz order), by default None\n flat : bool, optional\n True to flatten data, by default False\n order : str, optional\n Point and cell ordering.\n Either Fortran-like (\"F\") or C-like (\"C\"), by default \"F\"\n\n Returns\n -------\n dict or None\n Prepared data.\n \"\"\"\n if data is not None:\n data = dict(data)\n for name, value in data.items():\n data[name] = np.ascontiguousarray(\n _prepare(value, axes_reversed, axes_increase, flat, order)\n )\n return data"}, {"class_start_lineno": 1, "class_end_lineno": 526, "func_start_lineno": 295, "func_end_lineno": 329, "func_code": "def prepare_vtk_kwargs(data_location, data, cell_data, point_data, field_data):\n \"\"\"\n Prepare keyword arguments for evtk routines.\n\n Parameters\n ----------\n data_location : Location\n Data location in the grid, by default Location.CELLS\n data : dict or None\n Data in the corresponding shape given by name\n cell_data : dict or None\n Additional cell data\n point_data : dict or None\n Additional point data\n field_data : dict or None\n Additional field data\n\n Returns\n -------\n dict\n Keyword arguments.\n \"\"\"\n cdat = data_location == Location.CELLS\n kw = {\"cellData\": None, \"pointData\": None, \"fieldData\": None}\n kw[\"cellData\" if cdat else \"pointData\"] = data\n if kw[\"cellData\"]:\n kw[\"cellData\"].update(cell_data if cell_data is not None else {})\n else:\n kw[\"cellData\"] = cell_data\n if kw[\"pointData\"]:\n kw[\"pointData\"].update(point_data if point_data is not None else {})\n else:\n kw[\"pointData\"] = point_data\n kw[\"fieldData\"] = field_data\n return kw"}, {"class_start_lineno": 236, "class_end_lineno": 364, "func_start_lineno": 298, "func_end_lineno": 342, "func_code": " def export_vtk(\n self,\n path,\n data=None,\n cell_data=None,\n point_data=None,\n field_data=None,\n mesh_type=\"uniform\",\n ):\n \"\"\"\n Export grid and data to a VTK file.\n\n Parameters\n ----------\n path : pathlike\n File path.\n Suffix will be replaced according to mesh type (.vti, .vtr, .vtu)\n data : dict or None, optional\n Data in the corresponding shape given by name, by default None\n cell_data : dict or None, optional\n Additional cell data, by default None\n point_data : dict or None, optional\n Additional point data, by default None\n field_data : dict or None, optional\n Additional field data, by default None\n mesh_type : str, optional\n Mesh type (\"uniform\"/\"structured\"/\"unstructured\"),\n by default \"structured\"\n\n Raises\n ------\n ValueError\n If mesh type is not supported.\n \"\"\"\n if mesh_type != \"uniform\":\n super().export_vtk(path, data, cell_data, point_data, field_data, mesh_type)\n else:\n data = prepare_vtk_data(data, self.axes_reversed, self.axes_increase)\n kw = prepare_vtk_kwargs(\n self.data_location, data, cell_data, point_data, field_data\n )\n path = str(Path(path).with_suffix(\"\"))\n origin = self.origin + (0.0,) * (3 - self.dim)\n spacing = self.spacing + (0.0,) * (3 - self.dim)\n imageToVTK(path, origin, spacing, **kw)"}], "type": ["function_empty", "TDD"], "node": ["finam.data.grid_tools.gen_axes", "finam.data.grid_spec.UniformGrid.__init__", "finam.data.grid_spec.EsriGrid.to_uniform", "finam.data.grid_tools.prepare_vtk_data", "finam.data.grid_tools.prepare_vtk_kwargs", "finam.data.grid_spec.UniformGrid.export_vtk"], "language": "Python", "toolfunc_count": 2, "func_count": 5, "pytest_info": {"total_num": 10, "base_passed_num": 2}} {"id": ["skfolio.src.skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.src.skfolio.datasets._base.load_sp500_dataset", "skfolio.src.skfolio.utils.stats.assert_is_square", "skfolio.src.skfolio.utils.stats.assert_is_symmetric", "skfolio.src.skfolio.utils.stats.assert_is_distance"], "project": "skfolio", "origin_file": ["skfolio/datasets/_base.py", "skfolio/datasets/_base.py", "skfolio/utils/stats.py", "skfolio/utils/stats.py", "skfolio/utils/stats.py"], "test_list": ["tests/test_cluster/test_hierarchical.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 71, "func_end_lineno": 113, "func_code": "def load_gzip_compressed_csv_data(\n data_filename: str,\n data_module: str = DATA_MODULE,\n encoding=\"utf-8\",\n datetime_index: bool = True,\n) -> pd.DataFrame:\n \"\"\"Load gzip-compressed csv files with `importlib.resources`.\n\n 1) Open resource file with `importlib.resources.open_binary`\n 2) Decompress csv file with `gzip.open`\n 3) Load decompressed data with `pd.read_csv`\n\n Parameters\n ----------\n data_filename : str\n Name of gzip-compressed csv file (`'*.csv.gz'`) to be loaded from\n `data_module/data_file_name`. For example `'SPX500.csv.gz'`.\n\n data_module : str or module, default='skfolio.datasets.data'\n Module where data lives. The default is `'skfolio.datasets.data'`.\n\n encoding : str, default=\"utf-8\"\n Name of the encoding that the gzip-decompressed file will be\n decoded with. The default is 'utf-8'.\n\n datetime_index: bool, default=True\n If this is set to True, the DataFrame index is converted to datetime with\n format=\"%Y-%m-%d\".\n The default is `True`.\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n DataFrame with each row representing one observation and each column\n representing the asset price of a given observation.\n \"\"\"\n path = resources.files(data_module).joinpath(data_filename)\n with path.open(\"rb\") as compressed_file:\n compressed_file = gzip.open(compressed_file, mode=\"rt\", encoding=encoding)\n df = pd.read_csv(compressed_file, sep=\",\", index_col=0)\n if datetime_index:\n df.index = pd.to_datetime(df.index, format=\"%Y-%m-%d\")\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 168, "func_end_lineno": 204, "func_code": "def load_sp500_dataset() -> pd.DataFrame:\n \"\"\"Load the prices of 20 assets from the S&P 500 Index composition.\n\n This dataset is composed of the daily prices of 20 assets from the S&P 500\n composition starting from 1990-01-02 up to 2022-12-28.\n\n The data comes from the Yahoo public API.\n The price is the adjusted close which is the closing price after adjustments for\n all applicable splits and dividend distributions.\n The adjustment uses appropriate split and dividend multipliers, adhering to\n the Center for Research in Security Prices (CRSP) standards.\n\n ============== ==================\n Observations 8313\n Assets 20\n ============== ==================\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n Prices DataFrame\n\n Examples\n --------\n >>> from skfolio.datasets import load_sp500_dataset\n >>> prices = load_sp500_dataset()\n >>> prices.head()\n AAPL AMD BAC ... UNH WMT XOM\n 1990-01-02 0.332589 4.1250 11.65625 ... 0.382813 5.890625 12.5000\n 1990-01-03 0.334821 4.0000 11.75000 ... 0.375000 5.890625 12.3750\n 1990-01-04 0.335938 3.9375 11.50000 ... 0.371094 5.859375 12.2500\n 1990-01-05 0.337054 3.8125 11.25000 ... 0.355469 5.796875 12.1875\n 1990-01-08 0.339286 3.8125 11.31250 ... 0.347656 5.875000 12.3750\n \"\"\"\n data_filename = \"sp500_dataset.csv.gz\"\n df = load_gzip_compressed_csv_data(data_filename)\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 577, "func_start_lineno": 208, "func_end_lineno": 221, "func_code": "def assert_is_square(x: np.ndarray) -> None:\n \"\"\"Raises an error if the matrix is not square.\n\n Parameters\n ----------\n x : ndarray of shape (n, n)\n The matrix.\n\n Raises\n ------\n ValueError: if the matrix is not square.\n \"\"\"\n if x.ndim != 2 or x.shape[0] != x.shape[1]:\n raise ValueError(\"The matrix must be square\")"}, {"class_start_lineno": 1, "class_end_lineno": 577, "func_start_lineno": 224, "func_end_lineno": 238, "func_code": "def assert_is_symmetric(x: np.ndarray) -> None:\n \"\"\"Raises an error if the matrix is not symmetric.\n\n Parameters\n ----------\n x : ndarray of shape (n, m)\n The matrix.\n\n Raises\n ------\n ValueError: if the matrix is not symmetric.\n \"\"\"\n assert_is_square(x)\n if not np.allclose(x, x.T):\n raise ValueError(\"The matrix must be symmetric\")"}, {"class_start_lineno": 1, "class_end_lineno": 577, "func_start_lineno": 241, "func_end_lineno": 257, "func_code": "def assert_is_distance(x: np.ndarray) -> None:\n \"\"\"Raises an error if the matrix is not a distance matrix.\n\n Parameters\n ----------\n x : ndarray of shape (n, n)\n The matrix.\n\n Raises\n ------\n ValueError: if the matrix is a distance matrix.\n \"\"\"\n assert_is_symmetric(x)\n if not np.allclose(np.diag(x), np.zeros(x.shape[0]), atol=1e-5):\n raise ValueError(\n \"The distance matrix must have diagonal elements close to zeros\"\n )"}], "type": ["function_empty"], "node": ["skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.datasets._base.load_sp500_dataset", "skfolio.utils.stats.assert_is_square", "skfolio.utils.stats.assert_is_symmetric", "skfolio.utils.stats.assert_is_distance"], "language": "Python", "toolfunc_count": 5, "func_count": 5, "pytest_info": {"total_num": 65, "base_passed_num": 0}} {"id": ["skfolio.src.skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.src.skfolio.datasets._base.load_sp500_dataset", "skfolio.src.skfolio.utils.stats.assert_is_square", "skfolio.src.skfolio.utils.stats.assert_is_symmetric", "skfolio.src.skfolio.utils.stats.cov_nearest"], "project": "skfolio", "origin_file": ["skfolio/datasets/_base.py", "skfolio/datasets/_base.py", "skfolio/utils/stats.py", "skfolio/utils/stats.py", "skfolio/utils/stats.py"], "test_list": ["tests/test_distance/test_distance.py", "tests/test_metrics/test_scorer.py", "tests/test_moment/test_expected_returns/test_expected_returns.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 71, "func_end_lineno": 113, "func_code": "def load_gzip_compressed_csv_data(\n data_filename: str,\n data_module: str = DATA_MODULE,\n encoding=\"utf-8\",\n datetime_index: bool = True,\n) -> pd.DataFrame:\n \"\"\"Load gzip-compressed csv files with `importlib.resources`.\n\n 1) Open resource file with `importlib.resources.open_binary`\n 2) Decompress csv file with `gzip.open`\n 3) Load decompressed data with `pd.read_csv`\n\n Parameters\n ----------\n data_filename : str\n Name of gzip-compressed csv file (`'*.csv.gz'`) to be loaded from\n `data_module/data_file_name`. For example `'SPX500.csv.gz'`.\n\n data_module : str or module, default='skfolio.datasets.data'\n Module where data lives. The default is `'skfolio.datasets.data'`.\n\n encoding : str, default=\"utf-8\"\n Name of the encoding that the gzip-decompressed file will be\n decoded with. The default is 'utf-8'.\n\n datetime_index: bool, default=True\n If this is set to True, the DataFrame index is converted to datetime with\n format=\"%Y-%m-%d\".\n The default is `True`.\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n DataFrame with each row representing one observation and each column\n representing the asset price of a given observation.\n \"\"\"\n path = resources.files(data_module).joinpath(data_filename)\n with path.open(\"rb\") as compressed_file:\n compressed_file = gzip.open(compressed_file, mode=\"rt\", encoding=encoding)\n df = pd.read_csv(compressed_file, sep=\",\", index_col=0)\n if datetime_index:\n df.index = pd.to_datetime(df.index, format=\"%Y-%m-%d\")\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 168, "func_end_lineno": 204, "func_code": "def load_sp500_dataset() -> pd.DataFrame:\n \"\"\"Load the prices of 20 assets from the S&P 500 Index composition.\n\n This dataset is composed of the daily prices of 20 assets from the S&P 500\n composition starting from 1990-01-02 up to 2022-12-28.\n\n The data comes from the Yahoo public API.\n The price is the adjusted close which is the closing price after adjustments for\n all applicable splits and dividend distributions.\n The adjustment uses appropriate split and dividend multipliers, adhering to\n the Center for Research in Security Prices (CRSP) standards.\n\n ============== ==================\n Observations 8313\n Assets 20\n ============== ==================\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n Prices DataFrame\n\n Examples\n --------\n >>> from skfolio.datasets import load_sp500_dataset\n >>> prices = load_sp500_dataset()\n >>> prices.head()\n AAPL AMD BAC ... UNH WMT XOM\n 1990-01-02 0.332589 4.1250 11.65625 ... 0.382813 5.890625 12.5000\n 1990-01-03 0.334821 4.0000 11.75000 ... 0.375000 5.890625 12.3750\n 1990-01-04 0.335938 3.9375 11.50000 ... 0.371094 5.859375 12.2500\n 1990-01-05 0.337054 3.8125 11.25000 ... 0.355469 5.796875 12.1875\n 1990-01-08 0.339286 3.8125 11.31250 ... 0.347656 5.875000 12.3750\n \"\"\"\n data_filename = \"sp500_dataset.csv.gz\"\n df = load_gzip_compressed_csv_data(data_filename)\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 577, "func_start_lineno": 208, "func_end_lineno": 221, "func_code": "def assert_is_square(x: np.ndarray) -> None:\n \"\"\"Raises an error if the matrix is not square.\n\n Parameters\n ----------\n x : ndarray of shape (n, n)\n The matrix.\n\n Raises\n ------\n ValueError: if the matrix is not square.\n \"\"\"\n if x.ndim != 2 or x.shape[0] != x.shape[1]:\n raise ValueError(\"The matrix must be square\")"}, {"class_start_lineno": 1, "class_end_lineno": 577, "func_start_lineno": 224, "func_end_lineno": 238, "func_code": "def assert_is_symmetric(x: np.ndarray) -> None:\n \"\"\"Raises an error if the matrix is not symmetric.\n\n Parameters\n ----------\n x : ndarray of shape (n, m)\n The matrix.\n\n Raises\n ------\n ValueError: if the matrix is not symmetric.\n \"\"\"\n assert_is_square(x)\n if not np.allclose(x, x.T):\n raise ValueError(\"The matrix must be symmetric\")"}, {"class_start_lineno": 1, "class_end_lineno": 577, "func_start_lineno": 308, "func_end_lineno": 400, "func_code": "def cov_nearest(\n cov: np.ndarray,\n higham: bool = False,\n higham_max_iteration: int = 100,\n warn: bool = False,\n):\n \"\"\"Compute the nearest covariance matrix that is positive definite and with a\n cholesky decomposition than can be computed. The variance is left unchanged.\n A covariance matrix that is not positive definite often occurs in high\n dimensional problems. It can be due to multicollinearity, floating-point\n inaccuracies, or when the number of observations is smaller than the number of\n assets.\n\n First, it converts the covariance matrix to a correlation matrix.\n Then, it finds the nearest correlation matrix and converts it back to a covariance\n matrix using the initial standard deviation.\n\n Cholesky decomposition can fail for symmetric positive definite (SPD) matrix due\n to floating point error and inversely, Cholesky decomposition can success for\n non-SPD matrix. Therefore, we need to test for both. We always start by testing\n for Cholesky decomposition which is significantly faster than checking for positive\n eigenvalues.\n\n Parameters\n ----------\n cov : ndarray of shape (n, n)\n Covariance matrix.\n\n higham : bool, default=False\n If this is set to True, the Higham & Nick (2002) algorithm [1]_ is used,\n otherwise the eigenvalues are clipped to threshold above zeros (1e-13).\n The default (`False`) is to use the clipping method as the Higham & Nick\n algorithm can be slow for large datasets.\n\n higham_max_iteration : int, default=100\n Maximum number of iteration of the Higham & Nick (2002) algorithm.\n The default value is `100`.\n\n warn : bool, default=False\n If this is set to True, a user warning is emitted when the covariance matrix\n is not positive definite and replaced by the nearest. The default is False.\n\n Returns\n -------\n cov : ndarray\n The nearest covariance matrix.\n\n References\n ----------\n .. [1] \"Computing the nearest correlation matrix - a problem from finance\"\n IMA Journal of Numerical Analysis\n Higham & Nick (2002)\n \"\"\"\n assert_is_square(cov)\n assert_is_symmetric(cov)\n\n # Around 100 times faster than checking eigenvalues with np.linalg.eigh\n if is_cholesky_dec(cov) and is_positive_definite(cov):\n return cov\n\n if warn:\n warnings.warn(\n \"The covariance matrix is not positive definite. \"\n f\"The {'Higham' if higham else 'Clipping'} algorithm will be used to find \"\n \"the nearest positive definite covariance.\",\n stacklevel=2,\n )\n corr, std = cov_to_corr(cov)\n\n if higham:\n eps = np.finfo(np.float64).eps * 5\n diff = np.zeros(corr.shape)\n x = corr.copy()\n for _ in range(higham_max_iteration):\n x_adj = x - diff\n eig_vals, eig_vecs = np.linalg.eigh(x_adj)\n x = eig_vecs * np.maximum(eig_vals, eps) @ eig_vecs.T\n diff = x - x_adj\n np.fill_diagonal(x, 1)\n cov = corr_to_cov(x, std)\n if is_cholesky_dec(cov) and is_positive_definite(cov):\n break\n else:\n raise ValueError(\"Unable to find the nearest positive definite matrix\")\n else:\n eig_vals, eig_vecs = np.linalg.eigh(corr)\n # Clipping the eigenvalues with a value smaller than 1e-13 can cause scipy to\n # consider the matrix non-psd is some corner cases (see test/test_stats.py)\n x = eig_vecs * np.maximum(eig_vals, _CLIPPING_VALUE) @ eig_vecs.T\n x, _ = cov_to_corr(x)\n cov = corr_to_cov(x, std)\n\n return cov"}], "type": ["function_empty"], "node": ["skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.datasets._base.load_sp500_dataset", "skfolio.utils.stats.assert_is_square", "skfolio.utils.stats.assert_is_symmetric", "skfolio.utils.stats.cov_nearest"], "language": "Python", "toolfunc_count": 5, "func_count": 5, "pytest_info": {"total_num": 26, "base_passed_num": 6}} {"id": ["skfolio.src.skfolio.distribution.copula._clayton._base_sample_scores", "skfolio.src.skfolio.distribution.copula._clayton._neg_log_likelihood", "skfolio.src.skfolio.distribution.copula._utils._apply_copula_rotation", "skfolio.src.skfolio.distribution.copula._utils._apply_margin_swap", "skfolio.src.skfolio.distribution.copula._clayton._base_partial_derivative", "skfolio.src.skfolio.distribution.copula._utils._apply_rotation_partial_derivatives"], "project": "skfolio", "origin_file": ["skfolio/distribution/copula/_clayton.py", "skfolio/distribution/copula/_clayton.py", "skfolio/distribution/copula/_utils.py", "skfolio/distribution/copula/_utils.py", "skfolio/distribution/copula/_clayton.py", "skfolio/distribution/copula/_utils.py"], "test_list": ["tests/test_distribution/test_copula/test_clayton.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 539, "func_start_lineno": 416, "func_end_lineno": 448, "func_code": "def _base_sample_scores(X: np.ndarray, theta: float) -> np.ndarray:\n r\"\"\"Compute the log-likelihood of each sample (log-pdf) under the bivariate Clayton\n copula.\n\n Parameters\n ----------\n X : array-like of shape (n_observations, 2)\n Bivariate samples `(u, v)`, with each component in [0,1].\n\n theta : float\n The dependence parameter (must be greater than 0).\n\n Returns\n -------\n logpdf : ndarray of shape (n_observations,)\n Log-likelihood values for each observation.\n\n Raises\n ------\n ValueError\n If theta is not greater than 0.\n \"\"\"\n if theta <= 0:\n raise ValueError(\"Theta must be greater than 1 for the Clayton copula.\")\n\n x, y = np.log(X).T\n\n log_density = (\n np.log1p(theta)\n - (2.0 + 1.0 / theta) * np.log1p(np.expm1(-theta * x) + np.expm1(-theta * y))\n - (1.0 + theta) * (x + y)\n )\n return log_density"}, {"class_start_lineno": 1, "class_end_lineno": 539, "func_start_lineno": 395, "func_end_lineno": 413, "func_code": "def _neg_log_likelihood(theta: float, X: np.ndarray) -> float:\n \"\"\"Negative log-likelihood function for the Clayton copula.\n\n Parameters\n ----------\n X : array-like of shape (n_observations, 2)\n An array of bivariate inputs `(u, v)` where each row represents a\n bivariate observation. Both `u` and `v` must be in the interval `[0, 1]`,\n having been transformed to uniform marginals.\n\n theta : float\n The dependence parameter (must be greater than 0).\n\n Returns\n -------\n value : float\n The negative log-likelihood value.\n \"\"\"\n return -np.sum(_base_sample_scores(X=X, theta=theta))"}, {"class_start_lineno": 1, "class_end_lineno": 509, "func_start_lineno": 341, "func_end_lineno": 380, "func_code": "def _apply_copula_rotation(X: npt.ArrayLike, rotation: CopulaRotation) -> np.ndarray:\n r\"\"\"Apply a bivariate copula rotation using the standard (clockwise) convention.\n\n The transformations are defined as follows:\n\n - `CopulaRotation.R0` (0°): :math:`(u, v) \\mapsto (u, v)`\n - `CopulaRotation.R90` (90°): :math:`(u, v) \\mapsto (v,\\, 1 - u)`\n - `CopulaRotation.R180` (180°): :math:`(u, v) \\mapsto (1 - u,\\, 1 - v)`\n - `CopulaRotation.R270` (270°): :math:`(u, v) \\mapsto (1 - v,\\, u)`\n\n Parameters\n ----------\n X : array-like of shape (n_observations, 2)\n An array of bivariate inputs `(u, v)` where each row represents a\n bivariate observation.\n\n rotation : CopulaRotation\n The rotation to apply to the copula (default is no rotation).\n\n Returns\n -------\n rotated_X: ndarray of shape (n_observations, 2)\n The rotated data array.\n \"\"\"\n match rotation:\n case CopulaRotation.R0:\n # No rotation\n pass\n case CopulaRotation.R90:\n # (u, v) -> (v, 1 - u)\n X = np.column_stack([X[:, 1], 1.0 - X[:, 0]])\n case CopulaRotation.R180:\n # (u, v) -> (1 - u, 1 - v)\n X = 1.0 - X\n case CopulaRotation.R270:\n # (u, v) -> (1 - v, u)\n X = np.column_stack([1.0 - X[:, 1], X[:, 0]])\n case _:\n raise ValueError(f\"Unsupported rotation: {rotation}\")\n return X"}, {"class_start_lineno": 1, "class_end_lineno": 509, "func_start_lineno": 383, "func_end_lineno": 406, "func_code": "def _apply_margin_swap(X: np.ndarray, first_margin: bool) -> np.ndarray:\n \"\"\"\n Swap the columns of X if first_margin is False.\n\n If first_margin is True, X is returned unchanged; otherwise, the columns\n of X are swapped.\n\n Parameters\n ----------\n X : ndarray of shape (n_observations, 2)\n A 2D array of bivariate inputs (u, v).\n first_margin : bool\n If True, no swap is performed; if False, the columns of X are swapped.\n\n Returns\n -------\n X_swapped : ndarray of shape (n_observations, 2)\n The data array with columns swapped if first_margin is False.\n \"\"\"\n assert X.ndim == 2\n assert X.shape[1] == 2\n if first_margin:\n return X[:, [1, 0]]\n return X"}, {"class_start_lineno": 1, "class_end_lineno": 539, "func_start_lineno": 461, "func_end_lineno": 498, "func_code": "def _base_partial_derivative(\n X: np.ndarray, first_margin: bool, theta: float\n) -> np.ndarray:\n r\"\"\"\n Compute the partial derivative (h-function) for the unrotated Clayton copula.\n\n For Clayton, the copula is defined as:\n\n .. math::\n C(u,v)=\\Bigl(u^{-\\theta}+v^{-\\theta}-1\\Bigr)^{-1/\\theta}.\n\n The partial derivative with respect to v is:\n\n .. math::\n \\frac{\\partial C(u,v)}{\\partial v} = \\Bigl(u^{-\\theta}+v^{-\\theta}-1\\Bigr)^{-1/\\theta-1}\\,v^{-\\theta-1}.\n\n Parameters\n ----------\n X : array-like of shape (n_observations, 2)\n An array of bivariate inputs `(u, v)` with values in [0, 1].\n\n first_margin : bool, default=False\n If True, compute with respect to u (by swapping margins); otherwise\n compute with respect to v.\n\n theta : float\n The dependence parameter (must be > 0).\n\n Returns\n -------\n p : ndarray of shape (n_observations,)\n The computed h-function values.\n \"\"\"\n X = _apply_margin_swap(X, first_margin=first_margin)\n x = np.power(X[:, 0], -theta)\n y = np.power(X[:, 1], theta)\n p = np.power(1.0 + y * (x - 1.0), -(1.0 + 1.0 / theta))\n return p"}, {"class_start_lineno": 1, "class_end_lineno": 509, "func_start_lineno": 452, "func_end_lineno": 509, "func_code": "def _apply_rotation_partial_derivatives(\n func: Callable,\n X: np.ndarray,\n rotation: CopulaRotation,\n first_margin: bool,\n **kwargs,\n) -> np.ndarray:\n \"\"\"\n Apply a copula rotation to X and compute the corresponding partial derivatives.\n\n This function rotates the data X using the specified rotation and then computes\n the partial derivative (h-function) using the provided function. The result is then\n adjusted according to the rotation and the margin of interest.\n\n Parameters\n ----------\n func : Callable\n A function that computes the partial derivative (h-function) given X, the\n margin, and any additional keyword arguments.\n\n X : ndarray of shape (n_observations, 2)\n A 2D array of bivariate inputs.\n\n rotation : CopulaRotation\n The rotation to apply.\n\n first_margin : bool\n If True, compute the partial derivative with respect to the first margin;\n otherwise, compute it with respect to the second margin.\n\n **kwargs\n Additional keyword arguments to pass to the partial derivative function.\n\n Returns\n -------\n z : ndarray of shape (n_observations,)\n The transformed partial derivative values after applying the rotation.\n \"\"\"\n rotated_X = _apply_copula_rotation(X, rotation=rotation)\n\n match rotation:\n case CopulaRotation.R0:\n z = func(X=rotated_X, first_margin=first_margin, **kwargs)\n case CopulaRotation.R90:\n if first_margin:\n z = func(X=rotated_X, first_margin=not first_margin, **kwargs)\n else:\n z = 1 - func(X=rotated_X, first_margin=not first_margin, **kwargs)\n case CopulaRotation.R180:\n z = 1 - func(X=rotated_X, first_margin=first_margin, **kwargs)\n case CopulaRotation.R270:\n if first_margin:\n z = 1 - func(X=rotated_X, first_margin=not first_margin, **kwargs)\n else:\n z = func(X=rotated_X, first_margin=not first_margin, **kwargs)\n case _:\n raise ValueError(f\"Unsupported rotation: {rotation}\")\n return z"}], "type": ["function_empty", "TDD"], "node": ["skfolio.distribution.copula._clayton._base_sample_scores", "skfolio.distribution.copula._clayton._neg_log_likelihood", "skfolio.distribution.copula._utils._apply_copula_rotation", "skfolio.distribution.copula._utils._apply_margin_swap", "skfolio.distribution.copula._clayton._base_partial_derivative", "skfolio.distribution.copula._utils._apply_rotation_partial_derivatives"], "language": "Python", "toolfunc_count": 2, "func_count": 6, "pytest_info": {"total_num": 69, "base_passed_num": 5}} {"id": ["skfolio.src.skfolio.distribution.copula._gaussian._base_sample_scores", "skfolio.src.skfolio.distribution.copula._gaussian._neg_log_likelihood"], "project": "skfolio", "origin_file": ["skfolio/distribution/copula/_gaussian.py", "skfolio/distribution/copula/_gaussian.py"], "test_list": ["tests/test_distribution/test_copula/test_gaussian.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 407, "func_start_lineno": 373, "func_end_lineno": 407, "func_code": "def _base_sample_scores(X: np.ndarray, rho: float) -> np.ndarray:\n \"\"\"Compute the log-likelihood of each sample (log-pdf) under the bivariate\n Gaussian copula model.\n\n Parameters\n ----------\n X : array-like of shape (n_observations, 2)\n An array of bivariate inputs `(u, v)` where each row represents a\n bivariate observation. Both `u` and `v` must be in the interval `[0, 1]`,\n having been transformed to uniform marginals.\n\n rho : float\n Gaussian copula parameter.\n\n Returns\n -------\n density : ndarray of shape (n_observations,)\n The log-likelihood of each sample under the fitted copula.\n\n Raises\n ------\n ValueError\n If rho is not in (-1, 1)\n \"\"\"\n if not (-1.0 <= rho <= 1.0):\n raise ValueError(\"rho must be between -1 and 1.\")\n\n # Inverse CDF (ppf) using stdtrit for better performance\n u_inv, v_inv = sp.ndtri(X).T\n\n # Using np.log1p to avoid loss of precision\n log_density = -0.5 * np.log1p(-(rho**2)) - rho * (\n 0.5 * rho * (u_inv**2 + v_inv**2) - u_inv * v_inv\n ) / (1 - rho**2)\n return log_density"}, {"class_start_lineno": 1, "class_end_lineno": 407, "func_start_lineno": 352, "func_end_lineno": 370, "func_code": "def _neg_log_likelihood(rho: float, X: np.ndarray) -> float:\n \"\"\"Negative log-likelihood function for optimization.\n\n Parameters\n ----------\n X : array-like of shape (n_observations, 2)\n An array of bivariate inputs `(u, v)` where each row represents a\n bivariate observation. Both `u` and `v` must be in the interval `[0, 1]`,\n having been transformed to uniform marginals.\n\n rho : float\n Correlation copula parameter.\n\n Returns\n -------\n value : float\n The negative log-likelihood value.\n \"\"\"\n return -np.sum(_base_sample_scores(X=X, rho=rho))"}], "type": ["function_empty", "TDD"], "node": ["skfolio.distribution.copula._gaussian._base_sample_scores", "skfolio.distribution.copula._gaussian._neg_log_likelihood"], "language": "Python", "toolfunc_count": 1, "func_count": 2, "pytest_info": {"total_num": 38, "base_passed_num": 26}} {"id": ["skfolio.src.skfolio.distribution.copula._gumbel._base_sample_scores", "skfolio.src.skfolio.distribution.copula._gumbel._neg_log_likelihood", "skfolio.src.skfolio.distribution.copula._utils._apply_copula_rotation", "skfolio.src.skfolio.distribution.copula._utils._apply_margin_swap", "skfolio.src.skfolio.distribution.copula._gumbel._base_partial_derivative", "skfolio.src.skfolio.distribution.copula._utils._apply_rotation_partial_derivatives"], "project": "skfolio", "origin_file": ["skfolio/distribution/copula/_gumbel.py", "skfolio/distribution/copula/_gumbel.py", "skfolio/distribution/copula/_utils.py", "skfolio/distribution/copula/_utils.py", "skfolio/distribution/copula/_gumbel.py", "skfolio/distribution/copula/_utils.py"], "test_list": ["tests/test_distribution/test_copula/test_gumbel.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 560, "func_start_lineno": 422, "func_end_lineno": 451, "func_code": "def _base_sample_scores(X: np.ndarray, theta: float) -> np.ndarray:\n r\"\"\"Compute the log-likelihood of each sample (log-pdf) under the bivariate Gumbel\n copula.\n\n Parameters\n ----------\n X : array-like of shape (n_observations, 2)\n Bivariate samples `(u, v)`, with each component in [0,1].\n\n theta : float\n The dependence parameter (must be greater than 1).\n\n Returns\n -------\n logpdf : ndarray of shape (n_observations,)\n Log-likelihood values for each observation.\n \"\"\"\n if theta <= 1:\n raise ValueError(\"Theta must be greater than 1 for the Gumbel copula.\")\n Z = -np.log(X)\n s = np.power(np.power(Z, theta).sum(axis=1), 1 / theta)\n s = np.clip(s, a_min=1e-10, a_max=None)\n log_density = (\n -s\n + np.log(s + theta - 1)\n + (1 - 2 * theta) * np.log(s)\n + (theta - 1) * np.log(Z.prod(axis=1))\n + Z.sum(axis=1)\n )\n return log_density"}, {"class_start_lineno": 1, "class_end_lineno": 560, "func_start_lineno": 401, "func_end_lineno": 419, "func_code": "def _neg_log_likelihood(theta: float, X: np.ndarray) -> float:\n \"\"\"Negative log-likelihood function for the Gumbel copula.\n\n Parameters\n ----------\n X : array-like of shape (n_observations, 2)\n An array of bivariate inputs `(u, v)` where each row represents a\n bivariate observation. Both `u` and `v` must be in the interval [0, 1],\n having been transformed to uniform marginals.\n\n theta : float\n The dependence parameter (must be greater than 1).\n\n Returns\n -------\n value : float\n The negative log-likelihood value.\n \"\"\"\n return -np.sum(_base_sample_scores(X=X, theta=theta))"}, {"class_start_lineno": 1, "class_end_lineno": 509, "func_start_lineno": 341, "func_end_lineno": 380, "func_code": "def _apply_copula_rotation(X: npt.ArrayLike, rotation: CopulaRotation) -> np.ndarray:\n r\"\"\"Apply a bivariate copula rotation using the standard (clockwise) convention.\n\n The transformations are defined as follows:\n\n - `CopulaRotation.R0` (0°): :math:`(u, v) \\mapsto (u, v)`\n - `CopulaRotation.R90` (90°): :math:`(u, v) \\mapsto (v,\\, 1 - u)`\n - `CopulaRotation.R180` (180°): :math:`(u, v) \\mapsto (1 - u,\\, 1 - v)`\n - `CopulaRotation.R270` (270°): :math:`(u, v) \\mapsto (1 - v,\\, u)`\n\n Parameters\n ----------\n X : array-like of shape (n_observations, 2)\n An array of bivariate inputs `(u, v)` where each row represents a\n bivariate observation.\n\n rotation : CopulaRotation\n The rotation to apply to the copula (default is no rotation).\n\n Returns\n -------\n rotated_X: ndarray of shape (n_observations, 2)\n The rotated data array.\n \"\"\"\n match rotation:\n case CopulaRotation.R0:\n # No rotation\n pass\n case CopulaRotation.R90:\n # (u, v) -> (v, 1 - u)\n X = np.column_stack([X[:, 1], 1.0 - X[:, 0]])\n case CopulaRotation.R180:\n # (u, v) -> (1 - u, 1 - v)\n X = 1.0 - X\n case CopulaRotation.R270:\n # (u, v) -> (1 - v, u)\n X = np.column_stack([1.0 - X[:, 1], X[:, 0]])\n case _:\n raise ValueError(f\"Unsupported rotation: {rotation}\")\n return X"}, {"class_start_lineno": 1, "class_end_lineno": 509, "func_start_lineno": 383, "func_end_lineno": 406, "func_code": "def _apply_margin_swap(X: np.ndarray, first_margin: bool) -> np.ndarray:\n \"\"\"\n Swap the columns of X if first_margin is False.\n\n If first_margin is True, X is returned unchanged; otherwise, the columns\n of X are swapped.\n\n Parameters\n ----------\n X : ndarray of shape (n_observations, 2)\n A 2D array of bivariate inputs (u, v).\n first_margin : bool\n If True, no swap is performed; if False, the columns of X are swapped.\n\n Returns\n -------\n X_swapped : ndarray of shape (n_observations, 2)\n The data array with columns swapped if first_margin is False.\n \"\"\"\n assert X.ndim == 2\n assert X.shape[1] == 2\n if first_margin:\n return X[:, [1, 0]]\n return X"}, {"class_start_lineno": 1, "class_end_lineno": 560, "func_start_lineno": 464, "func_end_lineno": 507, "func_code": "def _base_partial_derivative(\n X: np.ndarray, first_margin: bool, theta: float\n) -> np.ndarray:\n r\"\"\"\n Compute the partial derivative (h-function) for the unrotated Gumbel copula.\n\n For Gumbel, the copula is defined as:\n\n .. math::\n C(u,v)=\\exp\\Bigl(-\\Bigl[(-\\ln u)^{\\theta}+(-\\ln v)^{\\theta}\\Bigr]^{1/\\theta}\\Bigr).\n\n The partial derivative with respect to v is:\n\n .. math::\n \\frac{\\partial C(u,v)}{\\partial v}\n = C(u,v)\\,\\Bigl[(-\\ln u)^{\\theta}+(-\\ln v)^{\\theta}\\Bigr]^{\\frac{1}{\\theta}-1}\n \\,(-\\ln v)^{\\theta-1}\\,\\frac{1}{v}.\n\n Parameters\n ----------\n X : array-like of shape (n_observations, 2)\n An array of bivariate inputs `(u, v)` with values in [0, 1].\n\n first_margin : bool, default=False\n If True, compute with respect to u (by swapping margins); otherwise,\n compute with respect to v.\n\n theta : float\n The dependence parameter (must be > 1).\n\n Returns\n -------\n p : ndarray of shape (n_observations,)\n The computed h-function values.\n \"\"\"\n X = _apply_margin_swap(X, first_margin=first_margin)\n _, v = X.T\n x, y = -np.log(X).T\n p = (\n np.exp(-np.power(np.power(x, theta) + np.power(y, theta), 1.0 / theta))\n * np.power(np.power(x / y, theta) + 1.0, 1.0 / theta - 1.0)\n / v\n )\n return p"}, {"class_start_lineno": 1, "class_end_lineno": 509, "func_start_lineno": 452, "func_end_lineno": 509, "func_code": "def _apply_rotation_partial_derivatives(\n func: Callable,\n X: np.ndarray,\n rotation: CopulaRotation,\n first_margin: bool,\n **kwargs,\n) -> np.ndarray:\n \"\"\"\n Apply a copula rotation to X and compute the corresponding partial derivatives.\n\n This function rotates the data X using the specified rotation and then computes\n the partial derivative (h-function) using the provided function. The result is then\n adjusted according to the rotation and the margin of interest.\n\n Parameters\n ----------\n func : Callable\n A function that computes the partial derivative (h-function) given X, the\n margin, and any additional keyword arguments.\n\n X : ndarray of shape (n_observations, 2)\n A 2D array of bivariate inputs.\n\n rotation : CopulaRotation\n The rotation to apply.\n\n first_margin : bool\n If True, compute the partial derivative with respect to the first margin;\n otherwise, compute it with respect to the second margin.\n\n **kwargs\n Additional keyword arguments to pass to the partial derivative function.\n\n Returns\n -------\n z : ndarray of shape (n_observations,)\n The transformed partial derivative values after applying the rotation.\n \"\"\"\n rotated_X = _apply_copula_rotation(X, rotation=rotation)\n\n match rotation:\n case CopulaRotation.R0:\n z = func(X=rotated_X, first_margin=first_margin, **kwargs)\n case CopulaRotation.R90:\n if first_margin:\n z = func(X=rotated_X, first_margin=not first_margin, **kwargs)\n else:\n z = 1 - func(X=rotated_X, first_margin=not first_margin, **kwargs)\n case CopulaRotation.R180:\n z = 1 - func(X=rotated_X, first_margin=first_margin, **kwargs)\n case CopulaRotation.R270:\n if first_margin:\n z = 1 - func(X=rotated_X, first_margin=not first_margin, **kwargs)\n else:\n z = func(X=rotated_X, first_margin=not first_margin, **kwargs)\n case _:\n raise ValueError(f\"Unsupported rotation: {rotation}\")\n return z"}], "type": ["function_empty", "TDD"], "node": ["skfolio.distribution.copula._gumbel._base_sample_scores", "skfolio.distribution.copula._gumbel._neg_log_likelihood", "skfolio.distribution.copula._utils._apply_copula_rotation", "skfolio.distribution.copula._utils._apply_margin_swap", "skfolio.distribution.copula._gumbel._base_partial_derivative", "skfolio.distribution.copula._utils._apply_rotation_partial_derivatives"], "language": "Python", "toolfunc_count": 2, "func_count": 6, "pytest_info": {"total_num": 69, "base_passed_num": 5}} {"id": ["skfolio.src.skfolio.distribution.copula._joe._base_sample_scores", "skfolio.src.skfolio.distribution.copula._joe._neg_log_likelihood", "skfolio.src.skfolio.distribution.copula._utils._apply_copula_rotation", "skfolio.src.skfolio.distribution.copula._utils._apply_margin_swap", "skfolio.src.skfolio.distribution.copula._joe._base_partial_derivative", "skfolio.src.skfolio.distribution.copula._utils._apply_rotation_partial_derivatives"], "project": "skfolio", "origin_file": ["skfolio/distribution/copula/_joe.py", "skfolio/distribution/copula/_joe.py", "skfolio/distribution/copula/_utils.py", "skfolio/distribution/copula/_utils.py", "skfolio/distribution/copula/_joe.py", "skfolio/distribution/copula/_utils.py"], "test_list": ["tests/test_distribution/test_copula/test_joe.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 609, "func_start_lineno": 439, "func_end_lineno": 473, "func_code": "def _base_sample_scores(X: np.ndarray, theta: float) -> np.ndarray:\n \"\"\"Compute the log-likelihood of each sample (log-pdf) under the bivariate\n Joe copula model.\n\n Parameters\n ----------\n X : array-like of shape (n_observations, 2)\n An array of bivariate inputs `(u, v)` where each row represents a\n bivariate observation. Both `u` and `v` must be in the interval `[0, 1]`,\n having been transformed to uniform marginals.\n\n theta : float\n The dependence parameter (must be greater than 1).\n\n Returns\n -------\n density : ndarray of shape (n_observations,)\n The log-likelihood of each sample under the fitted copula.\n\n Raises\n ------\n ValueError\n If rho is not in (-1, 1) or dof is not positive.\n \"\"\"\n if theta <= 1.0:\n raise ValueError(\"Theta must be greater than 1 for the Joe copula.\")\n\n # log-space transformation to improve stability near 0 or 1\n x, y = np.log1p(-X).T\n x_y = x + y\n d = np.exp(x * theta) + np.exp(y * theta) - np.exp(x_y * theta)\n log_density = (\n (1.0 / theta - 2.0) * np.log(d) + x_y * (theta - 1.0) + np.log(theta - 1.0 + d)\n )\n return log_density"}, {"class_start_lineno": 1, "class_end_lineno": 609, "func_start_lineno": 418, "func_end_lineno": 436, "func_code": "def _neg_log_likelihood(theta: float, X: np.ndarray) -> float:\n \"\"\"Negative log-likelihood function for optimization.\n\n Parameters\n ----------\n X : array-like of shape (n_observations, 2)\n An array of bivariate inputs `(u, v)` where each row represents a\n bivariate observation. Both `u` and `v` must be in the interval `[0, 1]`,\n having been transformed to uniform marginals.\n\n theta : float\n The dependence parameter (must be greater than 1).\n\n Returns\n -------\n value : float\n The negative log-likelihood value.\n \"\"\"\n return -np.sum(_base_sample_scores(X=X, theta=theta))"}, {"class_start_lineno": 1, "class_end_lineno": 509, "func_start_lineno": 341, "func_end_lineno": 380, "func_code": "def _apply_copula_rotation(X: npt.ArrayLike, rotation: CopulaRotation) -> np.ndarray:\n r\"\"\"Apply a bivariate copula rotation using the standard (clockwise) convention.\n\n The transformations are defined as follows:\n\n - `CopulaRotation.R0` (0°): :math:`(u, v) \\mapsto (u, v)`\n - `CopulaRotation.R90` (90°): :math:`(u, v) \\mapsto (v,\\, 1 - u)`\n - `CopulaRotation.R180` (180°): :math:`(u, v) \\mapsto (1 - u,\\, 1 - v)`\n - `CopulaRotation.R270` (270°): :math:`(u, v) \\mapsto (1 - v,\\, u)`\n\n Parameters\n ----------\n X : array-like of shape (n_observations, 2)\n An array of bivariate inputs `(u, v)` where each row represents a\n bivariate observation.\n\n rotation : CopulaRotation\n The rotation to apply to the copula (default is no rotation).\n\n Returns\n -------\n rotated_X: ndarray of shape (n_observations, 2)\n The rotated data array.\n \"\"\"\n match rotation:\n case CopulaRotation.R0:\n # No rotation\n pass\n case CopulaRotation.R90:\n # (u, v) -> (v, 1 - u)\n X = np.column_stack([X[:, 1], 1.0 - X[:, 0]])\n case CopulaRotation.R180:\n # (u, v) -> (1 - u, 1 - v)\n X = 1.0 - X\n case CopulaRotation.R270:\n # (u, v) -> (1 - v, u)\n X = np.column_stack([1.0 - X[:, 1], X[:, 0]])\n case _:\n raise ValueError(f\"Unsupported rotation: {rotation}\")\n return X"}, {"class_start_lineno": 1, "class_end_lineno": 509, "func_start_lineno": 383, "func_end_lineno": 406, "func_code": "def _apply_margin_swap(X: np.ndarray, first_margin: bool) -> np.ndarray:\n \"\"\"\n Swap the columns of X if first_margin is False.\n\n If first_margin is True, X is returned unchanged; otherwise, the columns\n of X are swapped.\n\n Parameters\n ----------\n X : ndarray of shape (n_observations, 2)\n A 2D array of bivariate inputs (u, v).\n first_margin : bool\n If True, no swap is performed; if False, the columns of X are swapped.\n\n Returns\n -------\n X_swapped : ndarray of shape (n_observations, 2)\n The data array with columns swapped if first_margin is False.\n \"\"\"\n assert X.ndim == 2\n assert X.shape[1] == 2\n if first_margin:\n return X[:, [1, 0]]\n return X"}, {"class_start_lineno": 1, "class_end_lineno": 609, "func_start_lineno": 517, "func_end_lineno": 546, "func_code": "def _base_partial_derivative(\n X: np.ndarray, first_margin: bool, theta: float\n) -> np.ndarray:\n r\"\"\"Compute the h-function (partial derivative) for the bivariate unrotated\n Joe copula with respect to a specified margin.\n\n Parameters\n ----------\n X : array-like of shape (n_observations, 2)\n An array of bivariate inputs `(u, v)` where each row represents a\n bivariate observation. Both `u` and `v` must be in the interval `[0, 1]`,\n having been transformed to uniform marginals.\n\n first_margin : bool, default=False\n If True, compute the partial derivative with respect to the first\n margin `u`; otherwise, compute the partial derivative with respect to the\n second margin `v`.\n\n theta : float\n The dependence parameter (must be greater than 1).\n\n Returns\n -------\n : ndarray of shape (n_observations,)\n h-function values :math:`h(u \\mid v) \\;=\\; p` for each observation in X.\n \"\"\"\n X = _apply_margin_swap(X, first_margin=first_margin)\n x, y = np.power(1 - X, theta).T\n p = np.power(1 + x / y - x, 1 / theta - 1) * (1.0 - x)\n return p"}, {"class_start_lineno": 1, "class_end_lineno": 509, "func_start_lineno": 452, "func_end_lineno": 509, "func_code": "def _apply_rotation_partial_derivatives(\n func: Callable,\n X: np.ndarray,\n rotation: CopulaRotation,\n first_margin: bool,\n **kwargs,\n) -> np.ndarray:\n \"\"\"\n Apply a copula rotation to X and compute the corresponding partial derivatives.\n\n This function rotates the data X using the specified rotation and then computes\n the partial derivative (h-function) using the provided function. The result is then\n adjusted according to the rotation and the margin of interest.\n\n Parameters\n ----------\n func : Callable\n A function that computes the partial derivative (h-function) given X, the\n margin, and any additional keyword arguments.\n\n X : ndarray of shape (n_observations, 2)\n A 2D array of bivariate inputs.\n\n rotation : CopulaRotation\n The rotation to apply.\n\n first_margin : bool\n If True, compute the partial derivative with respect to the first margin;\n otherwise, compute it with respect to the second margin.\n\n **kwargs\n Additional keyword arguments to pass to the partial derivative function.\n\n Returns\n -------\n z : ndarray of shape (n_observations,)\n The transformed partial derivative values after applying the rotation.\n \"\"\"\n rotated_X = _apply_copula_rotation(X, rotation=rotation)\n\n match rotation:\n case CopulaRotation.R0:\n z = func(X=rotated_X, first_margin=first_margin, **kwargs)\n case CopulaRotation.R90:\n if first_margin:\n z = func(X=rotated_X, first_margin=not first_margin, **kwargs)\n else:\n z = 1 - func(X=rotated_X, first_margin=not first_margin, **kwargs)\n case CopulaRotation.R180:\n z = 1 - func(X=rotated_X, first_margin=first_margin, **kwargs)\n case CopulaRotation.R270:\n if first_margin:\n z = 1 - func(X=rotated_X, first_margin=not first_margin, **kwargs)\n else:\n z = func(X=rotated_X, first_margin=not first_margin, **kwargs)\n case _:\n raise ValueError(f\"Unsupported rotation: {rotation}\")\n return z"}], "type": ["function_empty", "TDD"], "node": ["skfolio.distribution.copula._joe._base_sample_scores", "skfolio.distribution.copula._joe._neg_log_likelihood", "skfolio.distribution.copula._utils._apply_copula_rotation", "skfolio.distribution.copula._utils._apply_margin_swap", "skfolio.distribution.copula._joe._base_partial_derivative", "skfolio.distribution.copula._utils._apply_rotation_partial_derivatives"], "language": "Python", "toolfunc_count": 3, "func_count": 6, "pytest_info": {"total_num": 69, "base_passed_num": 5}} {"id": ["skfolio.src.skfolio.distribution.copula._clayton._base_sample_scores", "skfolio.src.skfolio.distribution.copula._clayton._neg_log_likelihood"], "project": "skfolio", "origin_file": ["skfolio/distribution/copula/_clayton.py", "skfolio/distribution/copula/_clayton.py"], "test_list": ["tests/test_distribution/test_copula/test_selection.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 539, "func_start_lineno": 416, "func_end_lineno": 448, "func_code": "def _base_sample_scores(X: np.ndarray, theta: float) -> np.ndarray:\n r\"\"\"Compute the log-likelihood of each sample (log-pdf) under the bivariate Clayton\n copula.\n\n Parameters\n ----------\n X : array-like of shape (n_observations, 2)\n Bivariate samples `(u, v)`, with each component in [0,1].\n\n theta : float\n The dependence parameter (must be greater than 0).\n\n Returns\n -------\n logpdf : ndarray of shape (n_observations,)\n Log-likelihood values for each observation.\n\n Raises\n ------\n ValueError\n If theta is not greater than 0.\n \"\"\"\n if theta <= 0:\n raise ValueError(\"Theta must be greater than 1 for the Clayton copula.\")\n\n x, y = np.log(X).T\n\n log_density = (\n np.log1p(theta)\n - (2.0 + 1.0 / theta) * np.log1p(np.expm1(-theta * x) + np.expm1(-theta * y))\n - (1.0 + theta) * (x + y)\n )\n return log_density"}, {"class_start_lineno": 1, "class_end_lineno": 539, "func_start_lineno": 395, "func_end_lineno": 413, "func_code": "def _neg_log_likelihood(theta: float, X: np.ndarray) -> float:\n \"\"\"Negative log-likelihood function for the Clayton copula.\n\n Parameters\n ----------\n X : array-like of shape (n_observations, 2)\n An array of bivariate inputs `(u, v)` where each row represents a\n bivariate observation. Both `u` and `v` must be in the interval `[0, 1]`,\n having been transformed to uniform marginals.\n\n theta : float\n The dependence parameter (must be greater than 0).\n\n Returns\n -------\n value : float\n The negative log-likelihood value.\n \"\"\"\n return -np.sum(_base_sample_scores(X=X, theta=theta))"}], "type": ["function_empty", "TDD"], "node": ["skfolio.distribution.copula._clayton._base_sample_scores", "skfolio.distribution.copula._clayton._neg_log_likelihood"], "language": "Python", "toolfunc_count": 1, "func_count": 2, "pytest_info": {"total_num": 4, "base_passed_num": 3}} {"id": ["skfolio.src.skfolio.distribution.copula._student_t._sample_scores", "skfolio.src.skfolio.distribution.copula._student_t._neg_log_likelihood"], "project": "skfolio", "origin_file": ["skfolio/distribution/copula/_student_t.py", "skfolio/distribution/copula/_student_t.py"], "test_list": ["tests/test_distribution/test_copula/test_student_t.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 486, "func_start_lineno": 445, "func_end_lineno": 486, "func_code": "def _sample_scores(X: np.ndarray, rho: float, dof: float) -> np.ndarray:\n \"\"\"Compute the log-likelihood of each sample (log-pdf) under the bivariate\n Gaussian copula model.\n\n Parameters\n ----------\n X : array-like of shape (n_observations, 2)\n An array of bivariate inputs `(u, v)` where each row represents a\n bivariate observation. Both `u` and `v` must be in the interval `[0, 1]`,\n having been transformed to uniform marginals.\n\n rho : float\n Gaussian copula parameter.\n\n Returns\n -------\n density : ndarray of shape (n_observations,)\n The log-likelihood of each sample under the fitted copula.\n\n Raises\n ------\n ValueError\n If rho is not in (-1, 1) or dof is not positive.\n \"\"\"\n if not (-1.0 <= rho <= 1.0):\n raise ValueError(\"rho must be between -1 and 1.\")\n if not 1.0 <= dof <= 50:\n raise ValueError(\"Degrees of freedom `dof` must be between 1 and 50.\")\n\n # Inverse CDF (ppf) using stdtrit for better performance\n x, y = sp.stdtrit(dof, X).T\n\n a = 1.0 - rho**2\n log_density = (\n sp.gammaln((dof + 2.0) / 2.0)\n + sp.gammaln(dof / 2.0)\n - 2.0 * sp.gammaln((dof + 1.0) / 2.0)\n - np.log(a) / 2\n + (dof + 1.0) / 2.0 * (np.log1p(x**2 / dof) + np.log1p(y**2 / dof))\n - (dof + 2.0) / 2.0 * np.log1p((x**2 - 2 * rho * x * y + y**2) / a / dof)\n )\n return log_density"}, {"class_start_lineno": 1, "class_end_lineno": 486, "func_start_lineno": 421, "func_end_lineno": 442, "func_code": "def _neg_log_likelihood(dof: float, rho: float, X: np.ndarray) -> float:\n \"\"\"Negative log-likelihood function for optimization.\n\n Parameters\n ----------\n X : array-like of shape (n_observations, 2)\n An array of bivariate inputs `(u, v)` where each row represents a\n bivariate observation. Both `u` and `v` must be in the interval `[0, 1]`,\n having been transformed to uniform marginals.\n\n rho : float\n Correlation copula parameter.\n\n dof : float\n Degree of freedom copula parameter.\n\n Returns\n -------\n value : float\n The negative log-likelihood value.\n \"\"\"\n return -np.sum(_sample_scores(X=X, rho=rho, dof=dof))"}], "type": ["function_empty", "TDD"], "node": ["skfolio.distribution.copula._student_t._sample_scores", "skfolio.distribution.copula._student_t._neg_log_likelihood"], "language": "Python", "toolfunc_count": 1, "func_count": 2, "pytest_info": {"total_num": 40, "base_passed_num": 17}} {"id": ["skfolio.src.skfolio.distribution.copula._utils._apply_copula_rotation", "skfolio.src.skfolio.distribution.copula._utils._apply_rotation_cdf", "skfolio.src.skfolio.distribution.copula._utils._apply_rotation_partial_derivatives"], "project": "skfolio", "origin_file": ["skfolio/distribution/copula/_utils.py", "skfolio/distribution/copula/_utils.py", "skfolio/distribution/copula/_utils.py"], "test_list": ["tests/test_distribution/test_copula/test_utils.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 509, "func_start_lineno": 341, "func_end_lineno": 380, "func_code": "def _apply_copula_rotation(X: npt.ArrayLike, rotation: CopulaRotation) -> np.ndarray:\n r\"\"\"Apply a bivariate copula rotation using the standard (clockwise) convention.\n\n The transformations are defined as follows:\n\n - `CopulaRotation.R0` (0°): :math:`(u, v) \\mapsto (u, v)`\n - `CopulaRotation.R90` (90°): :math:`(u, v) \\mapsto (v,\\, 1 - u)`\n - `CopulaRotation.R180` (180°): :math:`(u, v) \\mapsto (1 - u,\\, 1 - v)`\n - `CopulaRotation.R270` (270°): :math:`(u, v) \\mapsto (1 - v,\\, u)`\n\n Parameters\n ----------\n X : array-like of shape (n_observations, 2)\n An array of bivariate inputs `(u, v)` where each row represents a\n bivariate observation.\n\n rotation : CopulaRotation\n The rotation to apply to the copula (default is no rotation).\n\n Returns\n -------\n rotated_X: ndarray of shape (n_observations, 2)\n The rotated data array.\n \"\"\"\n match rotation:\n case CopulaRotation.R0:\n # No rotation\n pass\n case CopulaRotation.R90:\n # (u, v) -> (v, 1 - u)\n X = np.column_stack([X[:, 1], 1.0 - X[:, 0]])\n case CopulaRotation.R180:\n # (u, v) -> (1 - u, 1 - v)\n X = 1.0 - X\n case CopulaRotation.R270:\n # (u, v) -> (1 - v, u)\n X = np.column_stack([1.0 - X[:, 1], X[:, 0]])\n case _:\n raise ValueError(f\"Unsupported rotation: {rotation}\")\n return X"}, {"class_start_lineno": 1, "class_end_lineno": 509, "func_start_lineno": 409, "func_end_lineno": 449, "func_code": "def _apply_rotation_cdf(\n func: Callable, X: np.ndarray, rotation: CopulaRotation, **kwargs\n) -> np.ndarray:\n \"\"\"\n Apply a copula rotation to X and compute the corresponding CDF values.\n\n Parameters\n ----------\n func : Callable\n A function that computes the CDF given data X and additional keyword arguments.\n\n X : ndarray of shape (n_observations, 2)\n A 2D array of bivariate inputs.\n\n rotation : CopulaRotation\n The rotation to apply.\n\n **kwargs\n Additional keyword arguments to pass to the CDF function.\n\n Returns\n -------\n rotated_cdf : ndarray of shape (n_observations,)\n The transformed CDF values after applying the rotation.\n \"\"\"\n rotated_X = _apply_copula_rotation(X, rotation=rotation)\n cdf = func(X=rotated_X, **kwargs)\n\n match rotation:\n case CopulaRotation.R0:\n pass\n case CopulaRotation.R90:\n cdf = X[:, 1] - cdf\n case CopulaRotation.R180:\n cdf = np.sum(X, axis=1) - 1 + cdf\n case CopulaRotation.R270:\n cdf = X[:, 0] - cdf\n case _:\n raise ValueError(f\"Unsupported rotation: {rotation}\")\n\n return cdf"}, {"class_start_lineno": 1, "class_end_lineno": 509, "func_start_lineno": 452, "func_end_lineno": 509, "func_code": "def _apply_rotation_partial_derivatives(\n func: Callable,\n X: np.ndarray,\n rotation: CopulaRotation,\n first_margin: bool,\n **kwargs,\n) -> np.ndarray:\n \"\"\"\n Apply a copula rotation to X and compute the corresponding partial derivatives.\n\n This function rotates the data X using the specified rotation and then computes\n the partial derivative (h-function) using the provided function. The result is then\n adjusted according to the rotation and the margin of interest.\n\n Parameters\n ----------\n func : Callable\n A function that computes the partial derivative (h-function) given X, the\n margin, and any additional keyword arguments.\n\n X : ndarray of shape (n_observations, 2)\n A 2D array of bivariate inputs.\n\n rotation : CopulaRotation\n The rotation to apply.\n\n first_margin : bool\n If True, compute the partial derivative with respect to the first margin;\n otherwise, compute it with respect to the second margin.\n\n **kwargs\n Additional keyword arguments to pass to the partial derivative function.\n\n Returns\n -------\n z : ndarray of shape (n_observations,)\n The transformed partial derivative values after applying the rotation.\n \"\"\"\n rotated_X = _apply_copula_rotation(X, rotation=rotation)\n\n match rotation:\n case CopulaRotation.R0:\n z = func(X=rotated_X, first_margin=first_margin, **kwargs)\n case CopulaRotation.R90:\n if first_margin:\n z = func(X=rotated_X, first_margin=not first_margin, **kwargs)\n else:\n z = 1 - func(X=rotated_X, first_margin=not first_margin, **kwargs)\n case CopulaRotation.R180:\n z = 1 - func(X=rotated_X, first_margin=first_margin, **kwargs)\n case CopulaRotation.R270:\n if first_margin:\n z = 1 - func(X=rotated_X, first_margin=not first_margin, **kwargs)\n else:\n z = func(X=rotated_X, first_margin=not first_margin, **kwargs)\n case _:\n raise ValueError(f\"Unsupported rotation: {rotation}\")\n return z"}], "type": ["function_empty", "TDD"], "node": ["skfolio.distribution.copula._utils._apply_copula_rotation", "skfolio.distribution.copula._utils._apply_rotation_cdf", "skfolio.distribution.copula._utils._apply_rotation_partial_derivatives"], "language": "Python", "toolfunc_count": 2, "func_count": 3, "pytest_info": {"total_num": 10, "base_passed_num": 6}} {"id": ["skfolio.src.skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.src.skfolio.datasets._base.load_sp500_dataset"], "project": "skfolio", "origin_file": ["skfolio/datasets/_base.py", "skfolio/datasets/_base.py"], "test_list": ["tests/test_distribution/test_multivariate/test_utils.py", "tests/test_model_selection/test_walk_forward.py", "tests/test_utils/test_bootstrap.py", "tests/test_utils/test_validation.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 71, "func_end_lineno": 113, "func_code": "def load_gzip_compressed_csv_data(\n data_filename: str,\n data_module: str = DATA_MODULE,\n encoding=\"utf-8\",\n datetime_index: bool = True,\n) -> pd.DataFrame:\n \"\"\"Load gzip-compressed csv files with `importlib.resources`.\n\n 1) Open resource file with `importlib.resources.open_binary`\n 2) Decompress csv file with `gzip.open`\n 3) Load decompressed data with `pd.read_csv`\n\n Parameters\n ----------\n data_filename : str\n Name of gzip-compressed csv file (`'*.csv.gz'`) to be loaded from\n `data_module/data_file_name`. For example `'SPX500.csv.gz'`.\n\n data_module : str or module, default='skfolio.datasets.data'\n Module where data lives. The default is `'skfolio.datasets.data'`.\n\n encoding : str, default=\"utf-8\"\n Name of the encoding that the gzip-decompressed file will be\n decoded with. The default is 'utf-8'.\n\n datetime_index: bool, default=True\n If this is set to True, the DataFrame index is converted to datetime with\n format=\"%Y-%m-%d\".\n The default is `True`.\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n DataFrame with each row representing one observation and each column\n representing the asset price of a given observation.\n \"\"\"\n path = resources.files(data_module).joinpath(data_filename)\n with path.open(\"rb\") as compressed_file:\n compressed_file = gzip.open(compressed_file, mode=\"rt\", encoding=encoding)\n df = pd.read_csv(compressed_file, sep=\",\", index_col=0)\n if datetime_index:\n df.index = pd.to_datetime(df.index, format=\"%Y-%m-%d\")\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 168, "func_end_lineno": 204, "func_code": "def load_sp500_dataset() -> pd.DataFrame:\n \"\"\"Load the prices of 20 assets from the S&P 500 Index composition.\n\n This dataset is composed of the daily prices of 20 assets from the S&P 500\n composition starting from 1990-01-02 up to 2022-12-28.\n\n The data comes from the Yahoo public API.\n The price is the adjusted close which is the closing price after adjustments for\n all applicable splits and dividend distributions.\n The adjustment uses appropriate split and dividend multipliers, adhering to\n the Center for Research in Security Prices (CRSP) standards.\n\n ============== ==================\n Observations 8313\n Assets 20\n ============== ==================\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n Prices DataFrame\n\n Examples\n --------\n >>> from skfolio.datasets import load_sp500_dataset\n >>> prices = load_sp500_dataset()\n >>> prices.head()\n AAPL AMD BAC ... UNH WMT XOM\n 1990-01-02 0.332589 4.1250 11.65625 ... 0.382813 5.890625 12.5000\n 1990-01-03 0.334821 4.0000 11.75000 ... 0.375000 5.890625 12.3750\n 1990-01-04 0.335938 3.9375 11.50000 ... 0.371094 5.859375 12.2500\n 1990-01-05 0.337054 3.8125 11.25000 ... 0.355469 5.796875 12.1875\n 1990-01-08 0.339286 3.8125 11.31250 ... 0.347656 5.875000 12.3750\n \"\"\"\n data_filename = \"sp500_dataset.csv.gz\"\n df = load_gzip_compressed_csv_data(data_filename)\n return df"}], "type": ["function_empty"], "node": ["skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.datasets._base.load_sp500_dataset"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 24, "base_passed_num": 5}} {"id": ["skfolio.src.skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.src.skfolio.datasets._base.load_sp500_dataset", "skfolio.src.skfolio.measures._measures.get_cumulative_returns", "skfolio.src.skfolio.measures._measures.get_drawdowns"], "project": "skfolio", "origin_file": ["skfolio/datasets/_base.py", "skfolio/datasets/_base.py", "skfolio/measures/_measures.py", "skfolio/measures/_measures.py"], "test_list": ["tests/test_measures/test_measures.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 71, "func_end_lineno": 113, "func_code": "def load_gzip_compressed_csv_data(\n data_filename: str,\n data_module: str = DATA_MODULE,\n encoding=\"utf-8\",\n datetime_index: bool = True,\n) -> pd.DataFrame:\n \"\"\"Load gzip-compressed csv files with `importlib.resources`.\n\n 1) Open resource file with `importlib.resources.open_binary`\n 2) Decompress csv file with `gzip.open`\n 3) Load decompressed data with `pd.read_csv`\n\n Parameters\n ----------\n data_filename : str\n Name of gzip-compressed csv file (`'*.csv.gz'`) to be loaded from\n `data_module/data_file_name`. For example `'SPX500.csv.gz'`.\n\n data_module : str or module, default='skfolio.datasets.data'\n Module where data lives. The default is `'skfolio.datasets.data'`.\n\n encoding : str, default=\"utf-8\"\n Name of the encoding that the gzip-decompressed file will be\n decoded with. The default is 'utf-8'.\n\n datetime_index: bool, default=True\n If this is set to True, the DataFrame index is converted to datetime with\n format=\"%Y-%m-%d\".\n The default is `True`.\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n DataFrame with each row representing one observation and each column\n representing the asset price of a given observation.\n \"\"\"\n path = resources.files(data_module).joinpath(data_filename)\n with path.open(\"rb\") as compressed_file:\n compressed_file = gzip.open(compressed_file, mode=\"rt\", encoding=encoding)\n df = pd.read_csv(compressed_file, sep=\",\", index_col=0)\n if datetime_index:\n df.index = pd.to_datetime(df.index, format=\"%Y-%m-%d\")\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 168, "func_end_lineno": 204, "func_code": "def load_sp500_dataset() -> pd.DataFrame:\n \"\"\"Load the prices of 20 assets from the S&P 500 Index composition.\n\n This dataset is composed of the daily prices of 20 assets from the S&P 500\n composition starting from 1990-01-02 up to 2022-12-28.\n\n The data comes from the Yahoo public API.\n The price is the adjusted close which is the closing price after adjustments for\n all applicable splits and dividend distributions.\n The adjustment uses appropriate split and dividend multipliers, adhering to\n the Center for Research in Security Prices (CRSP) standards.\n\n ============== ==================\n Observations 8313\n Assets 20\n ============== ==================\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n Prices DataFrame\n\n Examples\n --------\n >>> from skfolio.datasets import load_sp500_dataset\n >>> prices = load_sp500_dataset()\n >>> prices.head()\n AAPL AMD BAC ... UNH WMT XOM\n 1990-01-02 0.332589 4.1250 11.65625 ... 0.382813 5.890625 12.5000\n 1990-01-03 0.334821 4.0000 11.75000 ... 0.375000 5.890625 12.3750\n 1990-01-04 0.335938 3.9375 11.50000 ... 0.371094 5.859375 12.2500\n 1990-01-05 0.337054 3.8125 11.25000 ... 0.355469 5.796875 12.1875\n 1990-01-08 0.339286 3.8125 11.31250 ... 0.347656 5.875000 12.3750\n \"\"\"\n data_filename = \"sp500_dataset.csv.gz\"\n df = load_gzip_compressed_csv_data(data_filename)\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 633, "func_start_lineno": 405, "func_end_lineno": 428, "func_code": "def get_cumulative_returns(returns: np.ndarray, compounded: bool = False) -> np.ndarray:\n \"\"\"Compute the cumulative returns from the returns.\n Non-compounded cumulative returns start at 0.\n Compounded cumulative returns are rescaled to start at 1000.\n\n Parameters\n ----------\n returns : ndarray of shape (n_observations,)\n Vector of returns.\n\n compounded : bool, default=False\n If this is set to True, the cumulative returns are compounded otherwise they\n are uncompounded.\n\n Returns\n -------\n values: ndarray of shape (n_observations,)\n Cumulative returns.\n \"\"\"\n if compounded:\n cumulative_returns = 1000 * np.cumprod(1 + returns) # Rescaled to start at 1000\n else:\n cumulative_returns = np.cumsum(returns)\n return cumulative_returns"}, {"class_start_lineno": 1, "class_end_lineno": 633, "func_start_lineno": 431, "func_end_lineno": 453, "func_code": "def get_drawdowns(returns: np.ndarray, compounded: bool = False) -> np.ndarray:\n \"\"\"Compute the drawdowns' series from the returns.\n\n Parameters\n ----------\n returns : ndarray of shape (n_observations,)\n Vector of returns.\n\n compounded : bool, default=False\n If this is set to True, the cumulative returns are compounded otherwise they\n are uncompounded.\n\n Returns\n -------\n values: ndarray of shape (n_observations,)\n Drawdowns.\n \"\"\"\n cumulative_returns = get_cumulative_returns(returns=returns, compounded=compounded)\n if compounded:\n drawdowns = cumulative_returns / np.maximum.accumulate(cumulative_returns) - 1\n else:\n drawdowns = cumulative_returns - np.maximum.accumulate(cumulative_returns)\n return drawdowns"}], "type": ["function_empty", "TDD"], "node": ["skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.datasets._base.load_sp500_dataset", "skfolio.measures._measures.get_cumulative_returns", "skfolio.measures._measures.get_drawdowns"], "language": "Python", "toolfunc_count": 2, "func_count": 4, "pytest_info": {"total_num": 17, "base_passed_num": 0}} {"id": ["skfolio.src.skfolio.model_selection._combinatorial._n_splits", "skfolio.src.skfolio.model_selection._combinatorial._n_test_paths"], "project": "skfolio", "origin_file": ["skfolio/model_selection/_combinatorial.py", "skfolio/model_selection/_combinatorial.py", "skfolio/model_selection/_combinatorial.py"], "test_list": ["tests/test_model_selection/test_combinatorial.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 564, "func_start_lineno": 415, "func_end_lineno": 431, "func_code": "def _n_splits(n_folds: int, n_test_folds: int) -> int:\n \"\"\"Number of splits.\n\n Parameters\n ----------\n n_folds : int\n Number of folds.\n\n n_test_folds : int\n Number of test folds.\n\n Returns\n -------\n n_splits : int\n Number of splits\n \"\"\"\n return math.comb(n_folds, n_test_folds)"}, {"class_start_lineno": 1, "class_end_lineno": 564, "func_start_lineno": 434, "func_end_lineno": 453, "func_code": "def _n_test_paths(n_folds: int, n_test_folds: int) -> int:\n \"\"\"Number of test paths that can be reconstructed from the train/test\n combinations.\n\n Parameters\n ----------\n n_folds : int\n Number of folds.\n\n n_test_folds : int\n Number of test folds.\n\n Returns\n -------\n n_splits : int\n Number of test paths.\n \"\"\"\n return (\n _n_splits(n_folds=n_folds, n_test_folds=n_test_folds) * n_test_folds // n_folds\n )"}, {"class_start_lineno": 46, "class_end_lineno": 412, "func_start_lineno": 203, "func_end_lineno": 207, "func_code": " def n_test_paths(self) -> int:\n \"\"\"Number of test paths that can be reconstructed from the train/test\n combinations.\n \"\"\"\n return _n_test_paths(n_folds=self.n_folds, n_test_folds=self.n_test_folds)"}], "type": ["function_empty"], "node": ["skfolio.model_selection._combinatorial._n_splits", "skfolio.model_selection._combinatorial._n_test_paths", "skfolio.model_selection._combinatorial.CombinatorialPurgedCV.n_test_paths"], "language": "Python", "toolfunc_count": 2, "func_count": 2, "pytest_info": {"total_num": 8, "base_passed_num": 0}} {"id": ["skfolio.src.skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.src.skfolio.datasets._base.load_sp500_dataset", "skfolio.src.skfolio.utils.tools.safe_indexing", "skfolio.src.skfolio.utils.tools.safe_split", "skfolio.src.skfolio.model_selection._validation.cross_val_predict"], "project": "skfolio", "origin_file": ["skfolio/datasets/_base.py", "skfolio/datasets/_base.py", "skfolio/utils/tools.py", "skfolio/utils/tools.py", "skfolio/model_selection/_validation.py"], "test_list": ["tests/test_model_selection/test_validation.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 71, "func_end_lineno": 113, "func_code": "def load_gzip_compressed_csv_data(\n data_filename: str,\n data_module: str = DATA_MODULE,\n encoding=\"utf-8\",\n datetime_index: bool = True,\n) -> pd.DataFrame:\n \"\"\"Load gzip-compressed csv files with `importlib.resources`.\n\n 1) Open resource file with `importlib.resources.open_binary`\n 2) Decompress csv file with `gzip.open`\n 3) Load decompressed data with `pd.read_csv`\n\n Parameters\n ----------\n data_filename : str\n Name of gzip-compressed csv file (`'*.csv.gz'`) to be loaded from\n `data_module/data_file_name`. For example `'SPX500.csv.gz'`.\n\n data_module : str or module, default='skfolio.datasets.data'\n Module where data lives. The default is `'skfolio.datasets.data'`.\n\n encoding : str, default=\"utf-8\"\n Name of the encoding that the gzip-decompressed file will be\n decoded with. The default is 'utf-8'.\n\n datetime_index: bool, default=True\n If this is set to True, the DataFrame index is converted to datetime with\n format=\"%Y-%m-%d\".\n The default is `True`.\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n DataFrame with each row representing one observation and each column\n representing the asset price of a given observation.\n \"\"\"\n path = resources.files(data_module).joinpath(data_filename)\n with path.open(\"rb\") as compressed_file:\n compressed_file = gzip.open(compressed_file, mode=\"rt\", encoding=encoding)\n df = pd.read_csv(compressed_file, sep=\",\", index_col=0)\n if datetime_index:\n df.index = pd.to_datetime(df.index, format=\"%Y-%m-%d\")\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 168, "func_end_lineno": 204, "func_code": "def load_sp500_dataset() -> pd.DataFrame:\n \"\"\"Load the prices of 20 assets from the S&P 500 Index composition.\n\n This dataset is composed of the daily prices of 20 assets from the S&P 500\n composition starting from 1990-01-02 up to 2022-12-28.\n\n The data comes from the Yahoo public API.\n The price is the adjusted close which is the closing price after adjustments for\n all applicable splits and dividend distributions.\n The adjustment uses appropriate split and dividend multipliers, adhering to\n the Center for Research in Security Prices (CRSP) standards.\n\n ============== ==================\n Observations 8313\n Assets 20\n ============== ==================\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n Prices DataFrame\n\n Examples\n --------\n >>> from skfolio.datasets import load_sp500_dataset\n >>> prices = load_sp500_dataset()\n >>> prices.head()\n AAPL AMD BAC ... UNH WMT XOM\n 1990-01-02 0.332589 4.1250 11.65625 ... 0.382813 5.890625 12.5000\n 1990-01-03 0.334821 4.0000 11.75000 ... 0.375000 5.890625 12.3750\n 1990-01-04 0.335938 3.9375 11.50000 ... 0.371094 5.859375 12.2500\n 1990-01-05 0.337054 3.8125 11.25000 ... 0.355469 5.796875 12.1875\n 1990-01-08 0.339286 3.8125 11.31250 ... 0.347656 5.875000 12.3750\n \"\"\"\n data_filename = \"sp500_dataset.csv.gz\"\n df = load_gzip_compressed_csv_data(data_filename)\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 787, "func_start_lineno": 190, "func_end_lineno": 219, "func_code": "def safe_indexing(\n X: npt.ArrayLike | pd.DataFrame, indices: npt.ArrayLike | None, axis: int = 0\n):\n \"\"\"Return rows, items or columns of X using indices.\n\n Parameters\n ----------\n X : array-like\n Data from which to sample rows.\n\n indices : array-like, optional\n Indices of rows or columns.\n The default (`None`) is to select the entire data.\n\n axis : int, default=0\n The axis along which `X` will be sub-sampled. `axis=0` will select\n rows while `axis=1` will select columns.\n\n Returns\n -------\n subset :\n Subset of X on axis 0.\n \"\"\"\n if indices is None:\n return X\n if hasattr(X, \"iloc\"):\n return X.take(indices, axis=axis)\n if axis == 0:\n return X[indices]\n return X[:, indices]"}, {"class_start_lineno": 1, "class_end_lineno": 787, "func_start_lineno": 222, "func_end_lineno": 261, "func_code": "def safe_split(\n X: npt.ArrayLike,\n y: npt.ArrayLike | None = None,\n indices: np.ndarray | None = None,\n axis: int = 0,\n):\n \"\"\"Create subset of dataset.\n\n Slice X, y according to indices for cross-validation.\n\n Parameters\n ----------\n X : array-like\n Data to be indexed.\n\n y : array-like\n Data to be indexed.\n\n indices : ndarray of int, optional\n Rows or columns to select from X and y.\n The default (`None`) is to select the entire data.\n\n axis : int, default=0\n The axis along which `X` will be sub-sampled. `axis=0` will select\n rows while `axis=1` will select columns.\n\n Returns\n -------\n X_subset : array-like\n Indexed data.\n\n y_subset : array-like\n Indexed targets.\n \"\"\"\n X_subset = safe_indexing(X, indices=indices, axis=axis)\n if y is not None:\n y_subset = safe_indexing(y, indices=indices, axis=axis)\n else:\n y_subset = None\n return X_subset, y_subset"}, {"class_start_lineno": 1, "class_end_lineno": 254, "func_start_lineno": 38, "func_end_lineno": 254, "func_code": "def cross_val_predict(\n estimator: skb.BaseEstimator,\n X: npt.ArrayLike,\n y: npt.ArrayLike = None,\n cv: sks.BaseCrossValidator | BaseCombinatorialCV | int | None = None,\n n_jobs: int | None = None,\n method: str = \"predict\",\n verbose: int = 0,\n params: dict | None = None,\n pre_dispatch: str = \"2*n_jobs\",\n column_indices: np.ndarray | None = None,\n portfolio_params: dict | None = None,\n) -> MultiPeriodPortfolio | Population:\n \"\"\"Generate cross-validated `Portfolios` estimates.\n\n The data is split according to the `cv` parameter.\n The optimization estimator is fitted on the training set and portfolios are\n predicted on the corresponding test set.\n\n For non-combinatorial cross-validation like `Kfold`, the output is the predicted\n :class:`~skfolio.portfolio.MultiPeriodPortfolio` where\n each :class:`~skfolio.portfolio.Portfolio` corresponds to the prediction on each\n train/test pair (`k` portfolios for `Kfold`).\n\n For combinatorial cross-validation\n like :class:`~skfolio.model_selection.CombinatorialPurgedCV`, the output is the\n predicted :class:`~skfolio.population.Population` of multiple\n :class:`~skfolio.portfolio.MultiPeriodPortfolio` (each test outputs are a\n collection of multiple paths instead of one single path).\n\n Parameters\n ----------\n estimator : BaseOptimization\n :ref:`Optimization estimators ` use to fit the data.\n\n X : array-like of shape (n_observations, n_assets)\n Price returns of the assets.\n\n y : array-like of shape (n_observations, n_targets), optional\n Target data (optional).\n For example, the price returns of the factors.\n\n cv : int | cross-validation generator, optional\n Determines the cross-validation splitting strategy.\n Possible inputs for cv are:\n\n * None, to use the default 5-fold cross validation,\n * int, to specify the number of folds in a `(Stratified)KFold`,\n * `CV splitter`,\n * An iterable that generates (train, test) splits as arrays of indices.\n\n n_jobs : int, optional\n The number of jobs to run in parallel for `fit` of all `estimators`.\n `None` means 1 unless in a `joblib.parallel_backend` context. -1 means\n using all processors.\n\n method : str\n Invokes the passed method name of the passed estimator.\n\n verbose : int, default=0\n The verbosity level.\n\n params : dict, optional\n Parameters to pass to the underlying estimator's ``fit`` and the CV splitter.\n\n pre_dispatch : int or str, default='2*n_jobs'\n Controls the number of jobs that get dispatched during parallel\n execution. Reducing this number can be useful to avoid an\n explosion of memory consumption when more jobs get dispatched\n than CPUs can process. This parameter can be:\n\n * None, in which case all the jobs are immediately\n created and spawned. Use this for lightweight and\n fast-running jobs, to avoid delays due to on-demand\n spawning of the jobs\n\n * An int, giving the exact number of total jobs that are\n spawned\n\n * A str, giving an expression as a function of n_jobs,\n as in '2*n_jobs'\n\n column_indices : ndarray, optional\n Indices of the `X` columns to cross-validate on.\n\n portfolio_params : dict, optional\n Additional portfolio parameters passed to `MultiPeriodPortfolio`.\n\n Returns\n -------\n predictions : MultiPeriodPortfolio | Population\n This is the result of calling `predict`\n \"\"\"\n params = {} if params is None else params\n\n X, y = safe_split(X, y, indices=column_indices, axis=1)\n X, y = sku.indexable(X, y)\n\n if _routing_enabled():\n # For estimators, a MetadataRouter is created in get_metadata_routing\n # methods. For these router methods, we create the router to use\n # `process_routing` on it.\n # noinspection PyTypeChecker\n router = (\n skm.MetadataRouter(owner=\"cross_validate\")\n .add(\n splitter=cv,\n method_mapping=skm.MethodMapping().add(caller=\"fit\", callee=\"split\"),\n )\n .add(\n estimator=estimator,\n method_mapping=skm.MethodMapping().add(caller=\"fit\", callee=\"fit\"),\n )\n )\n try:\n routed_params = skm.process_routing(router, \"fit\", **params)\n except ske.UnsetMetadataPassedError as e:\n # The default exception would mention `fit` since in the above\n # `process_routing` code, we pass `fit` as the caller. However,\n # the user is not calling `fit` directly, so we change the message\n # to make it more suitable for this case.\n unrequested_params = sorted(e.unrequested_params)\n raise ske.UnsetMetadataPassedError(\n message=(\n f\"{unrequested_params} are passed to `cross_val_predict` but are\"\n \" not explicitly set as requested or not requested for\"\n f\" cross_validate's estimator: {estimator.__class__.__name__} Call\"\n \" `.set_fit_request({{metadata}}=True)` on the estimator for\"\n f\" each metadata in {unrequested_params} that you want to use and\"\n \" `metadata=False` for not using it. See the Metadata Routing User\"\n \" guide \"\n \" for more information.\"\n ),\n unrequested_params=e.unrequested_params,\n routed_params=e.routed_params,\n ) from None\n else:\n routed_params = sku.Bunch()\n routed_params.splitter = sku.Bunch(split={})\n routed_params.estimator = sku.Bunch(fit=params)\n\n cv = sks.check_cv(cv, y)\n splits = list(cv.split(X, y, **routed_params.splitter.split))\n\n portfolio_params = {} if portfolio_params is None else portfolio_params.copy()\n\n # We ensure that the folds are not shuffled\n if not isinstance(cv, BaseCombinatorialCV):\n try:\n if cv.shuffle:\n raise ValueError(\n \"`cross_val_predict` only works with cross-validation setting\"\n \" `shuffle=False`\"\n )\n except AttributeError:\n # If we cannot find the attribute shuffle, we check if the first folds\n # are shuffled\n for fold in splits[0]:\n if not np.all(np.diff(fold) > 0):\n raise ValueError(\n \"`cross_val_predict` only works with un-shuffled folds\"\n ) from None\n\n # We clone the estimator to make sure that all the folds are independent\n # and that it is pickle-able.\n parallel = skp.Parallel(n_jobs=n_jobs, verbose=verbose, pre_dispatch=pre_dispatch)\n # TODO remove when https://github.com/joblib/joblib/issues/1071 is fixed\n # noinspection PyCallingNonCallable\n predictions = parallel(\n skp.delayed(fit_and_predict)(\n sk.clone(estimator),\n X,\n y,\n train=train,\n test=test,\n fit_params=routed_params.estimator.fit,\n method=method,\n )\n for train, test in splits\n )\n\n if isinstance(cv, BaseCombinatorialCV):\n path_ids = cv.get_path_ids()\n path_nb = np.max(path_ids) + 1\n portfolios = [[] for _ in range(path_nb)]\n for i, prediction in enumerate(predictions):\n for j, p in enumerate(prediction):\n path_id = path_ids[i, j]\n portfolios[path_id].append(p)\n name = portfolio_params.pop(\"name\", \"path\")\n pred = Population(\n [\n MultiPeriodPortfolio(\n name=f\"{name}_{i}\", portfolios=portfolios[i], **portfolio_params\n )\n for i in range(path_nb)\n ]\n )\n else:\n # We need to re-order the test folds in case they were un-ordered by the\n # CV generator.\n # Because the tests folds are not shuffled, we use the first index of each\n # fold to order them.\n test_indices = np.concatenate([test for _, test in splits])\n if np.unique(test_indices, axis=0).shape[0] != test_indices.shape[0]:\n raise ValueError(\n \"`cross_val_predict` only works with non-duplicated test indices\"\n )\n test_indices = [test for _, test in splits]\n sorted_fold_id = np.argsort([x[0] for x in test_indices])\n pred = MultiPeriodPortfolio(\n portfolios=[predictions[fold_id] for fold_id in sorted_fold_id],\n check_observations_order=False,\n **portfolio_params,\n )\n\n return pred"}], "type": ["function_empty", "TDD"], "node": ["skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.datasets._base.load_sp500_dataset", "skfolio.utils.tools.safe_indexing", "skfolio.utils.tools.safe_split", "skfolio.model_selection._validation.cross_val_predict"], "language": "Python", "toolfunc_count": 3, "func_count": 5, "pytest_info": {"total_num": 3, "base_passed_num": 0}} {"id": ["skfolio.src.skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.src.skfolio.datasets._base.load_sp500_dataset", "skfolio.src.skfolio.datasets._base.get_data_home", "skfolio.src.skfolio.datasets._base.download_dataset", "skfolio.src.skfolio.datasets._base.load_sp500_implied_vol_dataset"], "project": "skfolio", "origin_file": ["skfolio/datasets/_base.py", "skfolio/datasets/_base.py", "skfolio/datasets/_base.py", "skfolio/datasets/_base.py", "skfolio/datasets/_base.py"], "test_list": ["tests/test_moment/test_covariance/test_implied_covariance.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 71, "func_end_lineno": 113, "func_code": "def load_gzip_compressed_csv_data(\n data_filename: str,\n data_module: str = DATA_MODULE,\n encoding=\"utf-8\",\n datetime_index: bool = True,\n) -> pd.DataFrame:\n \"\"\"Load gzip-compressed csv files with `importlib.resources`.\n\n 1) Open resource file with `importlib.resources.open_binary`\n 2) Decompress csv file with `gzip.open`\n 3) Load decompressed data with `pd.read_csv`\n\n Parameters\n ----------\n data_filename : str\n Name of gzip-compressed csv file (`'*.csv.gz'`) to be loaded from\n `data_module/data_file_name`. For example `'SPX500.csv.gz'`.\n\n data_module : str or module, default='skfolio.datasets.data'\n Module where data lives. The default is `'skfolio.datasets.data'`.\n\n encoding : str, default=\"utf-8\"\n Name of the encoding that the gzip-decompressed file will be\n decoded with. The default is 'utf-8'.\n\n datetime_index: bool, default=True\n If this is set to True, the DataFrame index is converted to datetime with\n format=\"%Y-%m-%d\".\n The default is `True`.\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n DataFrame with each row representing one observation and each column\n representing the asset price of a given observation.\n \"\"\"\n path = resources.files(data_module).joinpath(data_filename)\n with path.open(\"rb\") as compressed_file:\n compressed_file = gzip.open(compressed_file, mode=\"rt\", encoding=encoding)\n df = pd.read_csv(compressed_file, sep=\",\", index_col=0)\n if datetime_index:\n df.index = pd.to_datetime(df.index, format=\"%Y-%m-%d\")\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 168, "func_end_lineno": 204, "func_code": "def load_sp500_dataset() -> pd.DataFrame:\n \"\"\"Load the prices of 20 assets from the S&P 500 Index composition.\n\n This dataset is composed of the daily prices of 20 assets from the S&P 500\n composition starting from 1990-01-02 up to 2022-12-28.\n\n The data comes from the Yahoo public API.\n The price is the adjusted close which is the closing price after adjustments for\n all applicable splits and dividend distributions.\n The adjustment uses appropriate split and dividend multipliers, adhering to\n the Center for Research in Security Prices (CRSP) standards.\n\n ============== ==================\n Observations 8313\n Assets 20\n ============== ==================\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n Prices DataFrame\n\n Examples\n --------\n >>> from skfolio.datasets import load_sp500_dataset\n >>> prices = load_sp500_dataset()\n >>> prices.head()\n AAPL AMD BAC ... UNH WMT XOM\n 1990-01-02 0.332589 4.1250 11.65625 ... 0.382813 5.890625 12.5000\n 1990-01-03 0.334821 4.0000 11.75000 ... 0.375000 5.890625 12.3750\n 1990-01-04 0.335938 3.9375 11.50000 ... 0.371094 5.859375 12.2500\n 1990-01-05 0.337054 3.8125 11.25000 ... 0.355469 5.796875 12.1875\n 1990-01-08 0.339286 3.8125 11.31250 ... 0.347656 5.875000 12.3750\n \"\"\"\n data_filename = \"sp500_dataset.csv.gz\"\n df = load_gzip_compressed_csv_data(data_filename)\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 25, "func_end_lineno": 55, "func_code": "def get_data_home(data_home: str | Path | None = None) -> str:\n \"\"\"Return the path of the skfolio data directory.\n\n This folder is used by some large dataset loaders to avoid downloading the\n data several times.\n\n By default, the data directory is set to a folder named 'skfolio_data' in the\n user home folder.\n\n Alternatively, it can be set by the 'SKFOLIO_DATA' environment\n variable or programmatically by giving an explicit folder path. The '~'\n symbol is expanded to the user home folder.\n\n If the folder does not already exist, it is automatically created.\n\n Parameters\n ----------\n data_home : str, optional\n The path to skfolio data directory. If `None`, the default path\n is `~/skfolio_data`.\n\n Returns\n -------\n data_home: str or path-like, optional\n The path to skfolio data directory.\n \"\"\"\n if data_home is None:\n data_home = os.environ.get(\"SKFOLIO_DATA\", os.path.join(\"~\", \"skfolio_data\"))\n data_home = os.path.expanduser(data_home)\n os.makedirs(data_home, exist_ok=True)\n return data_home"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 116, "func_end_lineno": 165, "func_code": "def download_dataset(\n data_filename: str,\n data_home: str | Path | None = None,\n download_if_missing: bool = True,\n) -> pd.DataFrame:\n \"\"\"Download and save locally a dataset from the remote GitHub dataset folder.\n\n Parameters\n ----------\n data_filename : str\n Name of gzip-compressed csv file (`'*.csv.gz'`) to be loaded from a remote\n GitHub dataset folder.\n\n data_home : str or path-like, optional\n Specify another download and cache folder for the datasets. By default,\n all skfolio data is stored in `~/skfolio_data` sub-folders.\n\n download_if_missing : bool, default=True\n If False, raise an OSError if the data is not locally available\n instead of trying to download the data from the source site.\n The default is `True`.\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n DataFrame with each row representing one observation and each column\n representing the asset price of a given observation.\n \"\"\"\n # Use a CORS proxy when triggering requests from the browser\n url_prefix = \"https://corsproxy.io/?\" if sys.platform == \"emscripten\" else \"\"\n url = url_prefix + (\n f\"https://github.com/skfolio/skfolio-datasets/raw/main/\"\n f\"datasets/{data_filename}.csv.gz\"\n )\n\n data_home = get_data_home(data_home=data_home)\n filepath = os.path.join(data_home, f\"{data_filename}.pkz\")\n\n if os.path.exists(filepath):\n return joblib.load(filepath)\n\n if not download_if_missing:\n raise OSError(\"Data not found and `download_if_missing` is False\")\n\n archive_path = os.path.join(data_home, os.path.basename(url))\n ur.urlretrieve(url, archive_path)\n df = load_gzip_compressed_csv_data(archive_path)\n joblib.dump(df, filepath, compress=6)\n os.remove(archive_path)\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 400, "func_end_lineno": 448, "func_code": "def load_sp500_implied_vol_dataset(\n data_home=None, download_if_missing=True\n) -> pd.DataFrame:\n \"\"\"Load the 3 months ATM implied volatility of the 20 assets from the\n SP500 dataset.\n\n This dataset is composed of the 3 months ATM implied volatility of 20 assets\n from the S&P 500 composition starting from 2010-01-04 up to 2022-12-28.\n\n The data comes from the Yahoo public API option chains.\n\n ============== ==================\n Observations 3270\n Assets 20\n ============== ==================\n\n Parameters\n ----------\n data_home : str, optional\n Specify another download and cache folder for the datasets.\n By default, all skfolio data is stored in `~/skfolio_data` subfolders.\n\n download_if_missing : bool, default=True\n If False, raise an OSError if the data is not locally available\n instead of trying to download the data from the source site.\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n Implied volatility DataFrame\n\n Examples\n --------\n >>> from skfolio.datasets import load_sp500_implied_vol_dataset\n >>> implied_vol = load_sp500_implied_vol_dataset()\n >>> implied_vol.head()\n AAPL AMD BAC ... UNH WMT XOM\n Date ...\n 2010-01-04 0.364353 0.572056 0.382926 ... 0.362751 0.171737 0.201485\n 2010-01-05 0.371865 0.568791 0.374699 ... 0.368504 0.174764 0.203852\n 2010-01-06 0.356746 0.558054 0.349220 ... 0.368514 0.171892 0.197475\n 2010-01-07 0.361084 0.560475 0.354942 ... 0.355792 0.169083 0.200046\n 2010-01-08 0.348085 0.543932 0.360345 ... 0.351130 0.170897 0.204832\n \"\"\"\n data_filename = \"sp500_implied_vol_dataset\"\n df = download_dataset(\n data_filename, data_home=data_home, download_if_missing=download_if_missing\n )\n return df"}], "type": ["function_empty"], "node": ["skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.datasets._base.load_sp500_dataset", "skfolio.datasets._base.get_data_home", "skfolio.datasets._base.download_dataset", "skfolio.datasets._base.load_sp500_implied_vol_dataset"], "language": "Python", "toolfunc_count": 5, "func_count": 5, "pytest_info": {"total_num": 25, "base_passed_num": 0}} {"id": ["skfolio.src.skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.src.skfolio.datasets._base.load_sp500_dataset", "skfolio.src.skfolio.optimization.cluster._nco.NestedClustersOptimization::get_metadata_routing", "skfolio.src.skfolio.optimization.cluster._nco.NestedClustersOptimization::fit"], "project": "skfolio", "origin_file": ["skfolio/datasets/_base.py", "skfolio/datasets/_base.py", "skfolio/optimization/cluster/_nco.py", "skfolio/optimization/cluster/_nco.py"], "test_list": ["tests/test_optimization/test_cluster/test_nco.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 71, "func_end_lineno": 113, "func_code": "def load_gzip_compressed_csv_data(\n data_filename: str,\n data_module: str = DATA_MODULE,\n encoding=\"utf-8\",\n datetime_index: bool = True,\n) -> pd.DataFrame:\n \"\"\"Load gzip-compressed csv files with `importlib.resources`.\n\n 1) Open resource file with `importlib.resources.open_binary`\n 2) Decompress csv file with `gzip.open`\n 3) Load decompressed data with `pd.read_csv`\n\n Parameters\n ----------\n data_filename : str\n Name of gzip-compressed csv file (`'*.csv.gz'`) to be loaded from\n `data_module/data_file_name`. For example `'SPX500.csv.gz'`.\n\n data_module : str or module, default='skfolio.datasets.data'\n Module where data lives. The default is `'skfolio.datasets.data'`.\n\n encoding : str, default=\"utf-8\"\n Name of the encoding that the gzip-decompressed file will be\n decoded with. The default is 'utf-8'.\n\n datetime_index: bool, default=True\n If this is set to True, the DataFrame index is converted to datetime with\n format=\"%Y-%m-%d\".\n The default is `True`.\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n DataFrame with each row representing one observation and each column\n representing the asset price of a given observation.\n \"\"\"\n path = resources.files(data_module).joinpath(data_filename)\n with path.open(\"rb\") as compressed_file:\n compressed_file = gzip.open(compressed_file, mode=\"rt\", encoding=encoding)\n df = pd.read_csv(compressed_file, sep=\",\", index_col=0)\n if datetime_index:\n df.index = pd.to_datetime(df.index, format=\"%Y-%m-%d\")\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 168, "func_end_lineno": 204, "func_code": "def load_sp500_dataset() -> pd.DataFrame:\n \"\"\"Load the prices of 20 assets from the S&P 500 Index composition.\n\n This dataset is composed of the daily prices of 20 assets from the S&P 500\n composition starting from 1990-01-02 up to 2022-12-28.\n\n The data comes from the Yahoo public API.\n The price is the adjusted close which is the closing price after adjustments for\n all applicable splits and dividend distributions.\n The adjustment uses appropriate split and dividend multipliers, adhering to\n the Center for Research in Security Prices (CRSP) standards.\n\n ============== ==================\n Observations 8313\n Assets 20\n ============== ==================\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n Prices DataFrame\n\n Examples\n --------\n >>> from skfolio.datasets import load_sp500_dataset\n >>> prices = load_sp500_dataset()\n >>> prices.head()\n AAPL AMD BAC ... UNH WMT XOM\n 1990-01-02 0.332589 4.1250 11.65625 ... 0.382813 5.890625 12.5000\n 1990-01-03 0.334821 4.0000 11.75000 ... 0.375000 5.890625 12.3750\n 1990-01-04 0.335938 3.9375 11.50000 ... 0.371094 5.859375 12.2500\n 1990-01-05 0.337054 3.8125 11.25000 ... 0.355469 5.796875 12.1875\n 1990-01-08 0.339286 3.8125 11.31250 ... 0.347656 5.875000 12.3750\n \"\"\"\n data_filename = \"sp500_dataset.csv.gz\"\n df = load_gzip_compressed_csv_data(data_filename)\n return df"}, {"class_start_lineno": 33, "class_end_lineno": 392, "func_start_lineno": 197, "func_end_lineno": 214, "func_code": " def get_metadata_routing(self):\n # noinspection PyTypeChecker\n router = (\n skm.MetadataRouter(owner=self.__class__.__name__)\n .add(\n distance_estimator=self.distance_estimator,\n method_mapping=skm.MethodMapping().add(caller=\"fit\", callee=\"fit\"),\n )\n .add(\n clustering_estimator=self.clustering_estimator,\n method_mapping=skm.MethodMapping().add(caller=\"fit\", callee=\"fit\"),\n )\n .add(\n inner_estimator=self.inner_estimator,\n method_mapping=skm.MethodMapping().add(caller=\"fit\", callee=\"fit\"),\n )\n )\n return router"}, {"class_start_lineno": 33, "class_end_lineno": 392, "func_start_lineno": 216, "func_end_lineno": 392, "func_code": " def fit(\n self, X: npt.ArrayLike, y: npt.ArrayLike | None = None, **fit_params\n ) -> \"NestedClustersOptimization\":\n \"\"\"Fit the Nested Clusters Optimization estimator.\n\n Parameters\n ----------\n X : array-like of shape (n_observations, n_assets)\n Price returns of the assets.\n\n y : array-like of shape (n_observations, n_targets), optional\n Price returns of factors or a target benchmark.\n The default is `None`.\n\n **fit_params : dict\n Parameters to pass to the underlying estimators.\n Only available if `enable_metadata_routing=True`, which can be\n set by using ``sklearn.set_config(enable_metadata_routing=True)``.\n See :ref:`Metadata Routing User Guide ` for\n more details.\n\n Returns\n -------\n self : NestedClustersOptimization\n Fitted estimator.\n \"\"\"\n routed_params = skm.process_routing(self, \"fit\", **fit_params)\n\n self.distance_estimator_ = check_estimator(\n self.distance_estimator,\n default=PearsonDistance(),\n check_type=BaseDistance,\n )\n self.clustering_estimator_ = check_estimator(\n self.clustering_estimator,\n default=HierarchicalClustering(),\n check_type=skb.BaseEstimator,\n )\n self.outer_estimator_ = check_estimator(\n self.outer_estimator,\n default=MeanRisk(),\n check_type=BaseOptimization,\n )\n _inner_estimator = check_estimator(\n self.inner_estimator,\n default=MeanRisk(),\n check_type=BaseOptimization,\n )\n\n # noinspection PyArgumentList\n self.distance_estimator_.fit(X, y, **routed_params.distance_estimator.fit)\n distance = self.distance_estimator_.distance_\n n_assets = distance.shape[0]\n\n # To keep the asset_names --> used for visualisation\n if isinstance(X, pd.DataFrame):\n distance = pd.DataFrame(distance, columns=X.columns)\n\n # noinspection PyUnresolvedReferences\n self.clustering_estimator_.fit(\n X=distance, y=None, **routed_params.clustering_estimator.fit\n )\n # noinspection PyUnresolvedReferences\n labels = self.clustering_estimator_.labels_\n n_clusters = max(labels) + 1\n clusters = [np.argwhere(labels == i).flatten() for i in range(n_clusters)]\n\n # Intra cluster weights\n # Fit the inner estimator on the whole training data. Those\n # base estimators will be used to retrieve the inner weights.\n # They are exposed publicly.\n # noinspection PyCallingNonCallable\n fitted_inner_estimators = skp.Parallel(n_jobs=self.n_jobs)(\n skp.delayed(fit_single_estimator)(\n sk.clone(_inner_estimator),\n X,\n y,\n routed_params.inner_estimator.fit,\n indices=cluster_ids,\n axis=1,\n )\n for cluster_ids in clusters\n if len(cluster_ids) != 1\n )\n fitted_inner_estimators = iter(fitted_inner_estimators)\n\n self.inner_estimators_ = []\n inner_weights = []\n for cluster_ids in clusters:\n w = np.zeros(n_assets)\n # For single assets, we don't run the inner optimization estimator.\n if len(cluster_ids) == 1:\n w[cluster_ids] = 1\n else:\n fitted_inner_estimator = next(fitted_inner_estimators)\n self.inner_estimators_.append(fitted_inner_estimator)\n w[cluster_ids] = fitted_inner_estimator.weights_\n inner_weights.append(w)\n inner_weights = np.array(inner_weights)\n assert not any(fitted_inner_estimators), (\n \"fitted_inner_estimator iterator must be empty\"\n )\n\n # Outer cluster weights\n # To train the outer-estimator using the most data as possible, we use\n # a cross-validation to obtain the output of the cluster estimators.\n # To ensure that the data provided to each estimator are the same,\n # we need to set the random state of the cv if there is one and we\n # need to take a copy.\n if self.cv == \"ignore\":\n cv_predictions = None\n test_indices = slice(None)\n else:\n cv = sks.check_cv(self.cv)\n if hasattr(cv, \"random_state\") and cv.random_state is None:\n cv.random_state = np.random.RandomState()\n # noinspection PyCallingNonCallable\n cv_predictions = skp.Parallel(n_jobs=self.n_jobs)(\n skp.delayed(cross_val_predict)(\n sk.clone(_inner_estimator),\n X,\n y,\n cv=deepcopy(cv),\n n_jobs=self.n_jobs,\n verbose=self.verbose,\n column_indices=cluster_ids,\n method=\"predict\",\n params=routed_params.inner_estimator.fit,\n )\n for cluster_ids in clusters\n if len(cluster_ids) != 1\n )\n cv_predictions = iter(cv_predictions)\n if isinstance(self.cv, BaseCombinatorialCV):\n test_indices = slice(None)\n else:\n test_indices = np.sort(\n np.concatenate([test for _, test in cv.split(X, y)])\n )\n\n # We validate and convert to numpy array only after inner-estimator fitting to\n # keep the assets names in case they are used in the estimator.\n if y is not None:\n X, y = skv.validate_data(self, X, y)\n y_pred = y[test_indices]\n else:\n X = skv.validate_data(self, X)\n y_pred = None\n\n X_pred = []\n fitted_inner_estimators = iter(self.inner_estimators_)\n for cluster_ids in clusters:\n if len(cluster_ids) == 1:\n pred = X[test_indices, cluster_ids[0]]\n else:\n if cv_predictions is None:\n fitted_inner_estimator = next(fitted_inner_estimators)\n pred = fitted_inner_estimator.predict(X[test_indices, cluster_ids])\n else:\n pred = next(cv_predictions)\n if isinstance(self.cv, BaseCombinatorialCV):\n pred = pred.quantile(\n measure=self.quantile_measure, q=self.quantile\n )\n X_pred.append(np.asarray(pred))\n X_pred = np.array(X_pred).T\n if cv_predictions is None:\n assert not any(fitted_inner_estimators), (\n \"fitted_inner_estimator iterator must be empty\"\n )\n else:\n assert not any(cv_predictions), \"cv_predictions iterator must be empty\"\n\n fit_single_estimator(self.outer_estimator_, X_pred, y_pred, fit_params={})\n outer_weights = self.outer_estimator_.weights_\n self.weights_ = outer_weights @ inner_weights\n return self"}], "type": ["function_empty", "TDD"], "node": ["skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.datasets._base.load_sp500_dataset", "skfolio.optimization.cluster._nco.NestedClustersOptimization.get_metadata_routing", "skfolio.optimization.cluster._nco.NestedClustersOptimization.fit"], "language": "Python", "toolfunc_count": 3, "func_count": 4, "pytest_info": {"total_num": 15, "base_passed_num": 0}} {"id": ["skfolio.src.skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.src.skfolio.datasets._base.load_sp500_dataset", "skfolio.src.skfolio.prior._empirical.EmpiricalPrior::get_metadata_routing", "skfolio.src.skfolio.prior._empirical.EmpiricalPrior::fit"], "project": "skfolio", "origin_file": ["skfolio/datasets/_base.py", "skfolio/datasets/_base.py", "skfolio/prior/_empirical.py", "skfolio/prior/_empirical.py"], "test_list": ["tests/test_optimization/test_cluster/test_hierarchical/test_herc.py", "tests/test_optimization/test_cluster/test_hierarchical/test_hrp.py", "tests/test_optimization/test_convex/test_maximum_diversification.py", "tests/test_optimization/test_convex/test_risk_budgeting.py", "tests/test_prior/test_empirical.py", "tests/test_uncertainty_set/test_bootstrap.py", "tests/test_uncertainty_set/test_empirical.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 71, "func_end_lineno": 113, "func_code": "def load_gzip_compressed_csv_data(\n data_filename: str,\n data_module: str = DATA_MODULE,\n encoding=\"utf-8\",\n datetime_index: bool = True,\n) -> pd.DataFrame:\n \"\"\"Load gzip-compressed csv files with `importlib.resources`.\n\n 1) Open resource file with `importlib.resources.open_binary`\n 2) Decompress csv file with `gzip.open`\n 3) Load decompressed data with `pd.read_csv`\n\n Parameters\n ----------\n data_filename : str\n Name of gzip-compressed csv file (`'*.csv.gz'`) to be loaded from\n `data_module/data_file_name`. For example `'SPX500.csv.gz'`.\n\n data_module : str or module, default='skfolio.datasets.data'\n Module where data lives. The default is `'skfolio.datasets.data'`.\n\n encoding : str, default=\"utf-8\"\n Name of the encoding that the gzip-decompressed file will be\n decoded with. The default is 'utf-8'.\n\n datetime_index: bool, default=True\n If this is set to True, the DataFrame index is converted to datetime with\n format=\"%Y-%m-%d\".\n The default is `True`.\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n DataFrame with each row representing one observation and each column\n representing the asset price of a given observation.\n \"\"\"\n path = resources.files(data_module).joinpath(data_filename)\n with path.open(\"rb\") as compressed_file:\n compressed_file = gzip.open(compressed_file, mode=\"rt\", encoding=encoding)\n df = pd.read_csv(compressed_file, sep=\",\", index_col=0)\n if datetime_index:\n df.index = pd.to_datetime(df.index, format=\"%Y-%m-%d\")\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 168, "func_end_lineno": 204, "func_code": "def load_sp500_dataset() -> pd.DataFrame:\n \"\"\"Load the prices of 20 assets from the S&P 500 Index composition.\n\n This dataset is composed of the daily prices of 20 assets from the S&P 500\n composition starting from 1990-01-02 up to 2022-12-28.\n\n The data comes from the Yahoo public API.\n The price is the adjusted close which is the closing price after adjustments for\n all applicable splits and dividend distributions.\n The adjustment uses appropriate split and dividend multipliers, adhering to\n the Center for Research in Security Prices (CRSP) standards.\n\n ============== ==================\n Observations 8313\n Assets 20\n ============== ==================\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n Prices DataFrame\n\n Examples\n --------\n >>> from skfolio.datasets import load_sp500_dataset\n >>> prices = load_sp500_dataset()\n >>> prices.head()\n AAPL AMD BAC ... UNH WMT XOM\n 1990-01-02 0.332589 4.1250 11.65625 ... 0.382813 5.890625 12.5000\n 1990-01-03 0.334821 4.0000 11.75000 ... 0.375000 5.890625 12.3750\n 1990-01-04 0.335938 3.9375 11.50000 ... 0.371094 5.859375 12.2500\n 1990-01-05 0.337054 3.8125 11.25000 ... 0.355469 5.796875 12.1875\n 1990-01-08 0.339286 3.8125 11.31250 ... 0.347656 5.875000 12.3750\n \"\"\"\n data_filename = \"sp500_dataset.csv.gz\"\n df = load_gzip_compressed_csv_data(data_filename)\n return df"}, {"class_start_lineno": 17, "class_end_lineno": 202, "func_start_lineno": 93, "func_end_lineno": 106, "func_code": " def get_metadata_routing(self):\n # noinspection PyTypeChecker\n router = (\n skm.MetadataRouter(owner=self.__class__.__name__)\n .add(\n mu_estimator=self.mu_estimator,\n method_mapping=skm.MethodMapping().add(caller=\"fit\", callee=\"fit\"),\n )\n .add(\n covariance_estimator=self.covariance_estimator,\n method_mapping=skm.MethodMapping().add(caller=\"fit\", callee=\"fit\"),\n )\n )\n return router"}, {"class_start_lineno": 17, "class_end_lineno": 202, "func_start_lineno": 108, "func_end_lineno": 202, "func_code": " def fit(self, X: npt.ArrayLike, y=None, **fit_params) -> \"EmpiricalPrior\":\n \"\"\"Fit the Empirical Prior estimator.\n\n Parameters\n ----------\n X : array-like of shape (n_observations, n_assets)\n Price returns of the assets.\n\n y : Ignored\n Not used, present for API consistency by convention.\n\n **fit_params : dict\n Parameters to pass to the underlying estimators.\n Only available if `enable_metadata_routing=True`, which can be\n set by using ``sklearn.set_config(enable_metadata_routing=True)``.\n See :ref:`Metadata Routing User Guide ` for\n more details.\n\n Returns\n -------\n self : EmpiricalPrior\n Fitted estimator.\n \"\"\"\n routed_params = skm.process_routing(self, \"fit\", **fit_params)\n\n self.mu_estimator_ = check_estimator(\n self.mu_estimator,\n default=EmpiricalMu(),\n check_type=BaseMu,\n )\n self.covariance_estimator_ = check_estimator(\n self.covariance_estimator,\n default=EmpiricalCovariance(),\n check_type=BaseCovariance,\n )\n # fitting estimators\n if not self.is_log_normal:\n if self.investment_horizon is not None:\n raise ValueError(\n \"`investment_horizon` must be `None` when \"\n \"`is_log_normal` is `False`\"\n )\n # Expected returns\n # noinspection PyArgumentList\n self.mu_estimator_.fit(X, y, **routed_params.mu_estimator.fit)\n mu = self.mu_estimator_.mu_\n\n # Covariance\n # noinspection PyArgumentList\n self.covariance_estimator_.fit(\n X, y, **routed_params.covariance_estimator.fit\n )\n covariance = self.covariance_estimator_.covariance_\n else:\n if self.investment_horizon is None:\n raise ValueError(\n \"`investment_horizon` must be provided when \"\n \"`is_log_normal` is `True`\"\n )\n # Convert linear returns to log returns\n X_log = np.log(1 + X)\n y_log = np.log(1 + y) if y is not None else None\n\n # Estimates the moments on the log returns\n # Expected returns\n # noinspection PyArgumentList\n self.mu_estimator_.fit(X_log, y_log, **routed_params.mu_estimator.fit)\n mu = self.mu_estimator_.mu_\n\n # Covariance\n # noinspection PyArgumentList\n self.covariance_estimator_.fit(\n X_log, y_log, **routed_params.covariance_estimator.fit\n )\n covariance = self.covariance_estimator_.covariance_\n\n # Using the property of aggregation across time we scale this distribution\n # to the investment horizon by the “square-root rule”.\n mu *= self.investment_horizon\n covariance *= self.investment_horizon\n\n # We convert it into a distribution of linear returns over the investment\n # horizon\n mu = np.exp(mu + 0.5 * np.diag(covariance))\n covariance = np.outer(mu, mu) * (np.exp(covariance) - 1)\n\n # we validate and convert to numpy after all models have been fitted to keep\n # features names information.\n X = skv.validate_data(self, X)\n self.prior_model_ = PriorModel(\n mu=mu,\n covariance=covariance,\n returns=X,\n )\n return self"}], "type": ["function_empty", "TDD"], "node": ["skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.datasets._base.load_sp500_dataset", "skfolio.prior._empirical.EmpiricalPrior.get_metadata_routing", "skfolio.prior._empirical.EmpiricalPrior.fit"], "language": "Python", "toolfunc_count": 3, "func_count": 4, "pytest_info": {"total_num": 398, "base_passed_num": 0}} {"id": ["skfolio.src.skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.src.skfolio.datasets._base.load_sp500_dataset", "skfolio.src.skfolio.optimization.ensemble._stacking.StackingOptimization::get_metadata_routing", "skfolio.src.skfolio.optimization.ensemble._stacking.StackingOptimization::fit"], "project": "skfolio", "origin_file": ["skfolio/datasets/_base.py", "skfolio/datasets/_base.py", "skfolio/optimization/ensemble/_stacking.py", "skfolio/optimization/ensemble/_stacking.py"], "test_list": ["tests/test_optimization/test_ensemble/test_stacking.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 71, "func_end_lineno": 113, "func_code": "def load_gzip_compressed_csv_data(\n data_filename: str,\n data_module: str = DATA_MODULE,\n encoding=\"utf-8\",\n datetime_index: bool = True,\n) -> pd.DataFrame:\n \"\"\"Load gzip-compressed csv files with `importlib.resources`.\n\n 1) Open resource file with `importlib.resources.open_binary`\n 2) Decompress csv file with `gzip.open`\n 3) Load decompressed data with `pd.read_csv`\n\n Parameters\n ----------\n data_filename : str\n Name of gzip-compressed csv file (`'*.csv.gz'`) to be loaded from\n `data_module/data_file_name`. For example `'SPX500.csv.gz'`.\n\n data_module : str or module, default='skfolio.datasets.data'\n Module where data lives. The default is `'skfolio.datasets.data'`.\n\n encoding : str, default=\"utf-8\"\n Name of the encoding that the gzip-decompressed file will be\n decoded with. The default is 'utf-8'.\n\n datetime_index: bool, default=True\n If this is set to True, the DataFrame index is converted to datetime with\n format=\"%Y-%m-%d\".\n The default is `True`.\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n DataFrame with each row representing one observation and each column\n representing the asset price of a given observation.\n \"\"\"\n path = resources.files(data_module).joinpath(data_filename)\n with path.open(\"rb\") as compressed_file:\n compressed_file = gzip.open(compressed_file, mode=\"rt\", encoding=encoding)\n df = pd.read_csv(compressed_file, sep=\",\", index_col=0)\n if datetime_index:\n df.index = pd.to_datetime(df.index, format=\"%Y-%m-%d\")\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 168, "func_end_lineno": 204, "func_code": "def load_sp500_dataset() -> pd.DataFrame:\n \"\"\"Load the prices of 20 assets from the S&P 500 Index composition.\n\n This dataset is composed of the daily prices of 20 assets from the S&P 500\n composition starting from 1990-01-02 up to 2022-12-28.\n\n The data comes from the Yahoo public API.\n The price is the adjusted close which is the closing price after adjustments for\n all applicable splits and dividend distributions.\n The adjustment uses appropriate split and dividend multipliers, adhering to\n the Center for Research in Security Prices (CRSP) standards.\n\n ============== ==================\n Observations 8313\n Assets 20\n ============== ==================\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n Prices DataFrame\n\n Examples\n --------\n >>> from skfolio.datasets import load_sp500_dataset\n >>> prices = load_sp500_dataset()\n >>> prices.head()\n AAPL AMD BAC ... UNH WMT XOM\n 1990-01-02 0.332589 4.1250 11.65625 ... 0.382813 5.890625 12.5000\n 1990-01-03 0.334821 4.0000 11.75000 ... 0.375000 5.890625 12.3750\n 1990-01-04 0.335938 3.9375 11.50000 ... 0.371094 5.859375 12.2500\n 1990-01-05 0.337054 3.8125 11.25000 ... 0.355469 5.796875 12.1875\n 1990-01-08 0.339286 3.8125 11.31250 ... 0.347656 5.875000 12.3750\n \"\"\"\n data_filename = \"sp500_dataset.csv.gz\"\n df = load_gzip_compressed_csv_data(data_filename)\n return df"}, {"class_start_lineno": 30, "class_end_lineno": 355, "func_start_lineno": 233, "func_end_lineno": 241, "func_code": " def get_metadata_routing(self):\n # noinspection PyTypeChecker\n router = skm.MetadataRouter(owner=self.__class__.__name__)\n for name, estimator in self.estimators:\n router.add(\n **{name: estimator},\n method_mapping=skm.MethodMapping().add(caller=\"fit\", callee=\"fit\"),\n )\n return router"}, {"class_start_lineno": 30, "class_end_lineno": 355, "func_start_lineno": 243, "func_end_lineno": 355, "func_code": " def fit(\n self, X: npt.ArrayLike, y: npt.ArrayLike | None = None, **fit_params\n ) -> \"StackingOptimization\":\n \"\"\"Fit the Stacking Optimization estimator.\n\n Parameters\n ----------\n X : array-like of shape (n_observations, n_assets)\n Price returns of the assets.\n\n y : array-like of shape (n_observations, n_targets), optional\n Price returns of factors or a target benchmark.\n The default is `None`.\n\n **fit_params : dict\n Parameters to pass to the underlying estimators.\n Only available if `enable_metadata_routing=True`, which can be\n set by using ``sklearn.set_config(enable_metadata_routing=True)``.\n See :ref:`Metadata Routing User Guide ` for\n more details.\n\n Returns\n -------\n self : StackingOptimization\n Fitted estimator.\n \"\"\"\n routed_params = skm.process_routing(self, \"fit\", **fit_params)\n\n names, all_estimators = self._validate_estimators()\n self.final_estimator_ = check_estimator(\n self.final_estimator,\n default=MeanRisk(),\n check_type=BaseOptimization,\n )\n\n if self.cv == \"prefit\":\n self.estimators_ = []\n for estimator in all_estimators:\n skv.check_is_fitted(estimator)\n self.estimators_.append(estimator)\n else:\n # Fit the base estimators on the whole training data. Those\n # base estimators will be used to retrieve the inner weights.\n # They are exposed publicly.\n # noinspection PyCallingNonCallable\n self.estimators_ = skp.Parallel(n_jobs=self.n_jobs)(\n skp.delayed(fit_single_estimator)(\n sk.clone(est), X, y, routed_params[name][\"fit\"]\n )\n for name, est in zip(names, all_estimators, strict=True)\n )\n\n self.named_estimators_ = {\n name: estimator\n for name, estimator in zip(names, self.estimators_, strict=True)\n }\n\n inner_weights = np.array([estimator.weights_ for estimator in self.estimators_])\n\n # To train the final-estimator using the most data as possible, we use\n # a cross-validation to obtain the output of the stacked estimators.\n # To ensure that the data provided to each estimator are the same,\n # we need to set the random state of the cv if there is one and we\n # need to take a copy.\n if self.cv in [\"prefit\", \"ignore\"]:\n X_pred = np.array(\n [estimator.predict(X) for estimator in self.estimators_]\n ).T\n else:\n cv = sks.check_cv(self.cv)\n if hasattr(cv, \"random_state\") and cv.random_state is None:\n cv.random_state = np.random.RandomState()\n # noinspection PyCallingNonCallable\n cv_predictions = skp.Parallel(n_jobs=self.n_jobs)(\n skp.delayed(cross_val_predict)(\n sk.clone(est),\n X,\n y,\n cv=deepcopy(cv),\n method=\"predict\",\n n_jobs=self.n_jobs,\n params=routed_params[name][\"fit\"],\n verbose=self.verbose,\n )\n for name, est in zip(names, all_estimators, strict=True)\n )\n\n # We validate and convert to numpy array only after base-estimator fitting\n # to keep the assets names in case they are used in the estimator.\n if y is not None:\n _, y = skv.validate_data(self, X, y, multi_output=True)\n else:\n _ = skv.validate_data(self, X)\n\n if isinstance(self.cv, BaseCombinatorialCV):\n X_pred = np.array(\n [\n pred.quantile(measure=self.quantile_measure, q=self.quantile)\n for pred in cv_predictions\n ]\n ).T\n else:\n X_pred = np.array(cv_predictions).T\n if y is not None:\n test_indices = np.sort(\n np.concatenate([test for _, test in cv.split(X, y)])\n )\n y = y[test_indices]\n\n fit_single_estimator(self.final_estimator_, X_pred, y, {})\n outer_weights = self.final_estimator_.weights_\n self.weights_ = outer_weights @ inner_weights\n return self"}], "type": ["function_empty", "TDD"], "node": ["skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.datasets._base.load_sp500_dataset", "skfolio.optimization.ensemble._stacking.StackingOptimization.get_metadata_routing", "skfolio.optimization.ensemble._stacking.StackingOptimization.fit"], "language": "Python", "toolfunc_count": 3, "func_count": 4, "pytest_info": {"total_num": 5, "base_passed_num": 1}} {"id": ["skfolio.src.skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.src.skfolio.datasets._base.load_sp500_dataset", "skfolio.src.skfolio.datasets._base.load_factors_dataset", "skfolio.src.skfolio.prior._empirical.EmpiricalPrior::get_metadata_routing", "skfolio.src.skfolio.prior._empirical.EmpiricalPrior::fit"], "project": "skfolio", "origin_file": ["skfolio/datasets/_base.py", "skfolio/datasets/_base.py", "skfolio/datasets/_base.py", "skfolio/prior/_empirical.py", "skfolio/prior/_empirical.py"], "test_list": ["tests/test_optimization/test_naive/test_naive.py", "tests/test_prior/test_factor_model.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 71, "func_end_lineno": 113, "func_code": "def load_gzip_compressed_csv_data(\n data_filename: str,\n data_module: str = DATA_MODULE,\n encoding=\"utf-8\",\n datetime_index: bool = True,\n) -> pd.DataFrame:\n \"\"\"Load gzip-compressed csv files with `importlib.resources`.\n\n 1) Open resource file with `importlib.resources.open_binary`\n 2) Decompress csv file with `gzip.open`\n 3) Load decompressed data with `pd.read_csv`\n\n Parameters\n ----------\n data_filename : str\n Name of gzip-compressed csv file (`'*.csv.gz'`) to be loaded from\n `data_module/data_file_name`. For example `'SPX500.csv.gz'`.\n\n data_module : str or module, default='skfolio.datasets.data'\n Module where data lives. The default is `'skfolio.datasets.data'`.\n\n encoding : str, default=\"utf-8\"\n Name of the encoding that the gzip-decompressed file will be\n decoded with. The default is 'utf-8'.\n\n datetime_index: bool, default=True\n If this is set to True, the DataFrame index is converted to datetime with\n format=\"%Y-%m-%d\".\n The default is `True`.\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n DataFrame with each row representing one observation and each column\n representing the asset price of a given observation.\n \"\"\"\n path = resources.files(data_module).joinpath(data_filename)\n with path.open(\"rb\") as compressed_file:\n compressed_file = gzip.open(compressed_file, mode=\"rt\", encoding=encoding)\n df = pd.read_csv(compressed_file, sep=\",\", index_col=0)\n if datetime_index:\n df.index = pd.to_datetime(df.index, format=\"%Y-%m-%d\")\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 168, "func_end_lineno": 204, "func_code": "def load_sp500_dataset() -> pd.DataFrame:\n \"\"\"Load the prices of 20 assets from the S&P 500 Index composition.\n\n This dataset is composed of the daily prices of 20 assets from the S&P 500\n composition starting from 1990-01-02 up to 2022-12-28.\n\n The data comes from the Yahoo public API.\n The price is the adjusted close which is the closing price after adjustments for\n all applicable splits and dividend distributions.\n The adjustment uses appropriate split and dividend multipliers, adhering to\n the Center for Research in Security Prices (CRSP) standards.\n\n ============== ==================\n Observations 8313\n Assets 20\n ============== ==================\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n Prices DataFrame\n\n Examples\n --------\n >>> from skfolio.datasets import load_sp500_dataset\n >>> prices = load_sp500_dataset()\n >>> prices.head()\n AAPL AMD BAC ... UNH WMT XOM\n 1990-01-02 0.332589 4.1250 11.65625 ... 0.382813 5.890625 12.5000\n 1990-01-03 0.334821 4.0000 11.75000 ... 0.375000 5.890625 12.3750\n 1990-01-04 0.335938 3.9375 11.50000 ... 0.371094 5.859375 12.2500\n 1990-01-05 0.337054 3.8125 11.25000 ... 0.355469 5.796875 12.1875\n 1990-01-08 0.339286 3.8125 11.31250 ... 0.347656 5.875000 12.3750\n \"\"\"\n data_filename = \"sp500_dataset.csv.gz\"\n df = load_gzip_compressed_csv_data(data_filename)\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 247, "func_end_lineno": 292, "func_code": "def load_factors_dataset() -> pd.DataFrame:\n \"\"\"Load the prices of 5 factor ETFs.\n\n This dataset is composed of the daily prices of 5 ETF representing common factors\n starting from 2014-01-02 up to 2022-12-28.\n\n The factors are:\n\n * \"MTUM\": Momentum\n * \"QUAL\": Quality\n * \"SIZE\": Size\n * \"VLUE\": Value\n * \"USMV\": low volatility\n\n The data comes from the Yahoo public API.\n The price is the adjusted close which is the closing price after adjustments for\n all applicable splits and dividend distributions.\n The adjustment uses appropriate split and dividend multipliers, adhering to\n the Center for Research in Security Prices (CRSP) standards.\n\n ============== ==================\n Observations 2264\n Assets 5\n ============== ==================\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n Prices DataFrame\n\n Examples\n --------\n >>> from skfolio.datasets import load_factors_dataset\n >>> prices = load_factors_dataset()\n >>> prices.head()\n MTUM QUAL SIZE USMV VLUE\n Date\n 2014-01-02 52.704 48.351 48.986 29.338 47.054\n 2014-01-03 52.792 48.256 48.722 29.330 46.999\n 2014-01-06 52.677 48.067 48.722 29.263 46.991\n 2014-01-07 53.112 48.455 48.731 29.430 47.253\n 2014-01-08 53.502 48.437 48.731 29.422 47.253\n \"\"\"\n data_filename = \"factors_dataset.csv.gz\"\n df = load_gzip_compressed_csv_data(data_filename)\n return df"}, {"class_start_lineno": 17, "class_end_lineno": 202, "func_start_lineno": 93, "func_end_lineno": 106, "func_code": " def get_metadata_routing(self):\n # noinspection PyTypeChecker\n router = (\n skm.MetadataRouter(owner=self.__class__.__name__)\n .add(\n mu_estimator=self.mu_estimator,\n method_mapping=skm.MethodMapping().add(caller=\"fit\", callee=\"fit\"),\n )\n .add(\n covariance_estimator=self.covariance_estimator,\n method_mapping=skm.MethodMapping().add(caller=\"fit\", callee=\"fit\"),\n )\n )\n return router"}, {"class_start_lineno": 17, "class_end_lineno": 202, "func_start_lineno": 108, "func_end_lineno": 202, "func_code": " def fit(self, X: npt.ArrayLike, y=None, **fit_params) -> \"EmpiricalPrior\":\n \"\"\"Fit the Empirical Prior estimator.\n\n Parameters\n ----------\n X : array-like of shape (n_observations, n_assets)\n Price returns of the assets.\n\n y : Ignored\n Not used, present for API consistency by convention.\n\n **fit_params : dict\n Parameters to pass to the underlying estimators.\n Only available if `enable_metadata_routing=True`, which can be\n set by using ``sklearn.set_config(enable_metadata_routing=True)``.\n See :ref:`Metadata Routing User Guide ` for\n more details.\n\n Returns\n -------\n self : EmpiricalPrior\n Fitted estimator.\n \"\"\"\n routed_params = skm.process_routing(self, \"fit\", **fit_params)\n\n self.mu_estimator_ = check_estimator(\n self.mu_estimator,\n default=EmpiricalMu(),\n check_type=BaseMu,\n )\n self.covariance_estimator_ = check_estimator(\n self.covariance_estimator,\n default=EmpiricalCovariance(),\n check_type=BaseCovariance,\n )\n # fitting estimators\n if not self.is_log_normal:\n if self.investment_horizon is not None:\n raise ValueError(\n \"`investment_horizon` must be `None` when \"\n \"`is_log_normal` is `False`\"\n )\n # Expected returns\n # noinspection PyArgumentList\n self.mu_estimator_.fit(X, y, **routed_params.mu_estimator.fit)\n mu = self.mu_estimator_.mu_\n\n # Covariance\n # noinspection PyArgumentList\n self.covariance_estimator_.fit(\n X, y, **routed_params.covariance_estimator.fit\n )\n covariance = self.covariance_estimator_.covariance_\n else:\n if self.investment_horizon is None:\n raise ValueError(\n \"`investment_horizon` must be provided when \"\n \"`is_log_normal` is `True`\"\n )\n # Convert linear returns to log returns\n X_log = np.log(1 + X)\n y_log = np.log(1 + y) if y is not None else None\n\n # Estimates the moments on the log returns\n # Expected returns\n # noinspection PyArgumentList\n self.mu_estimator_.fit(X_log, y_log, **routed_params.mu_estimator.fit)\n mu = self.mu_estimator_.mu_\n\n # Covariance\n # noinspection PyArgumentList\n self.covariance_estimator_.fit(\n X_log, y_log, **routed_params.covariance_estimator.fit\n )\n covariance = self.covariance_estimator_.covariance_\n\n # Using the property of aggregation across time we scale this distribution\n # to the investment horizon by the “square-root rule”.\n mu *= self.investment_horizon\n covariance *= self.investment_horizon\n\n # We convert it into a distribution of linear returns over the investment\n # horizon\n mu = np.exp(mu + 0.5 * np.diag(covariance))\n covariance = np.outer(mu, mu) * (np.exp(covariance) - 1)\n\n # we validate and convert to numpy after all models have been fitted to keep\n # features names information.\n X = skv.validate_data(self, X)\n self.prior_model_ = PriorModel(\n mu=mu,\n covariance=covariance,\n returns=X,\n )\n return self"}], "type": ["function_empty", "TDD"], "node": ["skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.datasets._base.load_sp500_dataset", "skfolio.datasets._base.load_factors_dataset", "skfolio.prior._empirical.EmpiricalPrior.get_metadata_routing", "skfolio.prior._empirical.EmpiricalPrior.fit"], "language": "Python", "toolfunc_count": 4, "func_count": 5, "pytest_info": {"total_num": 8, "base_passed_num": 0}} {"id": ["skfolio.src.skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.src.skfolio.datasets._base.load_sp500_dataset", "skfolio.src.skfolio.measures._measures.variance", "skfolio.src.skfolio.measures._measures.standard_deviation"], "project": "skfolio", "origin_file": ["skfolio/datasets/_base.py", "skfolio/datasets/_base.py", "skfolio/measures/_measures.py", "skfolio/measures/_measures.py"], "test_list": ["tests/test_portfolio/test_multi_period_portfolio.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 71, "func_end_lineno": 113, "func_code": "def load_gzip_compressed_csv_data(\n data_filename: str,\n data_module: str = DATA_MODULE,\n encoding=\"utf-8\",\n datetime_index: bool = True,\n) -> pd.DataFrame:\n \"\"\"Load gzip-compressed csv files with `importlib.resources`.\n\n 1) Open resource file with `importlib.resources.open_binary`\n 2) Decompress csv file with `gzip.open`\n 3) Load decompressed data with `pd.read_csv`\n\n Parameters\n ----------\n data_filename : str\n Name of gzip-compressed csv file (`'*.csv.gz'`) to be loaded from\n `data_module/data_file_name`. For example `'SPX500.csv.gz'`.\n\n data_module : str or module, default='skfolio.datasets.data'\n Module where data lives. The default is `'skfolio.datasets.data'`.\n\n encoding : str, default=\"utf-8\"\n Name of the encoding that the gzip-decompressed file will be\n decoded with. The default is 'utf-8'.\n\n datetime_index: bool, default=True\n If this is set to True, the DataFrame index is converted to datetime with\n format=\"%Y-%m-%d\".\n The default is `True`.\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n DataFrame with each row representing one observation and each column\n representing the asset price of a given observation.\n \"\"\"\n path = resources.files(data_module).joinpath(data_filename)\n with path.open(\"rb\") as compressed_file:\n compressed_file = gzip.open(compressed_file, mode=\"rt\", encoding=encoding)\n df = pd.read_csv(compressed_file, sep=\",\", index_col=0)\n if datetime_index:\n df.index = pd.to_datetime(df.index, format=\"%Y-%m-%d\")\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 168, "func_end_lineno": 204, "func_code": "def load_sp500_dataset() -> pd.DataFrame:\n \"\"\"Load the prices of 20 assets from the S&P 500 Index composition.\n\n This dataset is composed of the daily prices of 20 assets from the S&P 500\n composition starting from 1990-01-02 up to 2022-12-28.\n\n The data comes from the Yahoo public API.\n The price is the adjusted close which is the closing price after adjustments for\n all applicable splits and dividend distributions.\n The adjustment uses appropriate split and dividend multipliers, adhering to\n the Center for Research in Security Prices (CRSP) standards.\n\n ============== ==================\n Observations 8313\n Assets 20\n ============== ==================\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n Prices DataFrame\n\n Examples\n --------\n >>> from skfolio.datasets import load_sp500_dataset\n >>> prices = load_sp500_dataset()\n >>> prices.head()\n AAPL AMD BAC ... UNH WMT XOM\n 1990-01-02 0.332589 4.1250 11.65625 ... 0.382813 5.890625 12.5000\n 1990-01-03 0.334821 4.0000 11.75000 ... 0.375000 5.890625 12.3750\n 1990-01-04 0.335938 3.9375 11.50000 ... 0.371094 5.859375 12.2500\n 1990-01-05 0.337054 3.8125 11.25000 ... 0.355469 5.796875 12.1875\n 1990-01-08 0.339286 3.8125 11.31250 ... 0.347656 5.875000 12.3750\n \"\"\"\n data_filename = \"sp500_dataset.csv.gz\"\n df = load_gzip_compressed_csv_data(data_filename)\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 633, "func_start_lineno": 82, "func_end_lineno": 95, "func_code": "def variance(returns: np.ndarray) -> float:\n \"\"\"Compute the variance (second moment).\n\n Parameters\n ----------\n returns : ndarray of shape (n_observations,)\n Vector of returns.\n\n Returns\n -------\n value : float\n Variance.\n \"\"\"\n return returns.var(ddof=1)"}, {"class_start_lineno": 1, "class_end_lineno": 633, "func_start_lineno": 127, "func_end_lineno": 140, "func_code": "def standard_deviation(returns: np.ndarray) -> float:\n \"\"\"Compute the standard-deviation (square root of the second moment).\n\n Parameters\n ----------\n returns : ndarray of shape (n_observations,)\n Vector of returns.\n\n Returns\n -------\n value : float\n Standard-deviation.\n \"\"\"\n return np.sqrt(variance(returns=returns))"}], "type": ["function_empty"], "node": ["skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.datasets._base.load_sp500_dataset", "skfolio.measures._measures.variance", "skfolio.measures._measures.standard_deviation"], "language": "Python", "toolfunc_count": 4, "func_count": 4, "pytest_info": {"total_num": 106, "base_passed_num": 0}} {"id": ["skfolio.src.skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.src.skfolio.datasets._base.load_sp500_dataset", "skfolio.src.skfolio.utils.tools.input_to_array", "skfolio.src.skfolio.portfolio._portfolio.Portfolio::__init__"], "project": "skfolio", "origin_file": ["skfolio/datasets/_base.py", "skfolio/datasets/_base.py", "skfolio/utils/tools.py", "skfolio/portfolio/_portfolio.py"], "test_list": ["tests/test_pre_selection/test_select_k_extremes.py", "tests/test_pre_selection/test_select_non_dominated.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 71, "func_end_lineno": 113, "func_code": "def load_gzip_compressed_csv_data(\n data_filename: str,\n data_module: str = DATA_MODULE,\n encoding=\"utf-8\",\n datetime_index: bool = True,\n) -> pd.DataFrame:\n \"\"\"Load gzip-compressed csv files with `importlib.resources`.\n\n 1) Open resource file with `importlib.resources.open_binary`\n 2) Decompress csv file with `gzip.open`\n 3) Load decompressed data with `pd.read_csv`\n\n Parameters\n ----------\n data_filename : str\n Name of gzip-compressed csv file (`'*.csv.gz'`) to be loaded from\n `data_module/data_file_name`. For example `'SPX500.csv.gz'`.\n\n data_module : str or module, default='skfolio.datasets.data'\n Module where data lives. The default is `'skfolio.datasets.data'`.\n\n encoding : str, default=\"utf-8\"\n Name of the encoding that the gzip-decompressed file will be\n decoded with. The default is 'utf-8'.\n\n datetime_index: bool, default=True\n If this is set to True, the DataFrame index is converted to datetime with\n format=\"%Y-%m-%d\".\n The default is `True`.\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n DataFrame with each row representing one observation and each column\n representing the asset price of a given observation.\n \"\"\"\n path = resources.files(data_module).joinpath(data_filename)\n with path.open(\"rb\") as compressed_file:\n compressed_file = gzip.open(compressed_file, mode=\"rt\", encoding=encoding)\n df = pd.read_csv(compressed_file, sep=\",\", index_col=0)\n if datetime_index:\n df.index = pd.to_datetime(df.index, format=\"%Y-%m-%d\")\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 168, "func_end_lineno": 204, "func_code": "def load_sp500_dataset() -> pd.DataFrame:\n \"\"\"Load the prices of 20 assets from the S&P 500 Index composition.\n\n This dataset is composed of the daily prices of 20 assets from the S&P 500\n composition starting from 1990-01-02 up to 2022-12-28.\n\n The data comes from the Yahoo public API.\n The price is the adjusted close which is the closing price after adjustments for\n all applicable splits and dividend distributions.\n The adjustment uses appropriate split and dividend multipliers, adhering to\n the Center for Research in Security Prices (CRSP) standards.\n\n ============== ==================\n Observations 8313\n Assets 20\n ============== ==================\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n Prices DataFrame\n\n Examples\n --------\n >>> from skfolio.datasets import load_sp500_dataset\n >>> prices = load_sp500_dataset()\n >>> prices.head()\n AAPL AMD BAC ... UNH WMT XOM\n 1990-01-02 0.332589 4.1250 11.65625 ... 0.382813 5.890625 12.5000\n 1990-01-03 0.334821 4.0000 11.75000 ... 0.375000 5.890625 12.3750\n 1990-01-04 0.335938 3.9375 11.50000 ... 0.371094 5.859375 12.2500\n 1990-01-05 0.337054 3.8125 11.25000 ... 0.355469 5.796875 12.1875\n 1990-01-08 0.339286 3.8125 11.31250 ... 0.347656 5.875000 12.3750\n \"\"\"\n data_filename = \"sp500_dataset.csv.gz\"\n df = load_gzip_compressed_csv_data(data_filename)\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 787, "func_start_lineno": 357, "func_end_lineno": 442, "func_code": "def input_to_array(\n items: dict | npt.ArrayLike,\n n_assets: int,\n fill_value: Any,\n dim: int,\n assets_names: np.ndarray | None,\n name: str,\n) -> np.ndarray:\n \"\"\"Convert a collection of items (array-like or dictionary) into\n a numpy array and verify its shape.\n\n Parameters\n ----------\n items : np.ndarray | dict | list\n Items to verify and convert to array.\n\n n_assets : int\n Expected number of assets.\n Used to verify the shape of the converted array.\n\n fill_value : Any\n When `items` is a dictionary, elements that are not in `asset_names` are filled\n with `fill_value` in the converted array.\n\n dim : int\n Dimension of the final array.\n Possible values are `1` or `2`.\n\n assets_names : ndarray, optional\n Asset names used when `items` is a dictionary.\n\n name : str\n Name of the items used for error messages.\n\n Returns\n -------\n values : ndarray of shape (n_assets) for dim=1 or (n_groups, n_assets) for dim=2\n Converted array.\n \"\"\"\n if dim not in [1, 2]:\n raise ValueError(f\"dim must be 1 or 2, got {dim}\")\n if isinstance(items, dict):\n if assets_names is None:\n raise ValueError(\n f\"If `{name}` is provided as a dictionary, you must input `X` as a\"\n \" DataFrame with assets names in columns\"\n )\n if dim == 1:\n arr = np.array([items.get(asset, fill_value) for asset in assets_names])\n else:\n # add assets and convert dict to ordered array\n arr = {}\n for asset in assets_names:\n elem = items.get(asset)\n if elem is None:\n elem = [asset]\n elif np.isscalar(elem):\n elem = [asset, elem]\n else:\n elem = [asset, *elem]\n arr[asset] = elem\n arr = (\n pd.DataFrame.from_dict(arr, orient=\"index\")\n .loc[assets_names]\n .to_numpy()\n .T\n )\n else:\n arr = np.asarray(items)\n\n if arr.ndim != dim:\n raise ValueError(f\"`{name}` must be a {dim}D array, got a {arr.ndim}D array\")\n\n if not isinstance(fill_value, str) and np.isnan(arr).any():\n raise ValueError(f\"`{name}` contains NaN\")\n\n if arr.shape[-1] != n_assets:\n if dim == 1:\n s = \"(n_assets,)\"\n else:\n s = \"(n_groups, n_assets)\"\n raise ValueError(\n f\"`{name}` must be a of shape {s} with n_assets={n_assets}, \"\n f\"got {arr.shape[0]}\"\n )\n return arr"}, {"class_start_lineno": 29, "class_end_lineno": 861, "func_start_lineno": 432, "func_end_lineno": 568, "func_code": " def __init__(\n self,\n X: npt.ArrayLike,\n weights: skt.MultiInput,\n previous_weights: skt.MultiInput = None,\n transaction_costs: skt.MultiInput = None,\n management_fees: skt.MultiInput = None,\n risk_free_rate: float = 0,\n name: str | None = None,\n tag: str | None = None,\n annualized_factor: float = 252,\n fitness_measures: list[skt.Measure] | None = None,\n compounded: bool = False,\n min_acceptable_return: float | None = None,\n value_at_risk_beta: float = 0.95,\n entropic_risk_measure_theta: float = 1,\n entropic_risk_measure_beta: float = 0.95,\n cvar_beta: float = 0.95,\n evar_beta: float = 0.95,\n drawdown_at_risk_beta: float = 0.95,\n cdar_beta: float = 0.95,\n edar_beta: float = 0.95,\n ):\n # extract assets names from X\n assets = None\n observations = None\n if hasattr(X, \"columns\"):\n assets = np.asarray(X.columns, dtype=object)\n observations = np.asarray(X.index)\n\n # We don't perform extensive checks (like in check_X) for faster instantiation.\n rets = np.asarray(X)\n if rets.ndim != 2:\n raise ValueError(\"`X` must be a 2D array-like\")\n\n n_observations, n_assets = rets.shape\n\n weights = input_to_array(\n items=weights,\n n_assets=n_assets,\n fill_value=0,\n dim=1,\n assets_names=assets,\n name=\"weights\",\n )\n\n if previous_weights is None:\n previous_weights = np.zeros(n_assets)\n else:\n previous_weights = input_to_array(\n items=previous_weights,\n n_assets=n_assets,\n fill_value=0,\n dim=1,\n assets_names=assets,\n name=\"previous_weights\",\n )\n\n if transaction_costs is None:\n transaction_costs = 0\n elif not np.isscalar(transaction_costs):\n transaction_costs = input_to_array(\n items=transaction_costs,\n n_assets=n_assets,\n fill_value=0,\n dim=1,\n assets_names=assets,\n name=\"transaction_costs\",\n )\n\n if management_fees is None:\n management_fees = 0\n elif not np.isscalar(management_fees):\n management_fees = input_to_array(\n items=management_fees,\n n_assets=n_assets,\n fill_value=0,\n dim=1,\n assets_names=assets,\n name=\"management_fees\",\n )\n\n # Default observations and assets if X is not a DataFrame\n if observations is None or len(observations) == 0:\n observations = np.arange(n_observations)\n\n if assets is None or len(assets) == 0:\n assets = default_asset_names(n_assets=n_assets)\n\n # Computing portfolio returns\n if np.isscalar(transaction_costs) and transaction_costs == 0:\n total_cost = 0\n else:\n total_cost = (transaction_costs * abs(previous_weights - weights)).sum()\n\n if np.isscalar(management_fees) and management_fees == 0:\n total_fee = 0\n else:\n total_fee = (management_fees * weights).sum()\n\n returns = weights @ rets.T - total_cost - total_fee\n\n if np.any(np.isnan(returns)):\n raise ValueError(\"NaN found in `returns`\")\n\n super().__init__(\n returns=returns,\n observations=observations,\n name=name,\n tag=tag,\n fitness_measures=fitness_measures,\n compounded=compounded,\n risk_free_rate=risk_free_rate,\n annualized_factor=annualized_factor,\n min_acceptable_return=min_acceptable_return,\n value_at_risk_beta=value_at_risk_beta,\n cvar_beta=cvar_beta,\n entropic_risk_measure_theta=entropic_risk_measure_theta,\n entropic_risk_measure_beta=entropic_risk_measure_beta,\n evar_beta=evar_beta,\n drawdown_at_risk_beta=drawdown_at_risk_beta,\n cdar_beta=cdar_beta,\n edar_beta=edar_beta,\n )\n self._loaded = False\n # We save the original array-like object and not the numpy copy for improved\n # memory\n self.X = X\n self.assets = assets\n self.n_assets = n_assets\n self.weights = weights\n self.transaction_costs = transaction_costs\n self.management_fees = management_fees\n self.previous_weights = previous_weights\n self.total_cost = total_cost\n self.total_fee = total_fee\n self._loaded = True"}], "type": ["function_empty", "TDD"], "node": ["skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.datasets._base.load_sp500_dataset", "skfolio.utils.tools.input_to_array", "skfolio.portfolio._portfolio.Portfolio.__init__"], "language": "Python", "toolfunc_count": 2, "func_count": 4, "pytest_info": {"total_num": 2, "base_passed_num": 0}} {"id": ["skfolio.src.skfolio.utils.tools.safe_indexing", "skfolio.src.skfolio.utils.tools.safe_split", "skfolio.src.skfolio.model_selection._validation.cross_val_predict", "skfolio.src.skfolio.utils.tools._check_method_params", "skfolio.src.skfolio.utils.tools.fit_and_predict"], "project": "skfolio", "origin_file": ["skfolio/utils/tools.py", "skfolio/utils/tools.py", "skfolio/model_selection/_validation.py", "skfolio/utils/tools.py", "skfolio/utils/tools.py"], "test_list": ["tests/test_pre_selection/test_select_non_expiring.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 787, "func_start_lineno": 190, "func_end_lineno": 219, "func_code": "def safe_indexing(\n X: npt.ArrayLike | pd.DataFrame, indices: npt.ArrayLike | None, axis: int = 0\n):\n \"\"\"Return rows, items or columns of X using indices.\n\n Parameters\n ----------\n X : array-like\n Data from which to sample rows.\n\n indices : array-like, optional\n Indices of rows or columns.\n The default (`None`) is to select the entire data.\n\n axis : int, default=0\n The axis along which `X` will be sub-sampled. `axis=0` will select\n rows while `axis=1` will select columns.\n\n Returns\n -------\n subset :\n Subset of X on axis 0.\n \"\"\"\n if indices is None:\n return X\n if hasattr(X, \"iloc\"):\n return X.take(indices, axis=axis)\n if axis == 0:\n return X[indices]\n return X[:, indices]"}, {"class_start_lineno": 1, "class_end_lineno": 787, "func_start_lineno": 222, "func_end_lineno": 261, "func_code": "def safe_split(\n X: npt.ArrayLike,\n y: npt.ArrayLike | None = None,\n indices: np.ndarray | None = None,\n axis: int = 0,\n):\n \"\"\"Create subset of dataset.\n\n Slice X, y according to indices for cross-validation.\n\n Parameters\n ----------\n X : array-like\n Data to be indexed.\n\n y : array-like\n Data to be indexed.\n\n indices : ndarray of int, optional\n Rows or columns to select from X and y.\n The default (`None`) is to select the entire data.\n\n axis : int, default=0\n The axis along which `X` will be sub-sampled. `axis=0` will select\n rows while `axis=1` will select columns.\n\n Returns\n -------\n X_subset : array-like\n Indexed data.\n\n y_subset : array-like\n Indexed targets.\n \"\"\"\n X_subset = safe_indexing(X, indices=indices, axis=axis)\n if y is not None:\n y_subset = safe_indexing(y, indices=indices, axis=axis)\n else:\n y_subset = None\n return X_subset, y_subset"}, {"class_start_lineno": 1, "class_end_lineno": 254, "func_start_lineno": 38, "func_end_lineno": 254, "func_code": "def cross_val_predict(\n estimator: skb.BaseEstimator,\n X: npt.ArrayLike,\n y: npt.ArrayLike = None,\n cv: sks.BaseCrossValidator | BaseCombinatorialCV | int | None = None,\n n_jobs: int | None = None,\n method: str = \"predict\",\n verbose: int = 0,\n params: dict | None = None,\n pre_dispatch: str = \"2*n_jobs\",\n column_indices: np.ndarray | None = None,\n portfolio_params: dict | None = None,\n) -> MultiPeriodPortfolio | Population:\n \"\"\"Generate cross-validated `Portfolios` estimates.\n\n The data is split according to the `cv` parameter.\n The optimization estimator is fitted on the training set and portfolios are\n predicted on the corresponding test set.\n\n For non-combinatorial cross-validation like `Kfold`, the output is the predicted\n :class:`~skfolio.portfolio.MultiPeriodPortfolio` where\n each :class:`~skfolio.portfolio.Portfolio` corresponds to the prediction on each\n train/test pair (`k` portfolios for `Kfold`).\n\n For combinatorial cross-validation\n like :class:`~skfolio.model_selection.CombinatorialPurgedCV`, the output is the\n predicted :class:`~skfolio.population.Population` of multiple\n :class:`~skfolio.portfolio.MultiPeriodPortfolio` (each test outputs are a\n collection of multiple paths instead of one single path).\n\n Parameters\n ----------\n estimator : BaseOptimization\n :ref:`Optimization estimators ` use to fit the data.\n\n X : array-like of shape (n_observations, n_assets)\n Price returns of the assets.\n\n y : array-like of shape (n_observations, n_targets), optional\n Target data (optional).\n For example, the price returns of the factors.\n\n cv : int | cross-validation generator, optional\n Determines the cross-validation splitting strategy.\n Possible inputs for cv are:\n\n * None, to use the default 5-fold cross validation,\n * int, to specify the number of folds in a `(Stratified)KFold`,\n * `CV splitter`,\n * An iterable that generates (train, test) splits as arrays of indices.\n\n n_jobs : int, optional\n The number of jobs to run in parallel for `fit` of all `estimators`.\n `None` means 1 unless in a `joblib.parallel_backend` context. -1 means\n using all processors.\n\n method : str\n Invokes the passed method name of the passed estimator.\n\n verbose : int, default=0\n The verbosity level.\n\n params : dict, optional\n Parameters to pass to the underlying estimator's ``fit`` and the CV splitter.\n\n pre_dispatch : int or str, default='2*n_jobs'\n Controls the number of jobs that get dispatched during parallel\n execution. Reducing this number can be useful to avoid an\n explosion of memory consumption when more jobs get dispatched\n than CPUs can process. This parameter can be:\n\n * None, in which case all the jobs are immediately\n created and spawned. Use this for lightweight and\n fast-running jobs, to avoid delays due to on-demand\n spawning of the jobs\n\n * An int, giving the exact number of total jobs that are\n spawned\n\n * A str, giving an expression as a function of n_jobs,\n as in '2*n_jobs'\n\n column_indices : ndarray, optional\n Indices of the `X` columns to cross-validate on.\n\n portfolio_params : dict, optional\n Additional portfolio parameters passed to `MultiPeriodPortfolio`.\n\n Returns\n -------\n predictions : MultiPeriodPortfolio | Population\n This is the result of calling `predict`\n \"\"\"\n params = {} if params is None else params\n\n X, y = safe_split(X, y, indices=column_indices, axis=1)\n X, y = sku.indexable(X, y)\n\n if _routing_enabled():\n # For estimators, a MetadataRouter is created in get_metadata_routing\n # methods. For these router methods, we create the router to use\n # `process_routing` on it.\n # noinspection PyTypeChecker\n router = (\n skm.MetadataRouter(owner=\"cross_validate\")\n .add(\n splitter=cv,\n method_mapping=skm.MethodMapping().add(caller=\"fit\", callee=\"split\"),\n )\n .add(\n estimator=estimator,\n method_mapping=skm.MethodMapping().add(caller=\"fit\", callee=\"fit\"),\n )\n )\n try:\n routed_params = skm.process_routing(router, \"fit\", **params)\n except ske.UnsetMetadataPassedError as e:\n # The default exception would mention `fit` since in the above\n # `process_routing` code, we pass `fit` as the caller. However,\n # the user is not calling `fit` directly, so we change the message\n # to make it more suitable for this case.\n unrequested_params = sorted(e.unrequested_params)\n raise ske.UnsetMetadataPassedError(\n message=(\n f\"{unrequested_params} are passed to `cross_val_predict` but are\"\n \" not explicitly set as requested or not requested for\"\n f\" cross_validate's estimator: {estimator.__class__.__name__} Call\"\n \" `.set_fit_request({{metadata}}=True)` on the estimator for\"\n f\" each metadata in {unrequested_params} that you want to use and\"\n \" `metadata=False` for not using it. See the Metadata Routing User\"\n \" guide \"\n \" for more information.\"\n ),\n unrequested_params=e.unrequested_params,\n routed_params=e.routed_params,\n ) from None\n else:\n routed_params = sku.Bunch()\n routed_params.splitter = sku.Bunch(split={})\n routed_params.estimator = sku.Bunch(fit=params)\n\n cv = sks.check_cv(cv, y)\n splits = list(cv.split(X, y, **routed_params.splitter.split))\n\n portfolio_params = {} if portfolio_params is None else portfolio_params.copy()\n\n # We ensure that the folds are not shuffled\n if not isinstance(cv, BaseCombinatorialCV):\n try:\n if cv.shuffle:\n raise ValueError(\n \"`cross_val_predict` only works with cross-validation setting\"\n \" `shuffle=False`\"\n )\n except AttributeError:\n # If we cannot find the attribute shuffle, we check if the first folds\n # are shuffled\n for fold in splits[0]:\n if not np.all(np.diff(fold) > 0):\n raise ValueError(\n \"`cross_val_predict` only works with un-shuffled folds\"\n ) from None\n\n # We clone the estimator to make sure that all the folds are independent\n # and that it is pickle-able.\n parallel = skp.Parallel(n_jobs=n_jobs, verbose=verbose, pre_dispatch=pre_dispatch)\n # TODO remove when https://github.com/joblib/joblib/issues/1071 is fixed\n # noinspection PyCallingNonCallable\n predictions = parallel(\n skp.delayed(fit_and_predict)(\n sk.clone(estimator),\n X,\n y,\n train=train,\n test=test,\n fit_params=routed_params.estimator.fit,\n method=method,\n )\n for train, test in splits\n )\n\n if isinstance(cv, BaseCombinatorialCV):\n path_ids = cv.get_path_ids()\n path_nb = np.max(path_ids) + 1\n portfolios = [[] for _ in range(path_nb)]\n for i, prediction in enumerate(predictions):\n for j, p in enumerate(prediction):\n path_id = path_ids[i, j]\n portfolios[path_id].append(p)\n name = portfolio_params.pop(\"name\", \"path\")\n pred = Population(\n [\n MultiPeriodPortfolio(\n name=f\"{name}_{i}\", portfolios=portfolios[i], **portfolio_params\n )\n for i in range(path_nb)\n ]\n )\n else:\n # We need to re-order the test folds in case they were un-ordered by the\n # CV generator.\n # Because the tests folds are not shuffled, we use the first index of each\n # fold to order them.\n test_indices = np.concatenate([test for _, test in splits])\n if np.unique(test_indices, axis=0).shape[0] != test_indices.shape[0]:\n raise ValueError(\n \"`cross_val_predict` only works with non-duplicated test indices\"\n )\n test_indices = [test for _, test in splits]\n sorted_fold_id = np.argsort([x[0] for x in test_indices])\n pred = MultiPeriodPortfolio(\n portfolios=[predictions[fold_id] for fold_id in sorted_fold_id],\n check_observations_order=False,\n **portfolio_params,\n )\n\n return pred"}, {"class_start_lineno": 1, "class_end_lineno": 787, "func_start_lineno": 147, "func_end_lineno": 187, "func_code": "def _check_method_params(\n X: npt.ArrayLike, params: dict, indices: np.ndarray = None, axis: int = 0\n):\n \"\"\"Check and validate the parameters passed to a specific\n method like `fit`.\n\n Parameters\n ----------\n X : array-like of shape (n_samples, n_features)\n Data array.\n\n params : dict\n Dictionary containing the parameters passed to the method.\n\n indices : ndarray of shape (n_samples,), default=None\n Indices to be selected if the parameter has the same size as `X`.\n\n axis : int, default=0\n The axis along which `X` will be sub-sampled. `axis=0` will select\n rows while `axis=1` will select columns.\n\n Returns\n -------\n method_params_validated : dict\n Validated parameters. We ensure that the values support indexing.\n \"\"\"\n # noinspection PyUnresolvedReferences\n n_observations = X.shape[0]\n method_params_validated = {}\n for param_key, param_value in params.items():\n if param_value.shape[0] != n_observations:\n raise ValueError(\n f\"param_key has wrong number of observations, \"\n f\"received={param_value.shape[0]}, \"\n f\"expected={n_observations}\"\n )\n method_params_validated[param_key] = _make_indexable(param_value)\n method_params_validated[param_key] = safe_indexing(\n X=method_params_validated[param_key], indices=indices, axis=axis\n )\n return method_params_validated"}, {"class_start_lineno": 1, "class_end_lineno": 787, "func_start_lineno": 618, "func_end_lineno": 685, "func_code": "def fit_and_predict(\n estimator: Any,\n X: npt.ArrayLike,\n y: npt.ArrayLike | None,\n train: np.ndarray,\n test: np.ndarray | list[np.ndarray],\n fit_params: dict,\n method: str,\n column_indices: np.ndarray | None = None,\n) -> npt.ArrayLike | list[npt.ArrayLike]:\n \"\"\"Fit the estimator and predict values for a given dataset split.\n\n Parameters\n ----------\n estimator : estimator object implementing 'fit' and 'predict'\n The object to use to fit the data.\n\n X : array-like of shape (n_observations, n_assets)\n The data to fit.\n\n y : array-like of shape (n_observations, n_factors) or None\n The factor array if provided\n\n train : ndarray of int of shape (n_train_observations,)\n Indices of training samples.\n\n test : ndarray of int of shape (n_test_samples,) or list of ndarray\n Indices of test samples or list of indices.\n\n fit_params : dict\n Parameters that will be passed to `estimator.fit`.\n\n method : str\n Invokes the passed method name of the passed estimator.\n\n column_indices : ndarray, optional\n Indices of columns to select.\n The default (`None`) is to select all columns.\n\n Returns\n -------\n predictions : array-like or list of array-like\n If `test` is an array, it returns the array-like result of calling\n 'estimator.method' on `test`.\n Otherwise, if `test` is a list of arrays, it returns the list of array-like\n results of calling 'estimator.method' on each test set in `test`.\n \"\"\"\n fit_params = fit_params if fit_params is not None else {}\n fit_params = _check_method_params(X, params=fit_params, indices=train)\n\n X, y = safe_split(X, y, indices=column_indices, axis=1)\n X_train, y_train = safe_split(X, y, indices=train, axis=0)\n if y_train is None:\n estimator.fit(X_train, **fit_params)\n else:\n estimator.fit(X_train, y_train, **fit_params)\n func = getattr(estimator, method)\n\n if isinstance(test, list):\n predictions = []\n for t in test:\n X_test, _ = safe_split(X, indices=t, axis=0)\n predictions.append(func(X_test))\n else:\n X_test, _ = safe_split(X, indices=test, axis=0)\n predictions = func(X_test)\n\n return predictions"}], "type": ["function_empty", "TDD"], "node": ["skfolio.utils.tools.safe_indexing", "skfolio.utils.tools.safe_split", "skfolio.model_selection._validation.cross_val_predict", "skfolio.utils.tools._check_method_params", "skfolio.utils.tools.fit_and_predict"], "language": "Python", "toolfunc_count": 2, "func_count": 5, "pytest_info": {"total_num": 2, "base_passed_num": 1}} {"id": ["skfolio.src.skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.src.skfolio.datasets._base.load_factors_dataset", "skfolio.src.skfolio.datasets._base.load_sp500_dataset"], "project": "skfolio", "origin_file": ["skfolio/datasets/_base.py", "skfolio/datasets/_base.py", "skfolio/datasets/_base.py"], "test_list": ["tests/test_preprocessing/test_returns.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 71, "func_end_lineno": 113, "func_code": "def load_gzip_compressed_csv_data(\n data_filename: str,\n data_module: str = DATA_MODULE,\n encoding=\"utf-8\",\n datetime_index: bool = True,\n) -> pd.DataFrame:\n \"\"\"Load gzip-compressed csv files with `importlib.resources`.\n\n 1) Open resource file with `importlib.resources.open_binary`\n 2) Decompress csv file with `gzip.open`\n 3) Load decompressed data with `pd.read_csv`\n\n Parameters\n ----------\n data_filename : str\n Name of gzip-compressed csv file (`'*.csv.gz'`) to be loaded from\n `data_module/data_file_name`. For example `'SPX500.csv.gz'`.\n\n data_module : str or module, default='skfolio.datasets.data'\n Module where data lives. The default is `'skfolio.datasets.data'`.\n\n encoding : str, default=\"utf-8\"\n Name of the encoding that the gzip-decompressed file will be\n decoded with. The default is 'utf-8'.\n\n datetime_index: bool, default=True\n If this is set to True, the DataFrame index is converted to datetime with\n format=\"%Y-%m-%d\".\n The default is `True`.\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n DataFrame with each row representing one observation and each column\n representing the asset price of a given observation.\n \"\"\"\n path = resources.files(data_module).joinpath(data_filename)\n with path.open(\"rb\") as compressed_file:\n compressed_file = gzip.open(compressed_file, mode=\"rt\", encoding=encoding)\n df = pd.read_csv(compressed_file, sep=\",\", index_col=0)\n if datetime_index:\n df.index = pd.to_datetime(df.index, format=\"%Y-%m-%d\")\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 247, "func_end_lineno": 292, "func_code": "def load_factors_dataset() -> pd.DataFrame:\n \"\"\"Load the prices of 5 factor ETFs.\n\n This dataset is composed of the daily prices of 5 ETF representing common factors\n starting from 2014-01-02 up to 2022-12-28.\n\n The factors are:\n\n * \"MTUM\": Momentum\n * \"QUAL\": Quality\n * \"SIZE\": Size\n * \"VLUE\": Value\n * \"USMV\": low volatility\n\n The data comes from the Yahoo public API.\n The price is the adjusted close which is the closing price after adjustments for\n all applicable splits and dividend distributions.\n The adjustment uses appropriate split and dividend multipliers, adhering to\n the Center for Research in Security Prices (CRSP) standards.\n\n ============== ==================\n Observations 2264\n Assets 5\n ============== ==================\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n Prices DataFrame\n\n Examples\n --------\n >>> from skfolio.datasets import load_factors_dataset\n >>> prices = load_factors_dataset()\n >>> prices.head()\n MTUM QUAL SIZE USMV VLUE\n Date\n 2014-01-02 52.704 48.351 48.986 29.338 47.054\n 2014-01-03 52.792 48.256 48.722 29.330 46.999\n 2014-01-06 52.677 48.067 48.722 29.263 46.991\n 2014-01-07 53.112 48.455 48.731 29.430 47.253\n 2014-01-08 53.502 48.437 48.731 29.422 47.253\n \"\"\"\n data_filename = \"factors_dataset.csv.gz\"\n df = load_gzip_compressed_csv_data(data_filename)\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 168, "func_end_lineno": 204, "func_code": "def load_sp500_dataset() -> pd.DataFrame:\n \"\"\"Load the prices of 20 assets from the S&P 500 Index composition.\n\n This dataset is composed of the daily prices of 20 assets from the S&P 500\n composition starting from 1990-01-02 up to 2022-12-28.\n\n The data comes from the Yahoo public API.\n The price is the adjusted close which is the closing price after adjustments for\n all applicable splits and dividend distributions.\n The adjustment uses appropriate split and dividend multipliers, adhering to\n the Center for Research in Security Prices (CRSP) standards.\n\n ============== ==================\n Observations 8313\n Assets 20\n ============== ==================\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n Prices DataFrame\n\n Examples\n --------\n >>> from skfolio.datasets import load_sp500_dataset\n >>> prices = load_sp500_dataset()\n >>> prices.head()\n AAPL AMD BAC ... UNH WMT XOM\n 1990-01-02 0.332589 4.1250 11.65625 ... 0.382813 5.890625 12.5000\n 1990-01-03 0.334821 4.0000 11.75000 ... 0.375000 5.890625 12.3750\n 1990-01-04 0.335938 3.9375 11.50000 ... 0.371094 5.859375 12.2500\n 1990-01-05 0.337054 3.8125 11.25000 ... 0.355469 5.796875 12.1875\n 1990-01-08 0.339286 3.8125 11.31250 ... 0.347656 5.875000 12.3750\n \"\"\"\n data_filename = \"sp500_dataset.csv.gz\"\n df = load_gzip_compressed_csv_data(data_filename)\n return df"}], "type": ["function_empty"], "node": ["skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.datasets._base.load_factors_dataset", "skfolio.datasets._base.load_sp500_dataset"], "language": "Python", "toolfunc_count": 3, "func_count": 3, "pytest_info": {"total_num": 2, "base_passed_num": 0}} {"id": ["skfolio.src.skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.src.skfolio.datasets._base.load_sp500_dataset", "skfolio.src.skfolio.utils.equations._validate_groups", "skfolio.src.skfolio.utils.equations.equations_to_matrix"], "project": "skfolio", "origin_file": ["skfolio/datasets/_base.py", "skfolio/datasets/_base.py", "skfolio/utils/equations.py", "skfolio/utils/equations.py"], "test_list": ["tests/test_prior/test_black_litterman.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 71, "func_end_lineno": 113, "func_code": "def load_gzip_compressed_csv_data(\n data_filename: str,\n data_module: str = DATA_MODULE,\n encoding=\"utf-8\",\n datetime_index: bool = True,\n) -> pd.DataFrame:\n \"\"\"Load gzip-compressed csv files with `importlib.resources`.\n\n 1) Open resource file with `importlib.resources.open_binary`\n 2) Decompress csv file with `gzip.open`\n 3) Load decompressed data with `pd.read_csv`\n\n Parameters\n ----------\n data_filename : str\n Name of gzip-compressed csv file (`'*.csv.gz'`) to be loaded from\n `data_module/data_file_name`. For example `'SPX500.csv.gz'`.\n\n data_module : str or module, default='skfolio.datasets.data'\n Module where data lives. The default is `'skfolio.datasets.data'`.\n\n encoding : str, default=\"utf-8\"\n Name of the encoding that the gzip-decompressed file will be\n decoded with. The default is 'utf-8'.\n\n datetime_index: bool, default=True\n If this is set to True, the DataFrame index is converted to datetime with\n format=\"%Y-%m-%d\".\n The default is `True`.\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n DataFrame with each row representing one observation and each column\n representing the asset price of a given observation.\n \"\"\"\n path = resources.files(data_module).joinpath(data_filename)\n with path.open(\"rb\") as compressed_file:\n compressed_file = gzip.open(compressed_file, mode=\"rt\", encoding=encoding)\n df = pd.read_csv(compressed_file, sep=\",\", index_col=0)\n if datetime_index:\n df.index = pd.to_datetime(df.index, format=\"%Y-%m-%d\")\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 168, "func_end_lineno": 204, "func_code": "def load_sp500_dataset() -> pd.DataFrame:\n \"\"\"Load the prices of 20 assets from the S&P 500 Index composition.\n\n This dataset is composed of the daily prices of 20 assets from the S&P 500\n composition starting from 1990-01-02 up to 2022-12-28.\n\n The data comes from the Yahoo public API.\n The price is the adjusted close which is the closing price after adjustments for\n all applicable splits and dividend distributions.\n The adjustment uses appropriate split and dividend multipliers, adhering to\n the Center for Research in Security Prices (CRSP) standards.\n\n ============== ==================\n Observations 8313\n Assets 20\n ============== ==================\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n Prices DataFrame\n\n Examples\n --------\n >>> from skfolio.datasets import load_sp500_dataset\n >>> prices = load_sp500_dataset()\n >>> prices.head()\n AAPL AMD BAC ... UNH WMT XOM\n 1990-01-02 0.332589 4.1250 11.65625 ... 0.382813 5.890625 12.5000\n 1990-01-03 0.334821 4.0000 11.75000 ... 0.375000 5.890625 12.3750\n 1990-01-04 0.335938 3.9375 11.50000 ... 0.371094 5.859375 12.2500\n 1990-01-05 0.337054 3.8125 11.25000 ... 0.355469 5.796875 12.1875\n 1990-01-08 0.339286 3.8125 11.31250 ... 0.347656 5.875000 12.3750\n \"\"\"\n data_filename = \"sp500_dataset.csv.gz\"\n df = load_gzip_compressed_csv_data(data_filename)\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 499, "func_start_lineno": 195, "func_end_lineno": 226, "func_code": "def _validate_groups(groups: npt.ArrayLike, name: str = \"groups\") -> np.ndarray:\n \"\"\"Validate groups by checking its dim and if group names don't appear in multiple\n levels and convert to numpy array.\n\n Parameters\n ----------\n groups : array-like of shape (n_groups, n_assets)\n 2D-array of strings.\n\n Returns\n -------\n groups : ndarray of shape (n_groups, n_assets)\n 2D-array of strings.\n \"\"\"\n groups = np.asarray(groups)\n if groups.ndim != 2:\n raise ValueError(\n f\"`{name} must be a 2D array, got {groups.ndim}D array instead.\"\n )\n n = len(groups)\n group_sets = [set(groups[i]) for i in range(n)]\n for i in range(n - 1):\n for e in group_sets[i]:\n for j in range(i + 1, n):\n if e in group_sets[j]:\n raise DuplicateGroupsError(\n f\"'{e}' appear in two levels: {list(groups[i])} \"\n f\"and {list(groups[i])}. \"\n f\"{name} must be in only one level.\"\n )\n\n return groups"}, {"class_start_lineno": 1, "class_end_lineno": 499, "func_start_lineno": 32, "func_end_lineno": 134, "func_code": "def equations_to_matrix(\n groups: npt.ArrayLike,\n equations: npt.ArrayLike,\n sum_to_one: bool = False,\n raise_if_group_missing: bool = False,\n names: tuple[str, str] = (\"groups\", \"equations\"),\n) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:\n \"\"\"Convert a list of linear equations into the left and right matrices of the\n inequality A <= B and equality A == B.\n\n Parameters\n ----------\n groups : array-like of shape (n_groups, n_assets)\n 2D array of assets groups.\n\n For example:\n\n groups = np.array(\n [\n [\"SPX\", \"SX5E\", \"NKY\", \"TLT\"],\n [\"Equity\", \"Equity\", \"Equity\", \"Bond\"],\n [\"US\", \"Europe\", \"Japan\", \"US\"],\n ]\n )\n\n equations : array-like of shape (n_equations,)\n 1D array of equations.\n\n Example of valid equation patterns:\n * \"number_1 * group_1 + number_3 <= number_4 * group_3 + number_5\"\n * \"group_1 == number * group_2\"\n * \"group_1 <= number\"\n * \"group_1 == number\"\n\n \"group_1\" and \"group_2\" are the group names defined in `groups`.\n The second expression means that the sum of all assets in \"group_1\" should be\n less or equal to \"number\" times the sum of all assets in \"group_2\".\n\n For example:\n\n equations = [\n \"Equity <= 3 * Bond\",\n \"US >= 1.5\",\n \"Europe >= 0.5 * Japan\",\n \"Japan == 1\",\n \"3*SPX + 5*SX5E == 2*TLT + 3\",\n ]\n\n sum_to_one : bool\n If this is set to True, all elements in a group sum to one (used in the `views`\n of the Black-Litterman model).\n\n raise_if_group_missing : bool, default=False\n If this is set to True, an error is raised when a group is not found in the\n groups, otherwise only a warning is shown.\n The default is False.\n\n names : tuple[str, str], default=('groups', 'equations')\n The group and equation names used in error messages.\n The default is `('groups', 'equations')`.\n\n Returns\n -------\n left_equality: ndarray of shape (n_equations_equality, n_assets)\n right_equality: ndarray of shape (n_equations_equality,)\n The left and right matrices of the inequality A <= B.\n\n left_inequality: ndarray of shape (n_equations_inequality, n_assets)\n right_inequality: ndarray of shape (n_equations_inequality,)\n The left and right matrices of the equality A == B.\n \"\"\"\n groups = _validate_groups(groups, name=names[0])\n equations = _validate_equations(equations, name=names[1])\n\n a_equality = []\n b_equality = []\n\n a_inequality = []\n b_inequality = []\n\n for string in equations:\n try:\n left, right, is_inequality = _string_to_equation(\n groups=groups,\n string=string,\n sum_to_one=sum_to_one,\n )\n if is_inequality:\n a_inequality.append(left)\n b_inequality.append(right)\n else:\n a_equality.append(left)\n b_equality.append(right)\n except GroupNotFoundError as e:\n if raise_if_group_missing:\n raise\n warnings.warn(str(e), stacklevel=2)\n return (\n np.array(a_equality),\n np.array(b_equality),\n np.array(a_inequality),\n np.array(b_inequality),\n )"}], "type": ["function_empty", "TDD"], "node": ["skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.datasets._base.load_sp500_dataset", "skfolio.utils.equations._validate_groups", "skfolio.utils.equations.equations_to_matrix"], "language": "Python", "toolfunc_count": 3, "func_count": 4, "pytest_info": {"total_num": 4, "base_passed_num": 0}} {"id": ["skfolio.src.skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.src.skfolio.datasets._base.load_sp500_dataset", "skfolio.src.skfolio.distribution.multivariate._utils.ChildNode::central", "skfolio.src.skfolio.distribution.multivariate._utils.Edge::share_one_node", "skfolio.src.skfolio.distribution.multivariate._utils.Tree::set_edges_from_mst"], "project": "skfolio", "origin_file": ["skfolio/datasets/_base.py", "skfolio/datasets/_base.py", "skfolio/distribution/multivariate/_utils.py", "skfolio/distribution/multivariate/_utils.py", "skfolio/distribution/multivariate/_utils.py", "skfolio/distribution/multivariate/_utils.py"], "test_list": ["tests/test_prior/test_synthetic_data.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 71, "func_end_lineno": 113, "func_code": "def load_gzip_compressed_csv_data(\n data_filename: str,\n data_module: str = DATA_MODULE,\n encoding=\"utf-8\",\n datetime_index: bool = True,\n) -> pd.DataFrame:\n \"\"\"Load gzip-compressed csv files with `importlib.resources`.\n\n 1) Open resource file with `importlib.resources.open_binary`\n 2) Decompress csv file with `gzip.open`\n 3) Load decompressed data with `pd.read_csv`\n\n Parameters\n ----------\n data_filename : str\n Name of gzip-compressed csv file (`'*.csv.gz'`) to be loaded from\n `data_module/data_file_name`. For example `'SPX500.csv.gz'`.\n\n data_module : str or module, default='skfolio.datasets.data'\n Module where data lives. The default is `'skfolio.datasets.data'`.\n\n encoding : str, default=\"utf-8\"\n Name of the encoding that the gzip-decompressed file will be\n decoded with. The default is 'utf-8'.\n\n datetime_index: bool, default=True\n If this is set to True, the DataFrame index is converted to datetime with\n format=\"%Y-%m-%d\".\n The default is `True`.\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n DataFrame with each row representing one observation and each column\n representing the asset price of a given observation.\n \"\"\"\n path = resources.files(data_module).joinpath(data_filename)\n with path.open(\"rb\") as compressed_file:\n compressed_file = gzip.open(compressed_file, mode=\"rt\", encoding=encoding)\n df = pd.read_csv(compressed_file, sep=\",\", index_col=0)\n if datetime_index:\n df.index = pd.to_datetime(df.index, format=\"%Y-%m-%d\")\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 168, "func_end_lineno": 204, "func_code": "def load_sp500_dataset() -> pd.DataFrame:\n \"\"\"Load the prices of 20 assets from the S&P 500 Index composition.\n\n This dataset is composed of the daily prices of 20 assets from the S&P 500\n composition starting from 1990-01-02 up to 2022-12-28.\n\n The data comes from the Yahoo public API.\n The price is the adjusted close which is the closing price after adjustments for\n all applicable splits and dividend distributions.\n The adjustment uses appropriate split and dividend multipliers, adhering to\n the Center for Research in Security Prices (CRSP) standards.\n\n ============== ==================\n Observations 8313\n Assets 20\n ============== ==================\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n Prices DataFrame\n\n Examples\n --------\n >>> from skfolio.datasets import load_sp500_dataset\n >>> prices = load_sp500_dataset()\n >>> prices.head()\n AAPL AMD BAC ... UNH WMT XOM\n 1990-01-02 0.332589 4.1250 11.65625 ... 0.382813 5.890625 12.5000\n 1990-01-03 0.334821 4.0000 11.75000 ... 0.375000 5.890625 12.3750\n 1990-01-04 0.335938 3.9375 11.50000 ... 0.371094 5.859375 12.2500\n 1990-01-05 0.337054 3.8125 11.25000 ... 0.355469 5.796875 12.1875\n 1990-01-08 0.339286 3.8125 11.31250 ... 0.347656 5.875000 12.3750\n \"\"\"\n data_filename = \"sp500_dataset.csv.gz\"\n df = load_gzip_compressed_csv_data(data_filename)\n return df"}, {"class_start_lineno": 160, "class_end_lineno": 324, "func_start_lineno": 191, "func_end_lineno": 202, "func_code": " def central(self) -> bool:\n \"\"\"Determine whether this node is considered central.\n It is inherited from the associated edge's centrality.\n\n Returns\n -------\n central: bool\n True if the node is central; otherwise, False.\n \"\"\"\n if self._central is None:\n self._central = self.ref.strongly_central\n return self._central"}, {"class_start_lineno": 327, "class_end_lineno": 479, "func_start_lineno": 365, "func_end_lineno": 369, "func_code": " def weakly_central(self) -> bool:\n \"\"\"Determine if the edge is weakly central.\n An edge is weakly central if at least one of its two nodes is central.\n \"\"\"\n return self.node1.central or self.node2.central"}, {"class_start_lineno": 327, "class_end_lineno": 479, "func_start_lineno": 460, "func_end_lineno": 473, "func_code": " def share_one_node(self, other: \"Edge\") -> bool:\n \"\"\"Check whether two edges share exactly one node.\n\n Parameters\n ----------\n other : Edge\n Another edge to compare with.\n\n Returns\n -------\n bool\n True if the two edges share exactly one node; otherwise, False.\n \"\"\"\n return len({self.node1, self.node2} & {other.node1, other.node2}) == 1"}, {"class_start_lineno": 482, "class_end_lineno": 591, "func_start_lineno": 520, "func_end_lineno": 582, "func_code": " def set_edges_from_mst(self, dependence_method: DependenceMethod) -> None:\n \"\"\"Construct the Maximum Spanning Tree (MST) from the current nodes using\n the specified dependence method.\n\n The MST is built based on pairwise dependence measures computed between nodes.\n If any edge is (weakly) central, a central factor is added to the dependence\n measure to favor edges connected to central nodes.\n\n Parameters\n ----------\n dependence_method : DependenceMethod\n The method used to compute the dependence measure between nodes (e.g.,\n Kendall's tau).\n\n Returns\n -------\n None\n \"\"\"\n n = len(self.nodes)\n dependence_matrix = np.zeros((n, n))\n eligible_edges = {}\n central = False\n for i, j in combinations(range(n), 2):\n node1 = self.nodes[i]\n node2 = self.nodes[j]\n if self.level == 0 or node1.ref.share_one_node(node2.ref):\n edge = Edge(\n node1=node1, node2=node2, dependence_method=dependence_method\n )\n if not central and edge.weakly_central:\n central = True\n # Negate the matrix to use minimum_spanning_tree for maximum spanning\n # Add a cst to ensure that even if dep is 0, we still build a valid MST\n dep = abs(edge.dependence) + 1e-5\n dependence_matrix[i, j] = dep\n eligible_edges[(i, j)] = edge\n\n if np.any(np.isnan(dependence_matrix)):\n raise RuntimeError(\"dependence_matrix contains NaNs\")\n\n if central:\n max_dep = np.max(dependence_matrix)\n for (i, j), edge in eligible_edges.items():\n if edge.weakly_central:\n if edge.strongly_central:\n central_factor = 3 * max_dep\n else:\n central_factor = 2 * max_dep\n dep = dependence_matrix[i, j] + central_factor\n dependence_matrix[i, j] = dep\n\n # Compute the minimum spanning tree\n mst = ssc.minimum_spanning_tree(-dependence_matrix, overwrite=True)\n\n edges = []\n # Extract the indices of the non-zero entries (edges)\n for i, j in zip(*mst.nonzero(), strict=True):\n edge = eligible_edges[(i, j)]\n # connect Nodes to Edges\n edge.ref_to_nodes()\n edges.append(edge)\n\n self.edges = edges"}], "type": ["function_empty", "TDD"], "node": ["skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.datasets._base.load_sp500_dataset", "skfolio.distribution.multivariate._utils.ChildNode.central", "skfolio.distribution.multivariate._utils.Edge.weakly_central", "skfolio.distribution.multivariate._utils.Edge.share_one_node", "skfolio.distribution.multivariate._utils.Tree.set_edges_from_mst"], "language": "Python", "toolfunc_count": 4, "func_count": 5, "pytest_info": {"total_num": 4, "base_passed_num": 0}} {"id": ["skfolio.src.skfolio.utils.equations._split_equation_string", "skfolio.src.skfolio.utils.equations._string_to_equation", "skfolio.src.skfolio.utils.equations._validate_groups", "skfolio.src.skfolio.utils.equations.equations_to_matrix"], "project": "skfolio", "origin_file": ["skfolio/utils/equations.py", "skfolio/utils/equations.py", "skfolio/utils/equations.py", "skfolio/utils/equations.py"], "test_list": ["tests/test_utils/test_equations.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 499, "func_start_lineno": 347, "func_end_lineno": 371, "func_code": "def _split_equation_string(string: str) -> list[str]:\n \"\"\"Split an equation strings by operators.\"\"\"\n comp_pattern = \"(?=\" + \"|\".join([\".+\\\\\" + e for e in _COMPARISON_OPERATORS]) + \")\"\n if not bool(re.match(comp_pattern, string)):\n raise EquationToMatrixError(\n f\"The string must contains a comparison operator: \"\n f\"{list(_COMPARISON_OPERATORS)}\"\n )\n\n # Regex to match only '>' and '<' but not '<=' or '>='\n invalid_pattern = r\"(?(?!=)|(?)<(?!=)\"\n invalid_matches = re.findall(invalid_pattern, string)\n\n if len(invalid_matches) > 0:\n raise EquationToMatrixError(\n f\"{invalid_matches[0]} is an invalid comparison operator. \"\n f\"Valid comparison operators are: {list(_COMPARISON_OPERATORS)}\"\n )\n\n # '==' needs to be before '='\n operators = sorted(_OPERATORS, reverse=True)\n pattern = \"((?:\" + \"|\".join([\"\\\\\" + e for e in operators]) + \"))\"\n res = [x.strip() for x in re.split(pattern, string)]\n res = [x for x in res if x != \"\"]\n return res"}, {"class_start_lineno": 1, "class_end_lineno": 499, "func_start_lineno": 374, "func_end_lineno": 499, "func_code": "def _string_to_equation(\n groups: np.ndarray,\n string: str,\n sum_to_one: bool,\n) -> tuple[np.ndarray, float, bool]:\n \"\"\"Convert a string to a left 1D-array and right float of the form:\n `groups @ left <= right` or `groups @ left == right` and return whether it's an\n equality or inequality.\n\n Parameters\n ----------\n groups : ndarray of shape (n_groups, n_assets)\n Groups 2D-array\n\n string : str\n String to convert\n\n sum_to_one : bool\n If this is set to True, the 1D-array is scaled to have a sum of one.\n\n Returns\n -------\n left : 1D-array of shape (n_assets,)\n right : float\n is_inequality : bool\n \"\"\"\n n = groups.shape[1]\n err_msg = f\"Wrong pattern encountered while converting the string '{string}'\"\n\n iterator = iter(_split_equation_string(string))\n group_names = set(groups.flatten())\n\n def is_group(name: str) -> bool:\n return name in group_names\n\n left = np.zeros(n)\n right = 0\n main_sign = 1\n comparison_sign = None\n is_inequality = None\n e = next(iterator, None)\n i = 0\n while True:\n i += 1\n if i > 1e6:\n raise RecursionError(err_msg)\n if e is None:\n break\n sign = 1\n if e in _COMPARISON_OPERATORS:\n if e in _INEQUALITY_OPERATORS:\n is_inequality = True\n else:\n is_inequality = False\n main_sign = -1\n comparison_sign = _comparison_operator_sign(e)\n e = next(iterator, None)\n if e in _SUB_ADD_OPERATORS:\n sign *= _sub_add_operator_sign(e)\n e = next(iterator, None)\n elif e in _SUB_ADD_OPERATORS:\n sign *= _sub_add_operator_sign(e)\n e = next(iterator, None)\n elif e in _MUL_OPERATORS:\n raise EquationToMatrixError(\n f\"{err_msg}: the character '{e}' is wrongly positioned\"\n )\n sign *= main_sign\n # next can only be a number or a group\n if e is None or e in _OPERATORS:\n raise EquationToMatrixError(\n f\"{err_msg}: the character '{e}' is wrongly positioned\"\n )\n if is_group(e):\n arr = _matching_array(values=groups, key=e, sum_to_one=sum_to_one)\n # next can only be a '*' or an ['-', '+', '>=', '<=', '==', '='] or None\n e = next(iterator, None)\n if e is None or e in _NON_MUL_OPERATORS:\n left += sign * arr\n elif e in _MUL_OPERATORS:\n # next can only a number\n e = next(iterator, None)\n try:\n number = float(e)\n except ValueError:\n raise GroupNotFoundError(\n f\"{err_msg}: the group '{e}' is missing from the groups\"\n f\" {groups}\"\n ) from None\n\n left += number * sign * arr\n e = next(iterator, None)\n else:\n raise EquationToMatrixError(\n f\"{err_msg}: the character '{e}' is wrongly positioned\"\n )\n else:\n try:\n number = float(e)\n except ValueError:\n raise GroupNotFoundError(\n f\"{err_msg}: the group '{e}' is missing from the groups {groups}\"\n ) from None\n # next can only be a '*' or an operator or None\n e = next(iterator, None)\n if e in _MUL_OPERATORS:\n # next can only a group\n e = next(iterator, None)\n if not is_group(e):\n raise EquationToMatrixError(\n f\"{err_msg}: the character '{e}' is wrongly positioned\"\n )\n arr = _matching_array(values=groups, key=e, sum_to_one=sum_to_one)\n left += number * sign * arr\n e = next(iterator, None)\n elif e is None or e in _NON_MUL_OPERATORS:\n right += number * sign\n else:\n raise EquationToMatrixError(\n f\"{err_msg}: the character '{e}' is wrongly positioned\"\n )\n\n left *= comparison_sign\n right *= -comparison_sign\n\n return left, right, is_inequality"}, {"class_start_lineno": 1, "class_end_lineno": 499, "func_start_lineno": 195, "func_end_lineno": 226, "func_code": "def _validate_groups(groups: npt.ArrayLike, name: str = \"groups\") -> np.ndarray:\n \"\"\"Validate groups by checking its dim and if group names don't appear in multiple\n levels and convert to numpy array.\n\n Parameters\n ----------\n groups : array-like of shape (n_groups, n_assets)\n 2D-array of strings.\n\n Returns\n -------\n groups : ndarray of shape (n_groups, n_assets)\n 2D-array of strings.\n \"\"\"\n groups = np.asarray(groups)\n if groups.ndim != 2:\n raise ValueError(\n f\"`{name} must be a 2D array, got {groups.ndim}D array instead.\"\n )\n n = len(groups)\n group_sets = [set(groups[i]) for i in range(n)]\n for i in range(n - 1):\n for e in group_sets[i]:\n for j in range(i + 1, n):\n if e in group_sets[j]:\n raise DuplicateGroupsError(\n f\"'{e}' appear in two levels: {list(groups[i])} \"\n f\"and {list(groups[i])}. \"\n f\"{name} must be in only one level.\"\n )\n\n return groups"}, {"class_start_lineno": 1, "class_end_lineno": 499, "func_start_lineno": 32, "func_end_lineno": 134, "func_code": "def equations_to_matrix(\n groups: npt.ArrayLike,\n equations: npt.ArrayLike,\n sum_to_one: bool = False,\n raise_if_group_missing: bool = False,\n names: tuple[str, str] = (\"groups\", \"equations\"),\n) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:\n \"\"\"Convert a list of linear equations into the left and right matrices of the\n inequality A <= B and equality A == B.\n\n Parameters\n ----------\n groups : array-like of shape (n_groups, n_assets)\n 2D array of assets groups.\n\n For example:\n\n groups = np.array(\n [\n [\"SPX\", \"SX5E\", \"NKY\", \"TLT\"],\n [\"Equity\", \"Equity\", \"Equity\", \"Bond\"],\n [\"US\", \"Europe\", \"Japan\", \"US\"],\n ]\n )\n\n equations : array-like of shape (n_equations,)\n 1D array of equations.\n\n Example of valid equation patterns:\n * \"number_1 * group_1 + number_3 <= number_4 * group_3 + number_5\"\n * \"group_1 == number * group_2\"\n * \"group_1 <= number\"\n * \"group_1 == number\"\n\n \"group_1\" and \"group_2\" are the group names defined in `groups`.\n The second expression means that the sum of all assets in \"group_1\" should be\n less or equal to \"number\" times the sum of all assets in \"group_2\".\n\n For example:\n\n equations = [\n \"Equity <= 3 * Bond\",\n \"US >= 1.5\",\n \"Europe >= 0.5 * Japan\",\n \"Japan == 1\",\n \"3*SPX + 5*SX5E == 2*TLT + 3\",\n ]\n\n sum_to_one : bool\n If this is set to True, all elements in a group sum to one (used in the `views`\n of the Black-Litterman model).\n\n raise_if_group_missing : bool, default=False\n If this is set to True, an error is raised when a group is not found in the\n groups, otherwise only a warning is shown.\n The default is False.\n\n names : tuple[str, str], default=('groups', 'equations')\n The group and equation names used in error messages.\n The default is `('groups', 'equations')`.\n\n Returns\n -------\n left_equality: ndarray of shape (n_equations_equality, n_assets)\n right_equality: ndarray of shape (n_equations_equality,)\n The left and right matrices of the inequality A <= B.\n\n left_inequality: ndarray of shape (n_equations_inequality, n_assets)\n right_inequality: ndarray of shape (n_equations_inequality,)\n The left and right matrices of the equality A == B.\n \"\"\"\n groups = _validate_groups(groups, name=names[0])\n equations = _validate_equations(equations, name=names[1])\n\n a_equality = []\n b_equality = []\n\n a_inequality = []\n b_inequality = []\n\n for string in equations:\n try:\n left, right, is_inequality = _string_to_equation(\n groups=groups,\n string=string,\n sum_to_one=sum_to_one,\n )\n if is_inequality:\n a_inequality.append(left)\n b_inequality.append(right)\n else:\n a_equality.append(left)\n b_equality.append(right)\n except GroupNotFoundError as e:\n if raise_if_group_missing:\n raise\n warnings.warn(str(e), stacklevel=2)\n return (\n np.array(a_equality),\n np.array(b_equality),\n np.array(a_inequality),\n np.array(b_inequality),\n )"}], "type": ["function_empty", "TDD"], "node": ["skfolio.utils.equations._split_equation_string", "skfolio.utils.equations._string_to_equation", "skfolio.utils.equations._validate_groups", "skfolio.utils.equations.equations_to_matrix"], "language": "Python", "toolfunc_count": 2, "func_count": 4, "pytest_info": {"total_num": 12, "base_passed_num": 3}} {"id": ["skfolio.src.skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.src.skfolio.datasets._base.load_sp500_dataset", "skfolio.src.skfolio.datasets._base.get_data_home", "skfolio.src.skfolio.datasets._base.download_dataset", "skfolio.src.skfolio.datasets._base.load_nasdaq_dataset"], "project": "skfolio", "origin_file": ["skfolio/datasets/_base.py", "skfolio/datasets/_base.py", "skfolio/datasets/_base.py", "skfolio/datasets/_base.py", "skfolio/datasets/_base.py"], "test_list": ["tests/test_utils/test_stats.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 71, "func_end_lineno": 113, "func_code": "def load_gzip_compressed_csv_data(\n data_filename: str,\n data_module: str = DATA_MODULE,\n encoding=\"utf-8\",\n datetime_index: bool = True,\n) -> pd.DataFrame:\n \"\"\"Load gzip-compressed csv files with `importlib.resources`.\n\n 1) Open resource file with `importlib.resources.open_binary`\n 2) Decompress csv file with `gzip.open`\n 3) Load decompressed data with `pd.read_csv`\n\n Parameters\n ----------\n data_filename : str\n Name of gzip-compressed csv file (`'*.csv.gz'`) to be loaded from\n `data_module/data_file_name`. For example `'SPX500.csv.gz'`.\n\n data_module : str or module, default='skfolio.datasets.data'\n Module where data lives. The default is `'skfolio.datasets.data'`.\n\n encoding : str, default=\"utf-8\"\n Name of the encoding that the gzip-decompressed file will be\n decoded with. The default is 'utf-8'.\n\n datetime_index: bool, default=True\n If this is set to True, the DataFrame index is converted to datetime with\n format=\"%Y-%m-%d\".\n The default is `True`.\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n DataFrame with each row representing one observation and each column\n representing the asset price of a given observation.\n \"\"\"\n path = resources.files(data_module).joinpath(data_filename)\n with path.open(\"rb\") as compressed_file:\n compressed_file = gzip.open(compressed_file, mode=\"rt\", encoding=encoding)\n df = pd.read_csv(compressed_file, sep=\",\", index_col=0)\n if datetime_index:\n df.index = pd.to_datetime(df.index, format=\"%Y-%m-%d\")\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 168, "func_end_lineno": 204, "func_code": "def load_sp500_dataset() -> pd.DataFrame:\n \"\"\"Load the prices of 20 assets from the S&P 500 Index composition.\n\n This dataset is composed of the daily prices of 20 assets from the S&P 500\n composition starting from 1990-01-02 up to 2022-12-28.\n\n The data comes from the Yahoo public API.\n The price is the adjusted close which is the closing price after adjustments for\n all applicable splits and dividend distributions.\n The adjustment uses appropriate split and dividend multipliers, adhering to\n the Center for Research in Security Prices (CRSP) standards.\n\n ============== ==================\n Observations 8313\n Assets 20\n ============== ==================\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n Prices DataFrame\n\n Examples\n --------\n >>> from skfolio.datasets import load_sp500_dataset\n >>> prices = load_sp500_dataset()\n >>> prices.head()\n AAPL AMD BAC ... UNH WMT XOM\n 1990-01-02 0.332589 4.1250 11.65625 ... 0.382813 5.890625 12.5000\n 1990-01-03 0.334821 4.0000 11.75000 ... 0.375000 5.890625 12.3750\n 1990-01-04 0.335938 3.9375 11.50000 ... 0.371094 5.859375 12.2500\n 1990-01-05 0.337054 3.8125 11.25000 ... 0.355469 5.796875 12.1875\n 1990-01-08 0.339286 3.8125 11.31250 ... 0.347656 5.875000 12.3750\n \"\"\"\n data_filename = \"sp500_dataset.csv.gz\"\n df = load_gzip_compressed_csv_data(data_filename)\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 25, "func_end_lineno": 55, "func_code": "def get_data_home(data_home: str | Path | None = None) -> str:\n \"\"\"Return the path of the skfolio data directory.\n\n This folder is used by some large dataset loaders to avoid downloading the\n data several times.\n\n By default, the data directory is set to a folder named 'skfolio_data' in the\n user home folder.\n\n Alternatively, it can be set by the 'SKFOLIO_DATA' environment\n variable or programmatically by giving an explicit folder path. The '~'\n symbol is expanded to the user home folder.\n\n If the folder does not already exist, it is automatically created.\n\n Parameters\n ----------\n data_home : str, optional\n The path to skfolio data directory. If `None`, the default path\n is `~/skfolio_data`.\n\n Returns\n -------\n data_home: str or path-like, optional\n The path to skfolio data directory.\n \"\"\"\n if data_home is None:\n data_home = os.environ.get(\"SKFOLIO_DATA\", os.path.join(\"~\", \"skfolio_data\"))\n data_home = os.path.expanduser(data_home)\n os.makedirs(data_home, exist_ok=True)\n return data_home"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 116, "func_end_lineno": 165, "func_code": "def download_dataset(\n data_filename: str,\n data_home: str | Path | None = None,\n download_if_missing: bool = True,\n) -> pd.DataFrame:\n \"\"\"Download and save locally a dataset from the remote GitHub dataset folder.\n\n Parameters\n ----------\n data_filename : str\n Name of gzip-compressed csv file (`'*.csv.gz'`) to be loaded from a remote\n GitHub dataset folder.\n\n data_home : str or path-like, optional\n Specify another download and cache folder for the datasets. By default,\n all skfolio data is stored in `~/skfolio_data` sub-folders.\n\n download_if_missing : bool, default=True\n If False, raise an OSError if the data is not locally available\n instead of trying to download the data from the source site.\n The default is `True`.\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n DataFrame with each row representing one observation and each column\n representing the asset price of a given observation.\n \"\"\"\n # Use a CORS proxy when triggering requests from the browser\n url_prefix = \"https://corsproxy.io/?\" if sys.platform == \"emscripten\" else \"\"\n url = url_prefix + (\n f\"https://github.com/skfolio/skfolio-datasets/raw/main/\"\n f\"datasets/{data_filename}.csv.gz\"\n )\n\n data_home = get_data_home(data_home=data_home)\n filepath = os.path.join(data_home, f\"{data_filename}.pkz\")\n\n if os.path.exists(filepath):\n return joblib.load(filepath)\n\n if not download_if_missing:\n raise OSError(\"Data not found and `download_if_missing` is False\")\n\n archive_path = os.path.join(data_home, os.path.basename(url))\n ur.urlretrieve(url, archive_path)\n df = load_gzip_compressed_csv_data(archive_path)\n joblib.dump(df, filepath, compress=6)\n os.remove(archive_path)\n return df"}, {"class_start_lineno": 1, "class_end_lineno": 448, "func_start_lineno": 348, "func_end_lineno": 397, "func_code": "def load_nasdaq_dataset(data_home=None, download_if_missing=True) -> pd.DataFrame:\n \"\"\"Load the prices of 1455 assets from the NASDAQ Composite Index.\n\n This dataset is composed of the daily prices of 1455 assets from the NASDAQ\n Composite starting from 2018-01-02 up to 2023-05-31.\n\n The data comes from the Yahoo public API.\n The price is the adjusted close which is the closing price after adjustments for\n all applicable splits and dividend distributions.\n The adjustment uses appropriate split and dividend multipliers, adhering to\n the Center for Research in Security Prices (CRSP) standards.\n\n ============== ==================\n Observations 1362\n Assets 1455\n ============== ==================\n\n Parameters\n ----------\n data_home : str, optional\n Specify another download and cache folder for the datasets.\n By default, all skfolio data is stored in `~/skfolio_data` subfolders.\n\n download_if_missing : bool, default=True\n If False, raise an OSError if the data is not locally available\n instead of trying to download the data from the source site.\n\n Returns\n -------\n df : DataFrame of shape (n_observations, n_assets)\n Prices DataFrame\n\n Examples\n --------\n >>> from skfolio.datasets import load_nasdaq_dataset\n >>> prices = load_nasdaq_dataset()\n >>> prices.head()\n AAL AAOI AAON AAPL ... ZVRA ZYME ZYNE ZYXI\n Date ...\n 2018-01-02 51.648 37.91 35.621 41.310 ... 66.4 7.933 12.995 2.922\n 2018-01-03 51.014 37.89 36.247 41.303 ... 72.8 7.965 13.460 2.913\n 2018-01-04 51.336 38.38 36.103 41.495 ... 78.4 8.430 12.700 2.869\n 2018-01-05 51.316 38.89 36.681 41.967 ... 77.6 8.400 12.495 2.780\n 2018-01-08 50.809 38.37 36.103 41.811 ... 82.4 8.310 12.550 2.825\n \"\"\"\n data_filename = \"nasdaq_dataset\"\n df = download_dataset(\n data_filename, data_home=data_home, download_if_missing=download_if_missing\n )\n return df"}], "type": ["function_empty"], "node": ["skfolio.datasets._base.load_gzip_compressed_csv_data", "skfolio.datasets._base.load_sp500_dataset", "skfolio.datasets._base.get_data_home", "skfolio.datasets._base.download_dataset", "skfolio.datasets._base.load_nasdaq_dataset"], "language": "Python", "toolfunc_count": 5, "func_count": 5, "pytest_info": {"total_num": 37, "base_passed_num": 33}} {"id": ["skfolio.src.skfolio.utils.tools.optimal_rounding_decimals", "skfolio.src.skfolio.utils.tools.format_measure", "skfolio.src.skfolio.utils.tools.safe_indexing", "skfolio.src.skfolio.utils.tools.safe_split"], "project": "skfolio", "origin_file": ["skfolio/utils/tools.py", "skfolio/utils/tools.py", "skfolio/utils/tools.py", "skfolio/utils/tools.py"], "test_list": ["tests/test_utils/test_tools.py"], "prob_info": [{"class_start_lineno": 1, "class_end_lineno": 787, "func_start_lineno": 537, "func_end_lineno": 550, "func_code": "def optimal_rounding_decimals(x: float) -> int:\n \"\"\"Return the optimal rounding decimal number for a user-friendly formatting.\n\n Parameters\n ----------\n x : float\n Number to round.\n\n Returns\n -------\n n : int\n Rounding decimal number.\n \"\"\"\n return min(6, max(int(-np.log10(abs(x))) + 2, 2))"}, {"class_start_lineno": 1, "class_end_lineno": 787, "func_start_lineno": 506, "func_end_lineno": 534, "func_code": "def format_measure(x: float, percent: bool = False) -> str:\n \"\"\"Format a measure number into a user-friendly string.\n\n Parameters\n ----------\n x : float\n Number to format.\n\n percent : bool, default=False\n If this is set to True, the number is formatted in percentage.\n\n Returns\n -------\n formatted : str\n Formatted string.\n \"\"\"\n if np.isnan(x):\n return str(x)\n if percent:\n xn = x * 100\n f = \"%\"\n else:\n xn = x\n f = \"f\"\n if xn == 0:\n n = 0\n else:\n n = optimal_rounding_decimals(xn)\n return \"{value:{fmt}}\".format(value=x, fmt=f\".{n}{f}\")"}, {"class_start_lineno": 1, "class_end_lineno": 787, "func_start_lineno": 190, "func_end_lineno": 219, "func_code": "def safe_indexing(\n X: npt.ArrayLike | pd.DataFrame, indices: npt.ArrayLike | None, axis: int = 0\n):\n \"\"\"Return rows, items or columns of X using indices.\n\n Parameters\n ----------\n X : array-like\n Data from which to sample rows.\n\n indices : array-like, optional\n Indices of rows or columns.\n The default (`None`) is to select the entire data.\n\n axis : int, default=0\n The axis along which `X` will be sub-sampled. `axis=0` will select\n rows while `axis=1` will select columns.\n\n Returns\n -------\n subset :\n Subset of X on axis 0.\n \"\"\"\n if indices is None:\n return X\n if hasattr(X, \"iloc\"):\n return X.take(indices, axis=axis)\n if axis == 0:\n return X[indices]\n return X[:, indices]"}, {"class_start_lineno": 1, "class_end_lineno": 787, "func_start_lineno": 222, "func_end_lineno": 261, "func_code": "def safe_split(\n X: npt.ArrayLike,\n y: npt.ArrayLike | None = None,\n indices: np.ndarray | None = None,\n axis: int = 0,\n):\n \"\"\"Create subset of dataset.\n\n Slice X, y according to indices for cross-validation.\n\n Parameters\n ----------\n X : array-like\n Data to be indexed.\n\n y : array-like\n Data to be indexed.\n\n indices : ndarray of int, optional\n Rows or columns to select from X and y.\n The default (`None`) is to select the entire data.\n\n axis : int, default=0\n The axis along which `X` will be sub-sampled. `axis=0` will select\n rows while `axis=1` will select columns.\n\n Returns\n -------\n X_subset : array-like\n Indexed data.\n\n y_subset : array-like\n Indexed targets.\n \"\"\"\n X_subset = safe_indexing(X, indices=indices, axis=axis)\n if y is not None:\n y_subset = safe_indexing(y, indices=indices, axis=axis)\n else:\n y_subset = None\n return X_subset, y_subset"}], "type": ["function_empty", "TDD"], "node": ["skfolio.utils.tools.optimal_rounding_decimals", "skfolio.utils.tools.format_measure", "skfolio.utils.tools.safe_indexing", "skfolio.utils.tools.safe_split"], "language": "Python", "toolfunc_count": 1, "func_count": 4, "pytest_info": {"total_num": 21, "base_passed_num": 16}}