o
    Wh.                     @   sd   d dl mZ d dlZd dlmZ d dlZd dlm	Z
 d dlmZ d dlmZmZ G dd deZdS )    )cycleN)FigureCanvasAgg)Figure)BaseSolutionSolutionResultsc                       s2   e Zd ZdZ fddZdd Zd
dd	Z  ZS )	Analyticsa  
    A class for creating and updating various types of charts for visual analytics.

    This class extends BaseSolution to provide functionality for generating line, bar, pie, and area charts
    based on object detection and tracking data.

    Attributes:
        type (str): The type of analytics chart to generate ('line', 'bar', 'pie', or 'area').
        x_label (str): Label for the x-axis.
        y_label (str): Label for the y-axis.
        bg_color (str): Background color of the chart frame.
        fg_color (str): Foreground color of the chart frame.
        title (str): Title of the chart window.
        max_points (int): Maximum number of data points to display on the chart.
        fontsize (int): Font size for text display.
        color_cycle (cycle): Cyclic iterator for chart colors.
        total_counts (int): Total count of detected objects (used for line charts).
        clswise_count (Dict[str, int]): Dictionary for class-wise object counts.
        fig (Figure): Matplotlib figure object for the chart.
        ax (Axes): Matplotlib axes object for the chart.
        canvas (FigureCanvas): Canvas for rendering the chart.
        lines (dict): Dictionary to store line objects for area charts.
        color_mapping (Dict[str, str]): Dictionary mapping class labels to colors for consistent visualization.

    Methods:
        process: Process image data and update the chart.
        update_graph: Update the chart with new data points.

    Examples:
        >>> analytics = Analytics(analytics_type="line")
        >>> frame = cv2.imread("image.jpg")
        >>> results = analytics.process(frame, frame_number=1)
        >>> cv2.imshow("Analytics", results.plot_im)
    c                    sD  t  jdi | | jd | _| jdv rdnd| _d| _d| _d| _d| _d	| _	d
| _
d}tg d| _d| _i | _| jdv rpi | _t| j|d| _t| j| _| jjd| jd| _| jdkrn| jjg g d| jd\| _dS dS | jdv rtj|| jd\| _| _t| j| _| j| j i | _| jdkr| jd dS dS dS )zSInitialize Analytics class with various chart types for visual data representation.analytics_type>   barpieClasseszFrame#zTotal Countsz#F3F3F3z#111E68zUltralytics Solutions-      )g)@g@z#DD00BAz#042AFFz#FF4447z#7D24FFz#BD00FFr   >   arealine)	facecolorfigsizeo   )r   r   cyan)color	linewidth)r   r   r
   equalN )super__init__CFGtypex_labely_labelbg_colorfg_colortitle
max_pointsfontsizer   color_cycletotal_countsclswise_countlinesr   figFigureCanvascanvasadd_subplotaxplot
line_widthr   pltsubplotsset_facecolorcolor_mappingaxis)selfkwargsr   	__class__r   S/var/www/vscode/kcb/lib/python3.10/site-packages/ultralytics/solutions/analytics.pyr   2   s<   



zAnalytics.__init__c                 C   s   |  | | jdkr!| jD ]	}|  jd7  _q| j|d}d| _nD| jdv r]i | _| jD ]%}| jt| | jv rG| j| jt|   d7  < q,d| j| jt| < q,| j|| j| jd}nt	| j dt
|t| j| jdS )	a  
        Process image data and run object tracking to update analytics charts.

        Args:
            im0 (np.ndarray): Input image for processing.
            frame_number (int): Video frame number for plotting the data.

        Returns:
            (SolutionResults): Contains processed image `plot_im`, 'total_tracks' (int, total number of tracked objects)
                and 'classwise_count' (dict, per-class object count).

        Raises:
            ModuleNotFoundError: If an unsupported chart type is specified.

        Examples:
            >>> analytics = Analytics(analytics_type="line")
            >>> frame = np.zeros((480, 640, 3), dtype=np.uint8)
            >>> results = analytics.process(frame, frame_number=1)
        r      )frame_numberr   >   r	   r
   r   )r:   
count_dictr-   u    chart is not supported ❌)plot_imtotal_tracksclasswise_count)extract_tracksr   boxesr%   update_graphr&   clssnamesintModuleNotFoundErrorr   len	track_ids)r4   im0r:   _r<   clsr   r   r8   processX   s   




zAnalytics.processNr   c              
      s  |du rWt  j t|}t  j t j}t| jkr3| j d | j d }} j	||  j
d  jd  jd  j jd  nt| }t| }|dkr*tg d} jjrz jjd  nt g }d	d
 | D }	 jjrt jj| D ]
\}
}|
 |	|< qt |t|}t|}| D ]*}t |	| t|| |	|< t|	| |k rt |	| d|t|	|  f|	|< qt| jkr|dd }| D ]}|	| dd |	|< q j  |	 D ]'\}}t|} jj|||dd  jj||| jd jd | dd q|dkr j  |D ]}| jvrFt j j|< q6 fdd|D } jj|||d}t||D ]\}} jj |! |" d  |# t$|dd j%d q_t||D ]
\}}|
| q jj&dd j% j%d |dkrt'|fdd|D }d} j   jj(|||d j%idd \}}d!d t||D } jj&||d"d#d$d%  j)j*d&d'd(  j+d)  jj, j- j% j.d*  jj/ j0 j% j.d+ d*  jj1 j2 j% j.d+ d*  jj&dd j3 j3d}|4 D ]	}| j% q j5   j6   j78  t  j7j9: }t;<|dddddd+f t;j=} >| |S ),a  
        Update the graph with new data for single or multiple classes.

        Args:
            frame_number (int): The current frame number.
            count_dict (Dict[str, int] | None): Dictionary with class names as keys and counts as values for multiple
                classes. If None, updates a single line graph.
            plot (str): Type of the plot. Options are 'line', 'bar', 'pie', or 'area'.

        Returns:
            (np.ndarray): Updated image containing the graph.

        Examples:
            >>> analytics = Analytics(analytics_type="bar")
            >>> frame_num = 10
            >>> results_dict = {"person": 5, "car": 3}
            >>> updated_image = analytics.update_graph(frame_num, results_dict, plot="bar")
        NCountsz#7b0068*   r   r   r   c                 S   s   i | ]}|t g qS r   )nparray).0keyr   r   r8   
<dictcomp>       z*Analytics.update_graph.<locals>.<dictcomp>r9   gffffff?)r   alphaoz Data Points)r   r   marker
markersizelabelr	   c                    s   g | ]} j | qS r   )r2   )rQ   rY   )r4   r   r8   
<listcomp>   s    z*Analytics.update_graph.<locals>.<listcomp>)r      centerbottom)havar   z
upper left   )locr#   r   	edgecolorr
   c                    s   g | ]}|  d  qS )d   r   )rQ   size)totalr   r8   rZ      rT   Z   r   )labels
startangle	textpropsautopctc                 S   s"   g | ]\}}| d |ddqS )z (z.1fz%)r   )rQ   rY   
percentager   r   r8   rZ      s   " r   zcenter left)r9   r   g      ?r9   )r!   ra   bbox_to_anchorg?g      ?)leftrightz#f0f0f0)r   r#      )?rO   appendr   	get_xdatafloat	get_ydatar%   rF   r"   set_data	set_label	set_color
set_markerset_markersizer.   listkeysvaluesr   r,   r'   rP   zippadclearitemsnextfill_betweenr-   r2   r$   r	   textget_x	get_width
get_heightstrr    legendsumr
   r(   subplots_adjustr1   	set_titler!   r#   
set_xlabelr   
set_ylabelr   r   	get_textsrelimautoscale_viewr*   drawrendererbuffer_rgbacv2cvtColorCOLOR_RGBA2BGRdisplay_output)r4   r:   r;   r-   x_datay_datarg   countsr$   y_data_dictr   rR   
max_lengthr   rY   colorsbarsr	   countpercentagesstart_anglewedgesrI   legend_labelsr   r   rH   r   )r4   re   r8   rA      s   "
"$


	

	





$
zAnalytics.update_graph)Nr   )__name__
__module____qualname____doc__r   rK   rA   __classcell__r   r   r6   r8   r      s
    #&(r   )	itertoolsr   r   matplotlib.pyplotpyplotr/   numpyrO   matplotlib.backends.backend_aggr   r)   matplotlib.figurer   ultralytics.solutions.solutionsr   r   r   r   r   r   r8   <module>   s   