U
    Vc #                     @   sj   d dl Zd dlmZ d dlmZ d dlmZ d dlm	Z	 d dl
mZ d dlmZ dZG d	d
 d
ejZdS )    N)wrappers)plugin_util)provider)	http_util)base_plugin)metadatad   c                   @   sv   e Zd ZdZejZdd Zej	j
dd Zdd Zej	j
dd	 Zd
d Zdd Zdd Zdd Zdd Zdd ZdS )PrCurvesPluginz6A plugin that serves PR curves for individual classes.c                 C   s2   |j | _|jpi tjt| _tj	ddd| _
dS )zInstantiates a PrCurvesPlugin.

        Args:
          context: A base_plugin.TBContext instance. A magic container that
            TensorBoard uses to make objects available to the plugin.
        zPR curver   )Z	data_kindZlatest_known_versionN)Zdata_provider_data_providerZsampling_hintsgetr   PLUGIN_NAME_DEFAULT_DOWNSAMPLING_downsample_tor   Z_MetadataVersionChecker_version_checker)selfcontext r   Q/tmp/pip-unpacked-wheel-g8kmtpbc/tensorboard/plugins/pr_curve/pr_curves_plugin.py__init__"   s    
 zPrCurvesPlugin.__init__c              
   C   s   t |j}t |j}|jd}|s6t|ddS |jd}|sTt|ddS zt|| 	||||d}W n: t
k
r } zt|t|dd W Y S d}~X Y nX |S )	a  A route that returns a JSON mapping between runs and PR curve data.

        Returns:
          Given a tag and a comma-separated list of runs (both stored within GET
          parameters), fetches a JSON object that maps between run name and objects
          containing data required for PR curves for that run. Runs that either
          cannot be found or that lack tags will be excluded from the response.
        runz,No runs provided when fetching PR curve datai  tagz+No tag provided when fetching PR curve dataapplication/jsonz
text/plainN)r   r   environexperiment_idargsgetlistr   Respondr   pr_curves_impl
ValueErrorstr)r   requestctx
experimentrunsr   responseer   r   r   pr_curves_route2   s2    
    *zPrCurvesPlugin.pr_curves_routec           
         sz   i }t ||g} jj||tj| jd}|D ]D}||i |}	|	dkr^td||f  fdd|	D ||< q0|S )a}  Creates the JSON object for the PR curves response for a run-tag
        combo.

        Arguments:
          runs: A list of runs to fetch the curves for.
          tag: The tag to fetch the curves for.

        Raises:
          ValueError: If no PR curves could be fetched for a run and tag.

        Returns:
          The JSON object for the PR curves route response.
        )r   plugin_nameZrun_tag_filterZ
downsampleNz1No PR curves could be found for run %r and tag %rc                    s   g | ]}  |qS r   )_process_datum).0dr   r   r   
<listcomp>t   s     z1PrCurvesPlugin.pr_curves_impl.<locals>.<listcomp>)	r   ZRunTagFilterr
   Zread_tensorsr   r   r   r   r   )
r   r!   r"   r#   r   Zresponse_mappingZrtfZread_resultr   datar   r+   r   r   V   s&    zPrCurvesPlugin.pr_curves_implc                 C   s.   t |j}t |j}t|| ||dS )a  A route (HTTP handler) that returns a response with tags.

        Returns:
          A response that contains a JSON object. The keys of the object
          are all the runs. Each run is mapped to a (potentially empty) dictionary
          whose keys are tags associated with run and whose values are metadata
          (dictionaries).

          The metadata dictionaries contain 2 keys:
            - displayName: For the display name used atop visualizations in
                TensorBoard.
            - description: The description that appears near visualizations upon the
                user hovering over a certain icon.
        r   )r   r   r   r   r   r   	tags_impl)r   r    r!   r"   r   r   r   
tags_routew   s     
 zPrCurvesPlugin.tags_routec           
      C   s   | j j||tjd}dd |D }| D ]V\}}| D ]D\}}t|j}	| j|	j	||sbq:|j
t|jd|| |< q:q*|S )zCreates the JSON object for the tags route response.

        Returns:
          The JSON object for the tags route response.
        )r   r'   c                 S   s   i | ]
}|i qS r   r   )r)   r   r   r   r   
<dictcomp>   s      z,PrCurvesPlugin.tags_impl.<locals>.<dictcomp>)ZdisplayNamedescription)r
   Zlist_tensorsr   r   itemsZparse_plugin_metadataZplugin_contentr   okversionZdisplay_namer   Zmarkdown_to_safe_htmlr1   )
r   r!   r"   mappingresultr   Ztag_to_time_seriesr   Ztime_seriesZmdr   r   r   r.      s"      zPrCurvesPlugin.tags_implc                 C   s   | j | jdS )zGets all routes offered by the plugin.

        Returns:
          A dictionary mapping URL path to route that handles it.
        )z/tagsz
/pr_curves)r/   r&   r+   r   r   r   get_plugin_apps   s    zPrCurvesPlugin.get_plugin_appsc                 C   s   dS )NFr   r+   r   r   r   	is_active   s    zPrCurvesPlugin.is_activec                 C   s   t jdddS )Nztf-pr-curve-dashboardz	PR Curves)Zelement_nameZtab_name)r   ZFrontendMetadatar+   r   r   r   frontend_metadata   s    z PrCurvesPlugin.frontend_metadatac                 C   s   |  |j|j|jS )zConverts a TensorDatum into a dict that encapsulates information on
        it.

        Args:
          datum: The TensorDatum to convert.

        Returns:
          A JSON-able dictionary of PR curve data for 1 step.
        )_make_pr_entrystep	wall_timenumpy)r   Zdatumr   r   r   r(      s    
zPrCurvesPlugin._process_datumc                 C   s4  t j}t j}t j}t j}|||gddf tjdd}t|d }	|	dkrd||	 dkrd|	d8 }	qF|	d }
|j	d }t
dd|}dd || D }d	d || D }d
d || D }dd || D }|||t jd|
f  |t jd|
f  |d|
 |d|
 |d|
 |d|
 |d|
  d	S )a$  Creates an entry for PR curve data. Each entry corresponds to 1
        step.

        Args:
          step: The step.
          wall_time: The wall time.
          data_array: A numpy array of PR curve data stored in the summary format.

        Returns:
          A PR curve entry.
        Nr   )Zaxis   g        g      ?c                 S   s   g | ]}t |qS r   intr)   vr   r   r   r,      s     z1PrCurvesPlugin._make_pr_entry.<locals>.<listcomp>c                 S   s   g | ]}t |qS r   r?   rA   r   r   r   r,      s     c                 S   s   g | ]}t |qS r   r?   rA   r   r   r   r,      s     c                 S   s   g | ]}t |qS r   r?   rA   r   r   r   r,      s     )	r<   r;   Z	precisionZrecalltrue_positivesfalse_positivestrue_negativesfalse_negatives
thresholds)r   ZTRUE_POSITIVES_INDEXZFALSE_POSITIVES_INDEXZTRUE_NEGATIVES_INDEXZFALSE_NEGATIVES_INDEXZastyper@   sumlenshapenpZlinspaceZPRECISION_INDEXtolistZRECALL_INDEX)r   r;   r<   Z
data_arrayZtp_indexZfp_indexZtn_indexZfn_indexZ	positivesZend_index_inclusiveZ	end_indexZnum_thresholdsrG   rC   rD   rE   rF   r   r   r   r:      s:    "






zPrCurvesPlugin._make_pr_entryN)__name__
__module____qualname____doc__r   r   r'   r   r   RequestZapplicationr&   r   r/   r.   r7   r8   r9   r(   r:   r   r   r   r   r	      s   
#!
r	   )r=   rK   Zwerkzeugr   Ztensorboardr   Ztensorboard.datar   Ztensorboard.backendr   Ztensorboard.pluginsr   Ztensorboard.plugins.pr_curver   r   ZTBPluginr	   r   r   r   r   <module>   s   