
    i0                         S r SSKJr  SSKrSSKrSSKrSSKJrJ	r	J
r
  SSKr\R                  " \5      rSrSrS\S\4S jrS	\\4S
\R(                  S\S\S\S\4
S jjr      S:S\\   S\\   S\	\   S\S\S\S\	\\      S\4S jjr   S;S\
\\\   4   S\
\\\   4   S\	\   S\	\
\\\   4      S\4
S jjr    S<S\S\S\	\   S\S\	\   S\4S jjr\S :X  Ga  SSKr\R8                  " S!S"9r\R=                  S#\S$S%S&9  \R=                  S'\S(S)S&9  \R=                  S*\SS+S&9  \R=                  S,\S-S.S&9  \R=                  S/\S	S0S&9  \R=                  S1S2S3S49  \R=                  S5S2S6S49  \R?                  5       r \RB                  " \RD                  S7S89  \ RF                  =(       a    \ RH                  (       + r%\" \ RL                  \ RN                  \ RP                  \%\ RR                  \ RT                  S99  gg)=z*Plotting utilities for experiment results.    N)ListOptionalDicti    i,  pathreturnc                 l    [         R                  R                  U 5      S   R                  5       nUS;   $ )N   >   .tif.tiff)osr   splitextlower)r   exts     M   /home/ubuntu/codebase/yexijia/保研/colocation_mvp/src/experiment/plotter.py_is_tiff_pathr      s0    
''

4
 
#
)
)
+C###    @  figoutput_pathdpi	max_bytesmin_dpi_exclusivec                    U(       d  [        S5      e[        U5      nX$::  a  US-   n[        U5      (       d)  U R                  XSS9  [        R                  SU 35        g[        R                  " [        R                  R                  U5      =(       d    SSS	9  S
S0nU R                  5       u  pg[        S5       GH  nSn	US:  a  SU-  n	U R                  Xi-  Xy-  SS9  Un
US:  a!  [        US-   [        USUS-
  -  -  5      5      n
[        R                  " SSS9 nUR                   nSSS5         U R                  WU
SUS9  [        R                  R#                  U5      nX::  a@  X:  a;  [        R$                  " X5        [        R                  SU SU
 SU SU	S S3	5          g[        R&                  " U5        GM	     [        US-   [-        US5      5      nU R                  UUSUS9  [        R                  R+                  U5      (       a  [        R                  R#                  U5      OSn[        R/                  SU SU SU 35        g! , (       d  f       GN0= f! [(         aM     [        R                  R+                  W5      (       a  [        R&                  " U5        e ! [(         a     e f = ff = f) zSave figure with TIFF + dpi + filesize constraints.

Requirements (per user request):
- If TIFF: output as TIFF, dpi > 300, file size <= 2MB.
- For non-TIFF: still respect dpi argument but no size enforcement.
zoutput_path is requiredr	   tight)r   bbox_incheszPlot saved to N.T)exist_okcompressiontiff_lzw
   g      ?gq=
ףp?)forward   gffffff?   r   F)suffixdelete)r   r   
pil_kwargsz (format=TIFF, dpi=z, size=z bytes, scale=.3f)r   z.Saved TIFF but could not guarantee <=2MB (dpi=z	 bytes): )
ValueErrorintr   savefigloggerinfor   makedirsr   dirnameget_size_inchesrangeset_size_inchesmaxtempfileNamedTemporaryFilenamegetsizereplaceremove	Exceptionexistsminwarning)r   r   r   r   r   r&   orig_worig_hattemptscalecur_dpitmptmp_pathsizefallback_dpis                  r   _save_figure_with_constraintsrH      s    233 c(C
!#%%Kg>n[M23 KK,3dC  ,J ((*NF 9a<GOEM a<+a/SDWq[<Q5R1STG((F#xxH G	KK#%	   77??8,D W%@

81$[M1DWIWUYTZZhinorhsstu 		(#A X (1,c#sm<LKK	   ,.77>>++F+F277??;'BD
NN
8gdVS\]h\ijO GF(  	77>>(++IIh'   	sC   !I7A4I)-I)
I&	)
K 4:J/.K /
J<9K ;J<<K baselineourstitlexlabelylabelpreference_weightedc           	         [        [        S[        U 5      S-   5      5      n[        R                  " SS9n	[        R
                  " XSSSSS9  [        R
                  " XS	S
SSS9  Ub0  [        U5      [        U 5      :X  a  [        R
                  " XSSSSS9  [        R                  " USS9  [        R                  " USS9  [        R                  " USSS9  [        R                  " SS9  [        R                  " SSS9  [        R                  " SS/5        [        R                  " S[        U 5      /5        [        R                  " 5         U(       a  [        XUS9  O[        R                  " 5         [        R                   " 5         g)a  Plot learning curve comparing baseline, contrastive, and optionally preference-weighted methods.

Args:
    baseline: List of accuracy scores for baseline method
    ours: List of accuracy scores for contrastive method
    output_path: Path to save plot (optional)
    title: Plot title
    xlabel: X-axis label
    ylabel: Y-axis label
    preference_weighted: Optional list of accuracy scores for preference-weighted method (2025-style)
r	   )r       figsizeb-oBaseline   rP   label	linewidth
markersizer-sContrastiveNg-^Preference-Weighted (2025)   fontsize   boldr`   
fontweight   T333333?alphar   r   )listr2   lenpltfigureplotrL   rM   rK   legendgridylimxlimtight_layoutrH   showclose)
rI   rJ   r   rK   rL   rM   rN   r   roundsr   s
             r   plot_learning_curverw   v   s   * %3x=1,-.F
**W
%CHHVuJ!PQRHHV5qQ&3/B+Cs8}+Te;WcdqrsJJv#JJv#IIebV4JJHHTHHaVHHaX  %cC@
IIKr   baseline_metricscontrastive_metricspreference_weighted_metricsc           
         [        [        S[        U S   5      S-   5      5      n[        R                  " SSSS9u  pgUR                  SSSS	9  SS
US   4SSUS   4SSUS   4SSUS   4/nU GHJ  u  pnX	   nX   nUR                  X\SSSSS9  UR                  X]SSSSS9  Ub4  X;   a/  X9   n[        U5      [        U5      :X  a  UR                  X^SSSSS9  UR                  SSS 9  UR                  U
SS 9  UR                  U
S!SS	9  UR                  S"S 9  UR                  S#S$S%9  UR                  S&S/5        UR                  S[        U5      /5        [        U5      S&:  d  M  UR                  US'   S( [        U5      US'   4S)S*S+S,S-9  UR                  US'   S( [        U5      US'   4S)S.S+S,S-9  GMM     [        R                  " 5         U(       a  [!        XbUS/9  O[        R"                  " 5         [        R$                  " 5         g)0al  Plot all metrics (accuracy, precision, recall, F1) in subplots.

Args:
    baseline_metrics: Dictionary with 'accuracy', 'precision', 'recall', 'f1' lists
    contrastive_metrics: Dictionary with 'accuracy', 'precision', 'recall', 'f1' lists
    output_path: Path to save plot (optional)
    preference_weighted_metrics: Optional third method metrics (2025-style)
r	   accuracyrU   )ra   r    rQ   zEvaluation Metrics Comparison   rb   rc   Accuracy)r   r   	precision	Precision)r   r	   recallRecall)r	   r   f1zF1 Score)r	   r	   rS   rT   r"   rV   rZ   r[   Nr\   r]   Interaction Roundr    r_   r^   	   Trf   rg   r   r)   r'   zoffset points)r"   r   left   )
textcoordsxytexthar`   )r"   iri   )rj   r2   rk   rl   subplotssuptitlern   
set_xlabel
set_ylabel	set_titlero   rp   set_ylimset_xlimannotaters   rH   rt   ru   )rx   ry   r   rz   r   rv   r   axesmetrics
metric_keymetric_nameaxrI   contrastivepws                  r   plot_all_metrics_funcr      s7    %3/
;<q@ABFQ84ICLL02&LQ 
Zd,	k4:.	8T$Z(	z4:&	G (/#
#/)5
%zQSTU
U-1YZ[&2z7`,8B2w#h-'E1MYZghi
)B7
kB/
[2&A
		1	
C 
QF
QH&' x=1KK8B<,Hx|/L"1&VVW  YKK;r?3/3{3C[QS_2U"1(vXY  [/ (/4 %cC@
IIKr   baseline_pathcontrastive_pathplot_all_metricspreference_weighted_pathc                    [        U S5       n[        R                  " U5      nSSS5        [        US5       n[        R                  " U5      nSSS5        [        W[        5      (       a	  SU0n	SW0n
OUn	Wn
SnU(       aj  [
        R                  R                  U5      (       aF  [        US5       n[        R                  " U5      nSSS5        [        W[        5      (       a  UOSU0nU(       a  SU	;   a  SSK	J
n  U" U	U
UUUS9  gU(       a  US   OSn[        U	S   U
S   UUUS9  g! , (       d  f       GN= f! , (       d  f       N= f! , (       d  f       N= f)	a  Load results from JSON files and plot.

Args:
    baseline_path: Path to baseline metrics JSON file
    contrastive_path: Path to contrastive metrics JSON file
    output_path: Path to save plot (optional)
    plot_all_metrics: If True, plot all metrics in subplots; if False, plot only accuracy
    preference_weighted_path: Optional path to preference-weighted metrics JSON (2025-style third method)
rNr|   r   r   )r   )rz   r   )r   rN   r   )openjsonload
isinstancerj   r   r   isfiledictexperiment.plotterr   rw   )r   r   r   r   r   r   fbaseline_datacontrastive_datarx   ry   
pw_metricspw_datar   pw_accs                  r   plot_from_jsonr      s9   " 
mS	!Q		! 
" 
	$99Q< 
% -&&&6)+;<(.JBGGNN3K$L$L*C0AiilG 1 *7D 9 9W
G?T
K+;;<(2	
 ,6J'4Z(
+# &	
? 
"	! 
%	$ 10s"   D,D>2E,
D;>
E
E__main__zPlot learning curves)descriptionz
--baselinezresults/metrics_baseline.jsonzPath to baseline metrics JSON)typedefaulthelpz--contrastivez results/metrics_contrastive.jsonz Path to contrastive metrics JSONz--preference-weightedz@Path to preference-weighted metrics JSON (optional third method)z--outputzresults/learning_curve.tiffzOutput path for plotz--dpiz0Output DPI (must be >300 for TIFF, default: 320)z--accuracy-only
store_truezHOnly plot accuracy (single figure); default when not using --all-metrics)actionr   z--all-metricszBPlot all metrics (accuracy, precision, recall, F1) in 2x2 subplotsz4%(asctime)s - %(name)s - %(levelname)s - %(message)s)levelformat)r   r   r   )NzLearning Curve Comparisonr   r~   Nr   )NNr   )NFNr   )+__doc__matplotlib.pyplotpyplotrl   r   r   r5   typingr   r   r   logging	getLogger__name__r-   _MAX_TIFF_BYTES_MIN_DPI_EXCLUSIVEstrboolr   Figurer+   rH   floatrw   r   r   argparseArgumentParserparseradd_argument
parse_argsargsbasicConfigINFOall_metricsaccuracy_onlyplot_allrI   r   outputrN   r    r   r   <module>r      s7   0   	  ' ' 			8	$! $ $ $ $/^	^^ 
^ 	^
 ^H "&,%1545k4
u+4 #4 	4
 4 4 "$u+.4 
4t "&DH<3U+,<c4;./< #< "*$sDK/?*@!A	<
 
<D "&".26
6
6
 #6
 	6

 'sm6
 
6
r z$$1GHF
38W;  =
c;]>  @
/c4^  `

6S2  4
c3N  P
),f  h
`  b DllE :(:(:$:H!!%!9!9HH9 r   