o
    8wi3                     @   s  d dl Z d dlZd dlmZ d dlmZmZmZmZm	Z	m
Z
 d dlZd dlZd dlZd dlZd dlmZ d dlmZ d dlmZmZ d dlmZmZ d dlmZmZmZ d d	lmZ d dlmZmZmZ d
dlmZ d
dlm Z  ej!"ej!j# G dd dZ$dS )    N)Path)IterableOptionalCallable	GeneratorUnionDict)ExperimentalWarning)
BasePruner)BaseSampler
TPESampler)Trial
FixedTrial)
RDBStorageJournalStorageJournalFileStorage)tqdm   )Pipeline)PipelineInputc                   @   s6  e Zd ZdZ						d dedee dee deeee	f  deeee
f  d	ee d
efddZedefddZedefddZedefddZ	d!dee deeef deegef fddZ			d"dee dededeeef def
ddZ		d#dee dedeeef deeddf fddZdS )$	OptimizeraM  Pipeline optimizer

    Parameters
    ----------
    pipeline : `Pipeline`
        Pipeline.
    db : `Path`, optional
        Path to trial database on disk. Use ".sqlite" extension for SQLite
        backend, and ".journal" for Journal backend (prefered for parallel
        optimization).
    study_name : `str`, optional
        Name of study. In case it already exists, study will continue from
        there. # TODO -- generate this automatically
    sampler : `str` or sampler instance, optional
        Algorithm for value suggestion. Must be one of "RandomSampler" or
        "TPESampler", or a sampler instance. Defaults to "TPESampler".
    pruner : `str` or pruner instance, optional
        Algorithm for early pruning of trials. Must be one of "MedianPruner" or
        "SuccessiveHalvingPruner", or a pruner instance.
        Defaults to no pruning.
    seed : `int`, optional
        Seed value for the random number generator of the sampler.
        Defaults to no seed.
    average_case : `bool`, optional
        Optimise for average case. Defaults to False (i.e. worst case).
    NTpipelinedb
study_namesamplerprunerseedaverage_casec              
   C   s  || _ || _|d u rd | _n4t| jj}|dkr'td td| j | _n|dkr5td| j | _n|dkrBtt	| j | _|| _
t|trN|| _n.t|trrzttj||d| _W n tyq }	 zd}
t|
d }	~	ww |d u r|t|d| _t|tr|| _n%t|trz
ttj| | _W n ty }	 zd}
t|
d }	~	ww d | _tj| j
d	| j| j| j| j  d
| _|| _d S )Nz.dbzHStorage with '.db' extension has been deprecated. Use '.sqlite' instead.z
sqlite:///z.sqlitez.journal)r   z8`sampler` must be one of "RandomSampler" or "TPESampler"zC`pruner` must be one of "MedianPruner" or "SuccessiveHalvingPruner"T)r   load_if_existsstorager   r   	direction)r   r   storage_r   suffixwarningswarnr   r   r   r   
isinstancer   r   strgetattroptunasamplersAttributeError
ValueErrorr   r
   r   prunerscreate_studyget_directionstudy_r   )selfr   r   r   r   r   r   r   	extensionemsg r4   X/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/pyannote/pipeline/optimizer.py__init__Q   s^   





	zOptimizer.__init__returnc                 C   s   | j jS )zReturn best loss so far)r/   
best_valuer0   r4   r4   r5   	best_loss   s   zOptimizer.best_lossc                 C   s   t | jj}| jj|dS )zReturn best parameters so fartrial)r   r/   best_paramsr   
parameters)r0   r<   r4   r4   r5   r=      s   zOptimizer.best_paramsc                 C   s   | j | jS )z8Return pipeline instantiated with best parameters so far)r   instantiater=   r9   r4   r4   r5   best_pipeline   s   zOptimizer.best_pipelineFinputsshow_progressc                    sB   t   t }dkrdddddtdtf fdd	}|S )
a  
        Create objective function used by optuna

        Parameters
        ----------
        inputs : `iterable`
            List of inputs to process.
        show_progress : bool or dict
            Show within-trial progress bar using tqdm progress bar.
            Can also be a **kwarg dict passed to tqdm.

        Returns
        -------
        objective : `callable`
            Callable that takes trial as input and returns correspond loss.
        TzCurrent trialFr   )descleavepositionr<   r7   c              
      s0  zj  }W n ty } z
d}g }W Y d}~nd}~ww g }g }j j j| d}dkrAtddt i}|d t D ]q\}}	t		 }
||	}t		 }|
||
  t		 }|du rp||	|}|
| nddlm} ||	d |||	d}t		 }|
||  dkr|d	 jdu rqE| |du rt|nt|| | |rtj qEdkr|  | d
t| | dt| |du rtt|d	kr|d  } }}nt|dd\\}\}}}}n
|jdd\}\}}jr|du r|S t|S j  dkr|S |S )zCompute objective value

            Parameter
            ---------
            trial : `Trial`
                Current trial

            Returns
            -------
            loss : `float`
                Loss
            Nr;   Ftotalr   )get_annotated
annotation)uemr   processing_timeevaluation_timeg?)alphaminimizer4   )r   
get_metricNotImplementedErrorr?   r>   r   lenupdate	enumeratetimeappendlosspyannote.databaserG   r   reportnpmeanabsshould_pruner(   structsTrialPrunedcloseset_user_attrsumunique	bayes_mvsconfidence_intervalr   r.   )r<   metricr2   lossesrJ   rK   r   progress_bariinputbefore_processingoutputafter_processingbefore_evaluationrU   rG   _after_evaluationrY   lower_boundupper_boundrA   r0   rB   r4   r5   	objective   sl   


"


z*Optimizer.get_objective.<locals>.objective)listrP   r   float)r0   rA   rB   n_inputsrr   r4   rq   r5   get_objective   s   azOptimizer.get_objective
   n_iterations
warm_startc                 C   s   d| j _| j||d}|r4| j |}t  tjdtd | j	| W d   n1 s/w   Y  | jj
||ddd d| j _| j| jd	S )
a  Tune pipeline

        Parameters
        ----------
        inputs : iterable
            List of inputs processed by the pipeline at each iteration.
        n_iterations : int, optional
            Number of iterations. Defaults to 10.
        warm_start : dict, optional
            Nested dictionary of initial parameters used to bootstrap tuning.

        Returns
        -------
        result : dict
            ['loss']
            ['params'] nested dictionary of optimal parameters
        TrB   ignorecategoryNr   n_trialstimeoutn_jobsFrU   params)r   trainingrv   _flattenr#   catch_warningsfilterwarningsr	   r/   enqueue_trialoptimizer:   r=   )r0   rA   rx   ry   rB   rr   flattened_paramsr4   r4   r5   tune"  s   
zOptimizer.tunec           	   
   c   s   | j ||d}z| j}W n ty" } z	tj}W Y d}~nd}~ww |rL| j|}t  tj	dt
d | j| W d   n1 sGw   Y  	 d| j_| jj|dddd z| j}| j}W n tyu } zW Y d}~qLd}~ww d| j_||d	V  qM)
a  

        Parameters
        ----------
        inputs : iterable
            List of inputs processed by the pipeline at each iteration.
        warm_start : dict, optional
            Nested dictionary of initial parameters used to bootstrap tuning.

        Yields
        ------
        result : dict
            ['loss']
            ['params'] nested dictionary of optimal parameters
        rz   Nr{   r|   Tr   r~   Fr   )rv   r:   r+   rX   infr   r   r#   r   r   r	   r/   r   r   r   r=   )	r0   rA   ry   rB   rr   r:   r2   r   r=   r4   r4   r5   	tune_iterN  s6   


zOptimizer.tune_iter)NNNNNT)F)rw   NT)NT)__name__
__module____qualname____doc__r   r   r   r&   r   r   r
   intboolr6   propertyrt   r:   dictr=   r@   r   r   r   r   r   rv   r   r   r   r4   r4   r4   r5   r   5   s~    
A

 

/
r   )%rS   r#   pathlibr   typingr   r   r   r   r   r   numpyrX   optuna.loggingr(   optuna.prunersoptuna.samplersoptuna.exceptionsr	   r
   r   r   optuna.trialr   r   optuna.storagesr   r   r   r   r   r   r   loggingset_verbosityWARNINGr   r4   r4   r4   r5   <module>   s&    