




'''simple docstring'''





from sklearn.metrics import precision_score

import datasets


a		:  Dict   			=			'''
Precision is the fraction of correctly labeled positive examples out of all of the examples that were labeled as positive. It is computed via the equation:
Precision = TP / (TP + FP)
where TP is the True positives (i.e. the examples correctly labeled as positive) and FP is the False positive examples (i.e. the examples incorrectly labeled as positive).
'''


a		:  List[Any]   			=			'''
Args:
    predictions (`list` of `int`): Predicted class labels.
    references (`list` of `int`): Actual class labels.
    labels (`list` of `int`): The set of labels to include when `average` is not set to `\'binary\'`. If `average` is `None`, it should be the label order. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None.
    pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1.
    average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `\'binary\'`.

        - \'binary\': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary.
        - \'micro\': Calculate metrics globally by counting the total true positives, false negatives and false positives.
        - \'macro\': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.
        - \'weighted\': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `\'macro\'` to account for label imbalance. This option can result in an F-score that is not between precision and recall.
        - \'samples\': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).
    sample_weight (`list` of `float`): Sample weights Defaults to None.
    zero_division (`int` or `string`): Sets the value to return when there is a zero division. Defaults to \'warn\'.

        - 0: Returns 0 when there is a zero division.
        - 1: Returns 1 when there is a zero division.
        - \'warn\': Raises warnings and then returns 0 when there is a zero division.

Returns:
    precision (`float` or `array` of `float`): Precision score or list of precision scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate that fewer negative examples were incorrectly labeled as positive, which means that, generally, higher scores are better.

Examples:

    Example 1-A simple binary example
        >>> precision_metric = datasets.load_metric("precision")
        >>> results = precision_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0])
        >>> print(results)
        {\'precision\': 0.5}

    Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`.
        >>> precision_metric = datasets.load_metric("precision")
        >>> results = precision_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0)
        >>> print(round(results[\'precision\'], 2))
        0.67

    Example 3-The same simple binary example as in Example 1, but with `sample_weight` included.
        >>> precision_metric = datasets.load_metric("precision")
        >>> results = precision_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3])
        >>> print(results)
        {\'precision\': 0.23529411764705882}

    Example 4-A multiclass example, with different values for the `average` input.
        >>> predictions = [0, 2, 1, 0, 0, 1]
        >>> references = [0, 1, 2, 0, 1, 2]
        >>> results = precision_metric.compute(predictions=predictions, references=references, average=\'macro\')
        >>> print(results)
        {\'precision\': 0.2222222222222222}
        >>> results = precision_metric.compute(predictions=predictions, references=references, average=\'micro\')
        >>> print(results)
        {\'precision\': 0.3333333333333333}
        >>> results = precision_metric.compute(predictions=predictions, references=references, average=\'weighted\')
        >>> print(results)
        {\'precision\': 0.2222222222222222}
        >>> results = precision_metric.compute(predictions=predictions, references=references, average=None)
        >>> print([round(res, 2) for res in results[\'precision\']])
        [0.67, 0.0, 0.0]
'''


a		:  int   			=			'''
@article{scikit-learn,
    title={Scikit-learn: Machine Learning in {P}ython},
    author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.
    and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.
    and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and
    Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},
    journal={Journal of Machine Learning Research},
    volume={12},
    pages={2825--2830},
    year={2011}
}
'''




@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION			,		_KWARGS_DESCRIPTION					)
class     UpperCamelCase					(  datasets.Metric					):



  def 						a_       ( self   ):







      '''simple docstring'''


      return datasets.MetricInfo(
          description=_DESCRIPTION		,    citation=_CITATION		,    inputs_description=_KWARGS_DESCRIPTION		,    features=datasets.Features(
              {
                  """predictions""": datasets.Sequence(datasets.Value("""int32"""   )   ),
                  """references""": datasets.Sequence(datasets.Value("""int32"""   )   ),
              }
              if self.config_name == """multilabel"""
              else {
                  """predictions""": datasets.Value("""int32"""   ),
                  """references""": datasets.Value("""int32"""   ),
              }   )		,    reference_urls=["""https://scikit-learn.org/stable/modules/generated/sklearn.metrics.precision_score.html"""]		,    )



  def 						a_       ( self		,    __lowerCAmelCase		,    __lowerCAmelCase		,    __lowerCAmelCase=None		,    __lowerCAmelCase=1		,    __lowerCAmelCase="binary"		,    __lowerCAmelCase=None		,    __lowerCAmelCase="warn"		,    ):







      '''simple docstring'''


      _a							:       Dict       					=			precision_score(
          __lowerCAmelCase		,    __lowerCAmelCase		,    labels=__lowerCAmelCase		,    pos_label=__lowerCAmelCase		,    average=__lowerCAmelCase		,    sample_weight=__lowerCAmelCase		,    zero_division=__lowerCAmelCase		,    )
      return {"precision": float(__lowerCAmelCase   ) if score.size == 1 else score}








'''simple docstring'''





import math
import warnings
from dataclasses import dataclass
from typing import List, Optional, Tuple, Union

import numpy as np
import torch
from scipy import integrate

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput
from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin




@dataclass
# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->LMSDiscrete
class     UpperCamelCase					(  snake_case__					):
  a    :torch.FloatTensor
  a    :Optional[torch.FloatTensor]      					=				None






def UpperCAmelCase						(					UpperCAmelCase_      ,  UpperCAmelCase_=0.999      ,  UpperCAmelCase_="cosine"      ,  ):
    if alpha_transform_type == "cosine":

        def alpha_bar_fn(UpperCAmelCase_	):
            return math.cos((t + 0.008) / 1.008 * math.pi / 2	) ** 2

    elif alpha_transform_type == "exp":

        def alpha_bar_fn(UpperCAmelCase_	):
            return math.exp(t * -12.0	)

    else:
        raise ValueError(F'''Unsupported alpha_tranform_type: {alpha_transform_type}'''	)

    _a							:       Union[str, Any]       					=			[]
    for i in range(UpperCAmelCase_	):
        _a							:       Optional[int]       					=			i / num_diffusion_timesteps
        _a							:       Optional[Any]       					=			(i + 1) / num_diffusion_timesteps
        betas.append(min(1 - alpha_bar_fn(UpperCAmelCase_	) / alpha_bar_fn(UpperCAmelCase_	)      ,  UpperCAmelCase_	)	)
    return torch.tensor(UpperCAmelCase_      ,  dtype=torch.floataa	)





class     UpperCamelCase					(  snake_case__			,		snake_case__					):
  a    :Any      					=				[e.name for e in KarrasDiffusionSchedulers]
  a    :Tuple      					=				1



  @register_to_config
  def __init__( self		,    __lowerCAmelCase = 1000		,    __lowerCAmelCase = 0.0001		,    __lowerCAmelCase = 0.02		,    __lowerCAmelCase = "linear"		,    __lowerCAmelCase = None		,    __lowerCAmelCase = False		,    __lowerCAmelCase = "epsilon"		,    __lowerCAmelCase = "linspace"		,    __lowerCAmelCase = 0		,    ):







      '''simple docstring'''


      if trained_betas is not None:
          _a							:       str       					=			torch.tensor(__lowerCAmelCase		,    dtype=torch.floataa   )
      elif beta_schedule == "linear":
          _a							:       int       					=			torch.linspace(__lowerCAmelCase		,    __lowerCAmelCase		,    __lowerCAmelCase		,    dtype=torch.floataa   )
      elif beta_schedule == "scaled_linear":
          # this schedule is very specific to the latent diffusion model.
          _a							:       Any       					=			(
              torch.linspace(beta_start**0.5		,    beta_end**0.5		,    __lowerCAmelCase		,    dtype=torch.floataa   ) ** 2
          )
      elif beta_schedule == "squaredcos_cap_v2":
          # Glide cosine schedule
          _a							:       Optional[Any]       					=			betas_for_alpha_bar(__lowerCAmelCase   )
      else:
          raise NotImplementedError(f'''{beta_schedule} does is not implemented for {self.__class__}'''   )

      _a							:       Dict       					=			1.0 - self.betas
      _a							:       Any       					=			torch.cumprod(self.alphas		,    dim=0   )

      _a							:       List[Any]       					=			np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5   )
      _a							:       List[str]       					=			np.concatenate([sigmas[::-1], [0.0]]   ).astype(np.floataa   )
      _a							:       Optional[Any]       					=			torch.from_numpy(__lowerCAmelCase   )

      # setable values
      _a							:       Tuple       					=			None
      _a							:       List[Any]       					=			use_karras_sigmas
      self.set_timesteps(__lowerCAmelCase		,    __lowerCAmelCase   )
      _a							:       Dict       					=			[]
      _a							:       int       					=			False



  @property
  def 						a_       ( self   ):







      '''simple docstring'''


      if self.config.timestep_spacing in ["linspace", "trailing"]:
          return self.sigmas.max()

      return (self.sigmas.max() ** 2 + 1) ** 0.5



  def 						a_       ( self		,    __lowerCAmelCase		,    __lowerCAmelCase   ):







      '''simple docstring'''


      if isinstance(__lowerCAmelCase		,    torch.Tensor   ):
          _a							:       int       					=			timestep.to(self.timesteps.device   )
      _a							:       Optional[Any]       					=			(self.timesteps == timestep).nonzero().item()
      _a							:       int       					=			self.sigmas[step_index]
      _a							:       Optional[int]       					=			sample / ((sigma**2 + 1) ** 0.5)
      _a							:       str       					=			True
      return sample



  def 						a_       ( self		,    __lowerCAmelCase		,    __lowerCAmelCase		,    __lowerCAmelCase   ):







      '''simple docstring'''


      def lms_derivative(__lowerCAmelCase   ):
          _a							:       Optional[Any]       					=			1.0
          for k in range(__lowerCAmelCase   ):
              if current_order == k:
                  continue
              prod *= (tau - self.sigmas[t - k]) / (self.sigmas[t - current_order] - self.sigmas[t - k])
          return prod

      _a							:       Union[str, Any]       					=			integrate.quad(__lowerCAmelCase		,    self.sigmas[t]		,    self.sigmas[t + 1]		,    epsrel=1e-4   )[0]

      return integrated_coeff



  def 						a_       ( self		,    __lowerCAmelCase		,    __lowerCAmelCase = None   ):







      '''simple docstring'''


      _a							:       Optional[int]       					=			num_inference_steps

      # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891
      if self.config.timestep_spacing == "linspace":
          _a							:       str       					=			np.linspace(0		,    self.config.num_train_timesteps - 1		,    __lowerCAmelCase		,    dtype=__lowerCAmelCase   )[
              ::-1
          ].copy()
      elif self.config.timestep_spacing == "leading":
          _a							:       str       					=			self.config.num_train_timesteps // self.num_inference_steps
          # creates integer timesteps by multiplying by ratio
          # casting to int to avoid issues when num_inference_step is power of 3
          _a							:       List[str]       					=			(np.arange(0		,    __lowerCAmelCase   ) * step_ratio).round()[::-1].copy().astype(__lowerCAmelCase   )
          timesteps += self.config.steps_offset
      elif self.config.timestep_spacing == "trailing":
          _a							:       Optional[int]       					=			self.config.num_train_timesteps / self.num_inference_steps
          # creates integer timesteps by multiplying by ratio
          # casting to int to avoid issues when num_inference_step is power of 3
          _a							:       List[Any]       					=			(np.arange(self.config.num_train_timesteps		,    0		,    -step_ratio   )).round().copy().astype(__lowerCAmelCase   )
          timesteps -= 1
      else:
          raise ValueError(
              f'''{self.config.timestep_spacing} is not supported. Please make sure to choose one of \'linspace\', \'leading\' or \'trailing\'.'''   )

      _a							:       Optional[int]       					=			np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5   )
      _a							:       Optional[int]       					=			np.log(__lowerCAmelCase   )
      _a							:       Any       					=			np.interp(__lowerCAmelCase		,    np.arange(0		,    len(__lowerCAmelCase   )   )		,    __lowerCAmelCase   )

      if self.use_karras_sigmas:
          _a							:       str       					=			self._convert_to_karras(in_sigmas=__lowerCAmelCase   )
          _a							:       str       					=			np.array([self._sigma_to_t(__lowerCAmelCase		,    __lowerCAmelCase   ) for sigma in sigmas]   )

      _a							:       List[Any]       					=			np.concatenate([sigmas, [0.0]]   ).astype(np.floataa   )

      _a							:       int       					=			torch.from_numpy(__lowerCAmelCase   ).to(device=__lowerCAmelCase   )
      if str(__lowerCAmelCase   ).startswith("""mps"""   ):
          # mps does not support float64
          _a							:       List[str]       					=			torch.from_numpy(__lowerCAmelCase   ).to(__lowerCAmelCase		,    dtype=torch.floataa   )
      else:
          _a							:       int       					=			torch.from_numpy(__lowerCAmelCase   ).to(device=__lowerCAmelCase   )

      _a							:       Any       					=			[]



  def 						a_       ( self		,    __lowerCAmelCase		,    __lowerCAmelCase   ):







      '''simple docstring'''


      _a							:       Any       					=			np.log(__lowerCAmelCase   )

      # get distribution
      _a							:       Optional[Any]       					=			log_sigma - log_sigmas[:, np.newaxis]

      # get sigmas range
      _a							:       str       					=			np.cumsum((dists >= 0)		,    axis=0   ).argmax(axis=0   ).clip(max=log_sigmas.shape[0] - 2   )
      _a							:       List[str]       					=			low_idx + 1

      _a							:       Union[str, Any]       					=			log_sigmas[low_idx]
      _a							:       str       					=			log_sigmas[high_idx]

      # interpolate sigmas
      _a							:       Union[str, Any]       					=			(low - log_sigma) / (low - high)
      _a							:       Tuple       					=			np.clip(__lowerCAmelCase		,    0		,    1   )

      # transform interpolation to time range
      _a							:       Any       					=			(1 - w) * low_idx + w * high_idx
      _a							:       List[str]       					=			t.reshape(sigma.shape   )
      return t



  def 						a_       ( self		,    __lowerCAmelCase   ):







      '''simple docstring'''


      _a							:       float       					=			in_sigmas[-1].item()
      _a							:       float       					=			in_sigmas[0].item()

      _a							:       Tuple       					=			7.0  # 7.0 is the value used in the paper
      _a							:       Dict       					=			np.linspace(0		,    1		,    self.num_inference_steps   )
      _a							:       Optional[int]       					=			sigma_min ** (1 / rho)
      _a							:       Tuple       					=			sigma_max ** (1 / rho)
      _a							:       Dict       					=			(max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho
      return sigmas



  def 						a_       ( self		,    __lowerCAmelCase		,    __lowerCAmelCase		,    __lowerCAmelCase		,    __lowerCAmelCase = 4		,    __lowerCAmelCase = True		,    ):







      '''simple docstring'''


      if not self.is_scale_input_called:
          warnings.warn(
              """The `scale_model_input` function should be called before `step` to ensure correct denoising. """
              """See `StableDiffusionPipeline` for a usage example."""   )

      if isinstance(__lowerCAmelCase		,    torch.Tensor   ):
          _a							:       Tuple       					=			timestep.to(self.timesteps.device   )
      _a							:       List[str]       					=			(self.timesteps == timestep).nonzero().item()
      _a							:       str       					=			self.sigmas[step_index]

      # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise
      if self.config.prediction_type == "epsilon":
          _a							:       Any       					=			sample - sigma * model_output
      elif self.config.prediction_type == "v_prediction":
          # * c_out + input * c_skip
          _a							:       Any       					=			model_output * (-sigma / (sigma**2 + 1) ** 0.5) + (sample / (sigma**2 + 1))
      elif self.config.prediction_type == "sample":
          _a							:       List[Any]       					=			model_output
      else:
          raise ValueError(
              f'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`'''   )

      # 2. Convert to an ODE derivative
      _a							:       Any       					=			(sample - pred_original_sample) / sigma
      self.derivatives.append(__lowerCAmelCase   )
      if len(self.derivatives   ) > order:
          self.derivatives.pop(0   )

      # 3. Compute linear multistep coefficients
      _a							:       Optional[Any]       					=			min(step_index + 1		,    __lowerCAmelCase   )
      _a							:       int       					=			[self.get_lms_coefficient(__lowerCAmelCase		,    __lowerCAmelCase		,    __lowerCAmelCase   ) for curr_order in range(__lowerCAmelCase   )]

      # 4. Compute previous sample based on the derivatives path
      _a							:       Optional[Any]       					=			sample + sum(
          coeff * derivative for coeff, derivative in zip(__lowerCAmelCase		,    reversed(self.derivatives   )   )   )

      if not return_dict:
          return (prev_sample,)

      return LMSDiscreteSchedulerOutput(prev_sample=__lowerCAmelCase		,    pred_original_sample=__lowerCAmelCase   )



  def 						a_       ( self		,    __lowerCAmelCase		,    __lowerCAmelCase		,    __lowerCAmelCase		,    ):







      '''simple docstring'''


      _a							:       Optional[Any]       					=			self.sigmas.to(device=original_samples.device		,    dtype=original_samples.dtype   )
      if original_samples.device.type == "mps" and torch.is_floating_point(__lowerCAmelCase   ):
          # mps does not support float64
          _a							:       Any       					=			self.timesteps.to(original_samples.device		,    dtype=torch.floataa   )
          _a							:       Optional[Any]       					=			timesteps.to(original_samples.device		,    dtype=torch.floataa   )
      else:
          _a							:       int       					=			self.timesteps.to(original_samples.device   )
          _a							:       Optional[Any]       					=			timesteps.to(original_samples.device   )

      _a							:       Any       					=			[(schedule_timesteps == t).nonzero().item() for t in timesteps]

      _a							:       List[str]       					=			sigmas[step_indices].flatten()
      while len(sigma.shape   ) < len(original_samples.shape   ):
          _a							:       int       					=			sigma.unsqueeze(-1   )

      _a							:       List[str]       					=			original_samples + noise * sigma
      return noisy_samples



  def __len__( self   ):







      '''simple docstring'''


      return self.config.num_train_timesteps


