



"""simple docstring"""





import sys
from dataclasses import dataclass
from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union

import pandas as pd
import pyarrow as pa

import datasets
import datasets.config
from datasets.features.features import require_storage_cast
from datasets.table import table_cast


if TYPE_CHECKING:
  import sqlitea

  import sqlalchemy


SCREAMING_SNAKE_CASE				:     Tuple          =	datasets.utils.logging.get_logger(__name__)


@dataclass
class       __lowerCamelCase	(   datasets.BuilderConfig    ):
   __UpperCamelCase									=   None
   __UpperCamelCase									=   None
   __UpperCamelCase									=   None
   __UpperCamelCase									=   True
   __UpperCamelCase									=   None
   __UpperCamelCase									=   None
   __UpperCamelCase									=   None
   __UpperCamelCase									=   10_000
   __UpperCamelCase									=   None







   def 							A__						(self				):




      '''simple docstring'''




      if self.sql is None:
         raise ValueError("""sql must be specified"""				)
      if self.con is None:
         raise ValueError("""con must be specified"""				)







   def 							A__						(self       ,	lowerCamelCase       ,	lowerCamelCase = None       ,	):




      '''simple docstring'''




      _lowerCAmelCase					     =		config_kwargs.copy()
      # We need to stringify the Selectable object to make its hash deterministic

      # The process of stringifying is explained here: http://docs.sqlalchemy.org/en/latest/faq/sqlexpressions.html
      _lowerCAmelCase					     =		config_kwargs["""sql"""]
      if not isinstance(lowerCamelCase       ,	lowerCamelCase				):
         if datasets.config.SQLALCHEMY_AVAILABLE and "sqlalchemy" in sys.modules:
            import sqlalchemy

            if isinstance(lowerCamelCase       ,	sqlalchemy.sql.Selectable				):
               _lowerCAmelCase					     =		sqlalchemy.create_engine(config_kwargs["""con"""].split("""://"""				)[0] + """://"""				)
               _lowerCAmelCase					     =		str(sql.compile(dialect=engine.dialect				)				)
               _lowerCAmelCase					     =		sql_str
            else:
               raise TypeError(
                   f"""Supported types for 'sql' are string and sqlalchemy.sql.Selectable but got {type(lowerCamelCase				)}: {sql}"""				)
         else:
            raise TypeError(
                f"""Supported types for 'sql' are string and sqlalchemy.sql.Selectable but got {type(lowerCamelCase				)}: {sql}"""				)
      _lowerCAmelCase					     =		config_kwargs["""con"""]
      if not isinstance(lowerCamelCase       ,	lowerCamelCase				):
         _lowerCAmelCase					     =		id(lowerCamelCase				)
         logger.info(
             f"""SQL connection 'con' of type {type(lowerCamelCase				)} couldn't be hashed properly. To enable hashing, specify 'con' as URI string instead."""				)

      return super().create_config_id(lowerCamelCase       ,	custom_features=lowerCamelCase				)







   @property
   def 							A__						(self				):




      '''simple docstring'''




      _lowerCAmelCase					     =		{
          """index_col""": self.index_col,
          """columns""": self.columns,
          """params""": self.params,
          """coerce_float""": self.coerce_float,
          """parse_dates""": self.parse_dates,
      }
      return pd_read_sql_kwargs





class       __lowerCamelCase	(   datasets.ArrowBasedBuilder    ):
   __UpperCamelCase									=   SqlConfig







   def 							A__						(self				):




      '''simple docstring'''




      return datasets.DatasetInfo(features=self.config.features				)







   def 							A__						(self       ,	lowerCamelCase				):




      '''simple docstring'''




      return [datasets.SplitGenerator(name=datasets.Split.TRAIN       ,	gen_kwargs={}				)]







   def 							A__						(self       ,	lowerCamelCase				):




      '''simple docstring'''




      if self.config.features is not None:
         _lowerCAmelCase					     =		self.config.features.arrow_schema
         if all(not require_storage_cast(lowerCamelCase				) for feature in self.config.features.values()				):
            # cheaper cast
            _lowerCAmelCase					     =		pa.Table.from_arrays([pa_table[field.name] for field in schema]       ,	schema=lowerCamelCase				)
         else:
            # more expensive cast; allows str <-> int/float or str to Audio for example
            _lowerCAmelCase					     =		table_cast(lowerCamelCase       ,	lowerCamelCase				)
      return pa_table







   def 							A__						(self				):




      '''simple docstring'''




      _lowerCAmelCase					     =		self.config.chunksize
      _lowerCAmelCase					     =		pd.read_sql(
          self.config.sql       ,	self.config.con       ,	chunksize=lowerCamelCase       ,	**self.config.pd_read_sql_kwargs				)
      _lowerCAmelCase					     =		[sql_reader] if chunksize is None else sql_reader
      for chunk_idx, df in enumerate(lowerCamelCase				):
         _lowerCAmelCase					     =		pa.Table.from_pandas(lowerCamelCase				)
         yield chunk_idx, self._cast_table(lowerCamelCase				)




"""simple docstring"""





import torch

from diffusers import HeunDiscreteScheduler
from diffusers.utils import torch_device

from .test_schedulers import SchedulerCommonTest


class       __lowerCamelCase	(   __lowercase    ):
   __UpperCamelCase									=   (HeunDiscreteScheduler,)
   __UpperCamelCase									=   10







   def 							A__						(self       ,	**lowerCamelCase				):




      '''simple docstring'''




      _lowerCAmelCase					     =		{
          """num_train_timesteps""": 1_100,
          """beta_start""": 0.0001,
          """beta_end""": 0.02,
          """beta_schedule""": """linear""",
      }

      config.update(**lowerCamelCase				)
      return config







   def 							A__						(self				):




      '''simple docstring'''




      for timesteps in [10, 50, 100, 1_000]:
         self.check_over_configs(num_train_timesteps=lowerCamelCase				)







   def 							A__						(self				):




      '''simple docstring'''




      for beta_start, beta_end in zip([0.0_0001, 0.0001, 0.001]       ,	[0.0002, 0.002, 0.02]				):
         self.check_over_configs(beta_start=lowerCamelCase       ,	beta_end=lowerCamelCase				)







   def 							A__						(self				):




      '''simple docstring'''




      for schedule in ["linear", "scaled_linear", "exp"]:
         self.check_over_configs(beta_schedule=lowerCamelCase				)







   def 							A__						(self				):




      '''simple docstring'''




      for clip_sample_range in [1.0, 2.0, 3.0]:
         self.check_over_configs(clip_sample_range=lowerCamelCase       ,	clip_sample=lowerCamelCase				)







   def 							A__						(self				):




      '''simple docstring'''




      for prediction_type in ["epsilon", "v_prediction", "sample"]:
         self.check_over_configs(prediction_type=lowerCamelCase				)







   def 							A__						(self				):




      '''simple docstring'''




      _lowerCAmelCase					     =		self.scheduler_classes[0]
      _lowerCAmelCase					     =		self.get_scheduler_config()
      _lowerCAmelCase					     =		scheduler_class(**lowerCamelCase				)

      scheduler.set_timesteps(self.num_inference_steps				)

      _lowerCAmelCase					     =		self.dummy_model()
      _lowerCAmelCase					     =		self.dummy_sample_deter * scheduler.init_noise_sigma
      _lowerCAmelCase					     =		sample.to(lowerCamelCase				)

      for i, t in enumerate(scheduler.timesteps				):
         _lowerCAmelCase					     =		scheduler.scale_model_input(lowerCamelCase       ,	lowerCamelCase				)

         _lowerCAmelCase					     =		model(lowerCamelCase       ,	lowerCamelCase				)

         _lowerCAmelCase					     =		scheduler.step(lowerCamelCase       ,	lowerCamelCase       ,	lowerCamelCase				)
         _lowerCAmelCase					     =		output.prev_sample

      _lowerCAmelCase					     =		torch.sum(torch.abs(lowerCamelCase				)				)
      _lowerCAmelCase					     =		torch.mean(torch.abs(lowerCamelCase				)				)

      if torch_device in ["cpu", "mps"]:
         assert abs(result_sum.item() - 0.1233				) < 1e-2
         assert abs(result_mean.item() - 0.0002				) < 1e-3
      else:
         # CUDA
         assert abs(result_sum.item() - 0.1233				) < 1e-2
         assert abs(result_mean.item() - 0.0002				) < 1e-3







   def 							A__						(self				):




      '''simple docstring'''




      _lowerCAmelCase					     =		self.scheduler_classes[0]
      _lowerCAmelCase					     =		self.get_scheduler_config(prediction_type="""v_prediction"""				)
      _lowerCAmelCase					     =		scheduler_class(**lowerCamelCase				)

      scheduler.set_timesteps(self.num_inference_steps				)

      _lowerCAmelCase					     =		self.dummy_model()
      _lowerCAmelCase					     =		self.dummy_sample_deter * scheduler.init_noise_sigma
      _lowerCAmelCase					     =		sample.to(lowerCamelCase				)

      for i, t in enumerate(scheduler.timesteps				):
         _lowerCAmelCase					     =		scheduler.scale_model_input(lowerCamelCase       ,	lowerCamelCase				)

         _lowerCAmelCase					     =		model(lowerCamelCase       ,	lowerCamelCase				)

         _lowerCAmelCase					     =		scheduler.step(lowerCamelCase       ,	lowerCamelCase       ,	lowerCamelCase				)
         _lowerCAmelCase					     =		output.prev_sample

      _lowerCAmelCase					     =		torch.sum(torch.abs(lowerCamelCase				)				)
      _lowerCAmelCase					     =		torch.mean(torch.abs(lowerCamelCase				)				)

      if torch_device in ["cpu", "mps"]:
         assert abs(result_sum.item() - 4.6934e-07				) < 1e-2
         assert abs(result_mean.item() - 6.1112e-10				) < 1e-3
      else:
         # CUDA
         assert abs(result_sum.item() - 4.693428650170972e-07				) < 1e-2
         assert abs(result_mean.item() - 0.0002				) < 1e-3







   def 							A__						(self				):




      '''simple docstring'''




      _lowerCAmelCase					     =		self.scheduler_classes[0]
      _lowerCAmelCase					     =		self.get_scheduler_config()
      _lowerCAmelCase					     =		scheduler_class(**lowerCamelCase				)

      scheduler.set_timesteps(self.num_inference_steps       ,	device=lowerCamelCase				)

      _lowerCAmelCase					     =		self.dummy_model()
      _lowerCAmelCase					     =		self.dummy_sample_deter.to(lowerCamelCase				) * scheduler.init_noise_sigma

      for t in scheduler.timesteps:
         _lowerCAmelCase					     =		scheduler.scale_model_input(lowerCamelCase       ,	lowerCamelCase				)

         _lowerCAmelCase					     =		model(lowerCamelCase       ,	lowerCamelCase				)

         _lowerCAmelCase					     =		scheduler.step(lowerCamelCase       ,	lowerCamelCase       ,	lowerCamelCase				)
         _lowerCAmelCase					     =		output.prev_sample

      _lowerCAmelCase					     =		torch.sum(torch.abs(lowerCamelCase				)				)
      _lowerCAmelCase					     =		torch.mean(torch.abs(lowerCamelCase				)				)

      if str(lowerCamelCase				).startswith("""cpu"""				):
         # The following sum varies between 148 and 156 on mps. Why?
         assert abs(result_sum.item() - 0.1233				) < 1e-2
         assert abs(result_mean.item() - 0.0002				) < 1e-3
      elif str(lowerCamelCase				).startswith("""mps"""				):
         # Larger tolerance on mps
         assert abs(result_mean.item() - 0.0002				) < 1e-2
      else:
         # CUDA
         assert abs(result_sum.item() - 0.1233				) < 1e-2
         assert abs(result_mean.item() - 0.0002				) < 1e-3







   def 							A__						(self				):




      '''simple docstring'''




      _lowerCAmelCase					     =		self.scheduler_classes[0]
      _lowerCAmelCase					     =		self.get_scheduler_config()
      _lowerCAmelCase					     =		scheduler_class(**lowerCamelCase       ,	use_karras_sigmas=lowerCamelCase				)

      scheduler.set_timesteps(self.num_inference_steps       ,	device=lowerCamelCase				)

      _lowerCAmelCase					     =		self.dummy_model()
      _lowerCAmelCase					     =		self.dummy_sample_deter.to(lowerCamelCase				) * scheduler.init_noise_sigma
      _lowerCAmelCase					     =		sample.to(lowerCamelCase				)

      for t in scheduler.timesteps:
         _lowerCAmelCase					     =		scheduler.scale_model_input(lowerCamelCase       ,	lowerCamelCase				)

         _lowerCAmelCase					     =		model(lowerCamelCase       ,	lowerCamelCase				)

         _lowerCAmelCase					     =		scheduler.step(lowerCamelCase       ,	lowerCamelCase       ,	lowerCamelCase				)
         _lowerCAmelCase					     =		output.prev_sample

      _lowerCAmelCase					     =		torch.sum(torch.abs(lowerCamelCase				)				)
      _lowerCAmelCase					     =		torch.mean(torch.abs(lowerCamelCase				)				)

      assert abs(result_sum.item() - 0.0_0015				) < 1e-2
      assert abs(result_mean.item() - 1.9869554535034695e-07				) < 1e-2