
    @-Ph;                        d dl Z d dlZd dlmZ d dlZd dlZd dl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mZmZ d dlZd dlZdZdZ e
j        e          Z e
j                     d Zd Zd	 Z d
 Z!d Z"d Z#d Z$d Z%d Z&d Z'd!dZ(d Z)d"dZ*ddddZ+d"dZ,d#dZ-d Z.d Z/d Z0d Z1d Z2d Z3ed k    r e3             dS dS )$    N)literal_eval)defaultdict)ArgumentParserArgumentError	REMAINDERRawTextHelpFormatter)runrmcleanlistplotattachpeakaA  
Available commands:

    run      run a given command or python file
    attach   alias for 'run --attach': attach to an existing process by pid or name
    rm       remove a given file generated by mprof
    clean    clean the current directory from files created by mprof
    list     display existing profiles, with indices
    plot     plot memory consumption generated by mprof run
    peak     print the maximum memory used by an mprof run

Type mprof <command> --help for usage help on a specific command.
For example, mprof plot --help will list all plotting options.
c                      t          dt          j        t          j        d                   z             t          t
                     d S )Nz)Usage: %s <command> <options> <arguments>r   )printospbasenamesysargvhelp_msg     E/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/mprof.pyprint_usager   '   s>    	
5L!%%& ' ' '	(OOOOOr   c                  4   t          t          j                  dk    r"t                       t          j        d           t          j        d         t
          vr"t                       t          j        d           t          j                            d          S )z/Pop first argument, check it is a valid action.   )lenr   r   r   exitALL_ACTIONSpopr   r   r   
get_actionr!   -   sd    
38}}8A;+%%8<<??r   c                    t          j         d          }|                                 | dk    rt          j        |          }ng }| D ]}|dk    r		 t          |          }n# t          $ r d}Y nw xY w|D	 ||         }n # t
          $ r t	          d|z            w xY w||vr|                    |           rt          j        |          r||vr|                    |           t          j	        |          rt	          d|z            t	          d|z            t          |          D ]W}t          j        |          }|d         d	z   |d
         z   }t          j        |          r||vr|                    |           X|S )a  Return list of profile filenames.

    Parameters
    ==========
    args (list)
        list of filename or integer. An integer is the index of the
        profile in the list of existing profiles. 0 is the oldest,
        -1 in the more recent.
        Non-existing files cause a ValueError exception to be thrown.

    Returns
    =======
    filenames (list)
        list of existing memory profile filenames. It is guaranteed
        that an given file name will not appear twice in this list.
    mprofile_??????????????.datall--Nz%Invalid index (non-existing file): %szPath %s is a directoryzFile %s not foundr   _tsr   )globsortcopyint
ValueError
IndexErrorappendr   isfileisdirreversedsplitext)argsprofiles	filenamesargindexfilenamepartstimestamp_files           r   get_profile_filenamesr:   9   s   " y677HMMOOOu}}Ih''			 	@ 	@Cd{{C    T'HH! T T T$%Ls%RSSST 9,,$$X...:c?? @)++!((---Ys^^ @$%=%CDDD$%83%>??? Y'' - -X&&qE)E!H4:n%% 	-.	*I*I^,,,s   A""A10A17B  Bc                     t          d          } |                     ddt          j                   |                                 }t          d          }t          |          D ]\  }}t          j        |          d         	                    d          d	         }t          d
                    |||dd         |dd         |dd         |dd         |dd         |dd                              dS )z(Display existing profiles, with indices.z*mprof list
This command takes no argument.usage	--versionversionactionr?   r$   r   _z:{index} {filename} {hour}:{min}:{sec} {day}/{month}/{year}N         
         )r6   r7   yearmonthdayhourminsec)r   add_argumentmp__version__
parse_argsr:   	enumerater   r1   splitr   format)parserr2   r4   nr7   tss         r   list_actionrZ   s   s   ?A A AF
Ir~NNND%e,,I ++ D D8\(##A&,,S11"5JvAbqb6AaCb1gad8BrE2b5	  C C	D 	D 	D 	DD Dr   c                     t          d          } |                     ddt          j                   |                     dddd	d
           |                     ddd           |                                 }t          |j                  dk    r#t          d           t          j	        d           t          |j                  }|j        r%t          d           |D ]}t          |           dS |D ]}t          j        |           dS )z)TODO: merge with clean_action (@pgervais)z'mprof rm [options] numbers_or_filenamesr<   r>   r?   r@   	--dry-rundry_runF
store_true2Show what will be done, without actually doing it.destdefaultrA   helpnumbers_or_filenames*znumbers or filenames removednargsrc   r   z9A profile to remove must be provided (number or filename)r   Files to be removed: N)r   rP   rQ   rR   rS   r   rd   r   r   r   r:   r]   osremoverW   r2   r4   r7   s       r   	rm_actionrl      sF   "KLLLF
Ir~NNN
)U+U  W W W .c?  A A AD
4$%%**IJJJ%d&?@@I|  %&&&! 	 	H(OOOO	 	 " 	  	 HIh	  	 r   c                  n   t          d          } |                     ddt          j                   |                     dddd	d
           |                                 }t          d          }|j        r%t          d           |D ]}t          |           dS |D ]}t          j	        |           dS )z/Remove every profile file in current directory.z+mprof clean
This command takes no argument.r<   r>   r?   r@   r\   r]   Fr^   r_   r`   r$   rh   N)
r   rP   rQ   rR   rS   r:   r]   r   ri   rj   rk   s       r   clean_actionrn      s    @B B BF
Ir~NNN
)U+U  W W W D%e,,I|  %&&&! 	 	H(OOOO	 	 " 	  	 HIh	  	 r   c                 h    t          d          fd| D             } d                    |           S )z/Given a set or arguments, compute command-line.z 	c                 N    g | ]!}                     |          r|nd |z   d z   "S )')
isdisjoint).0sblankss     r   
<listcomp>z get_cmd_line.<locals>.<listcomp>   s8    GGGQ""1%%8AA37S=GGGr    )setjoin)r2   ru   s    @r   get_cmd_linerz      s7    ZZFGGGG$GGGD88D>>r   c                 |    t           j                                        D ]}| |                                v r|c S d S )N)rQ   psutilprocess_itername)r~   is     r   find_first_processr      sE    Y##%%  16688HHH 4r   c                      t           j        } | d d         dgz   | dd          z   t           _        t                       d S )Nr   --attach)r   r   
run_action)r   s    r   attach_actionr      s9    8DBQBx:,&abb1CHLLLLLr   c                  
   dd l } dd l}t          dt                    }|                    ddt
          j                   |                    ddd	d
           |                    ddd	d           |                    ddddt          dd           |                    dddd	d           |                    dddd	d           |                    ddd d	d!           |                    d"d#d$d	d%          }|                    d&d'd(dt          d)*           |                    d+d,d-d. | j	        d/ | j
                              z  d01           |                    d2d3g d4d5d67           |                    d8t          d9:           |                                }t          |j                  dk    r#t          d;           t!          j        d<           t          d=                    |j        t)          j        t           j        d                                        |j        }|j        }|j        rt          d>                    |d                              |d                                         r%t5          |d                   }t7          |          }nst9          |d                   }	|	)t;          |d?                    |d                             |	j        }	 |	                                }n#  t7          |          }Y nxY w|j         d@|_         nFt          dA           |d         !                    dB          rX|j"        sQ|j#        rC|d         $                    d          s |%                    dt           j&                   dC|_'        ndD|_'        |j'        rt          dE           |d         $                    d          s |%                    dt           j&                   t7          |          }dFdGdHd,|g}
|j(        r|
)                    d           |
|d<d<<   |*                    |          }n$t7          |          }|*                    |          }tW          |dI          5 }|,                    dJ                    |                     t          j-        ||j        |j         dD|j(        |j#        ||j.        K           d d d            n# 1 swxY w Y   |j/        rF|j0        dk    r tb          2                    dL|j0                   t!          j        |j0                   d S d S )MNr   zmprof run [options] program)r=   formatter_classr>   r?   r@   z--pythonpythonr^   znActivates extra features when the profiling executable is a Python program (currently: function timestamping.)ra   rA   rc   z
--nopythonnopythonzlDisables extra features when the profiled executable is a Python program (currently: function timestamping.)z
--intervalz-Tintervalz0.1storez-Sampling period (in seconds), defaults to 0.1ra   rb   typerA   rc   z--include-childrenz-Cinclude_childrenz=Monitors forked processes as well (sum up all process memory)z--multiprocessz-Mmultiprocessz_Monitors forked processes creating individual plots for each child (disables --python features)z--exit-codez-E	exit_codezPropagate the exit coder   z-aattach_existingz8Attach to an existing process, by process name or by pidz	--timeout-ttimeoutzctimeout in seconds for the profiling, default new process has no timeout, attach existing is 1 hour)ra   rA   r   rc   --output-or7   zmprofile_%s.datz%Y%m%d%H%M%SzFile to store results in, defaults to 'mprofile_<YYYYMMDDhhmmss>.dat' in the current directory,
(where <YYYYMMDDhhmmss> is the date-time of the program start).
This file contains the process memory consumption, in Mb (one value per line).ra   rb   rc   	--backendbackend)r|   
psutil_pss
psutil_ussposixtracemallocr|   zoCurrent supported backends: 'psutil', 'psutil_pss', 'psutil_uss', 'posix', 'tracemalloc'. Defaults to 'psutil'.)ra   choicesrb   rc   programam  Option 1: "<EXECUTABLE> <ARG1> <ARG2>..." - profile executable
Option 2: "<PYTHON_SCRIPT> <ARG1> <ARG2>..." - profile python script
Option 3: (--python flag present) "<PYTHON_EXECUTABLE> <PYTHON_SCRIPT> <ARG1> <ARG2>..." - profile python script with specified interpreter
Option 4: (--python flag present) "<PYTHON_MODULE> <ARG1> <ARG2>..." - profile python module
rf   z2A program to run must be provided. Use -h for helpr   z{1}: Sampling memory every {0}sz-attaching to existing process, using hint: {}z_
When attaching, program should be process name or pid.
Failed to find a process using hint: {}i  zrunning new processz.pyFTzrunning as a Python program...z-mmemory_profilerz--timestampazCMDLINE {0}
)procr   r   
timestampsr   r   streamr   z.Program resulted with a non-zero exit code: %s)3time
subprocessr   r   rP   rQ   rR   floatr*   strftime	localtimer   rS   r   r   r   r   r   rV   r   r   r   r   r7   r   isdigitr   rz   r   r   pidcmdliner   endswithr   r   
startswithinsert
executabler   r   r-   Popenopenwritememory_usager   r   
returncodeloggererror)r   r   rW   
attach_argr2   mprofile_outputr   pcmd_liner   
extra_argsfs               r   r   r      s\   "?QefffF
Ir~NNN

, R  S S S
:l P  Q Q Q
dUQV_fL  N N N
,d9KT``  b b b
($^L C  D D D
t+lYvwww$$Z<MVbW % Y YJ
T	'PS C  D D D

Dz 1MDM.R`RVR`RbRb4c4c cR  S S S
 )={={={ ( O  P P P 	~     D
4<ABCCC	
+
2
2s|CHQK002 2 3 3 3 mOlG )*=DDWQZPPQQQ1: 	1WQZ((A#G,,HH%gaj11D|#J  1T  1[  1[  \c  de  \f  1g  1g  h  h  hA1<<>>1'00<DL#$$$1:u%% 	#dm 	#  # qz,,X66 6NN1cn555#"; 	*23331:((22 2q#.111#G,,H 1=$XJ$ 8!!"6777%GAaCL  ))AA#G,,H  ))A	os	#	# Xq	&&x00111
QY])-)>%)%6q$,	X 	X 	X 	XX X X X X X X X X X X X X X X ~ <1LLI1<XXX s   +L   L<AS&&S*-S*rc                    	 ddl }nI# t          $ r<}t          d           t          |           t          j        d           Y d}~nd}~ww xY wd}|                                d         |                                d         z
  |z  }	|                                d         |                                d         z
  d|z  z  }
|                    |
dd|
g          }|                    |	|	|	 |	 g          }|d         dk    rd|z   }|j        /|j        d         | d         |z
  cxk    r|j        d         k    r5n n2|                    || d         z   |z
  ||d         z   d	|z   d
|           |j        0|j        d         | d         |z
  cxk    r|j        d         k    r8n dS |                    | | d         z   |z
  ||d         z   d	|z   d
           dS dS )aG  Add two brackets on the memory line plot.

    This function uses the current figure.

    Parameters
    ==========
    xloc: tuple with 2 values
        brackets location (on horizontal axis).
    yloc: tuple with 2 values
        brackets location (on vertical axis)
    xshift: float
        value to subtract to xloc.
    r   N"matplotlib is needed for plotting.r   g      4@g      @rB   rw   -   )	linewidthlabel)r   )	pylabImportErrorr   r   r   ylimxlimasarrayr   )xlocylocxshiftcolorr   optionspleheight_ratiovsizehsize	bracket_x	bracket_ys                r   add_bracketsr   %  s&      2333a LWWYYq\BGGIIaL(L8EWWYYq\BGGIIaL(R,->?E

E1a/00I

E55&5&9::I Qx3e|w|A47V3CWWWWUVWWWWW
	DG#f,i$q'.Aeq 	 	7 	7 	7|w|A47V3CWWWWUVWWWWWW

T!W$v-y47/Beq 	 	* 	* 	* 	* 	*  XW    
A2AAc                 b   i }g }g }t          t                    }d}t          | d          }|D ]}|dk    rt          d          |                    dd          \  }}	|dk    rf|	                    d          }
|                    t          |
d                              |                    t          |
d                              |d	k    r|	                    d          }
|
dd
         \  }}}}}|                    |g           }t          |          t          |          t          |          t          |          g}t          |
          dk    r*|
d
         }|                    t          |                     |                    |           |||<   q|dk    rb|	                    d          }
|
d         }||                             t          |
d                   t          |
d                   f           |dk    r|	}|
                                 |||| ||dS )a  Read an mprofile file and return its content.

    Returns
    =======
    content: dict
        Keys:

        - "mem_usage": (list) memory usage values, in MiB
        - "timestamp": (list) time instant for each memory usage value, in
            second
        - "func_timestamp": (dict) for each function, timestamps and memory
            usage upon entering and exiting.
        - 'cmd_line': (str) command-line ran for this profile.
    Nr   
zSampling time was too shortrw   r   MEMr   FUNC   rE   CHLDr   CMDLINE)	mem_usage	timestampfunc_timestampr7   r   children)r   r   r   r+   rU   r-   r   getr   r*   close)r7   func_tsr   r   r   r   r   lfieldvaluevaluesf_name	mem_startstartmem_endendrY   	to_appendstack_levelchldnums                       r   read_mprofile_filer   T  s4    GIID!!HHXsA    99:;;;wwsAuE>>[[%%FU6!9--...U6!9--....f__[[%%F5;BQBZ2FIugsVR((BuuSzz53C3CU7^^TI6{{a$Qi  [!1!1222IIi    GFOOf__[[%%FQiGW$$vay!!5#3#34    iHHGGIII"%8 h8 8 8r   Tc                    	 dd l }nI# t          $ r<}t          d           t          |           t          j        d           Y d }~nd }~ww xY wdd l}t          |           }t          |d                   dk    r<t          d                    |d                              t          j        d           |d         }	|d         }
|d         }|d	         }t          |	          dk    rV|		                                D ]A}|D ]<}|

                    |d d
                    |
                    |d
d                    =B|                    |          }|                    |
          }
|
                                }||         }|
|         }
t          |
d                   }|
|z
  }
|                                }|                                }d}d}|d uot!          |d          o|j        du }t%          j        dt%          j        |                    d                    t+          t-          t/          j        |          d         dz                                z   }d }|r5|                    |
|d          }|d                    |d                   z   }|                    |
|d||t          |          z           z   |           |r,|                    |
|
|d         z  |d         z   ddd           |                                \  }}|dz  }|dz  }t          |          dk    r|rd}t9          |                                          D ]5\  }\  }}|                    d |D                       |z
  }|                    d |D                       }d } d}!|r2|                    ||d          } d                    | d                   }!|                    ||d||dz   t          |          z           z   d                    ||!                     |r,|                    ||| d         z  | d         z   ddd            |                                }"|"|d         k    r||                                         |"f}7|                    |d         |                                d         dz   |                                d         dz
  d!d           |                    |d         |                                 d         dz   |                                 d         dz
  d!d           t          |	          dk    r|rd}#tC          |	"                                          }$|	                                D ]e\  }%}&|&D ]X}'tG          |'d d
         |'d
d          |||#t          |          z           |$|%         d"|'d         |'d         z
  z  z   |#           Y|#dz  }#f|rp|                    ||                                 d         dz   |                                 d         dz
  d!d$           |                    |
|         ||d!d$           |S )%Nr   r   r   r   ** No memory usage values have been found in the profile file.**
File path: {0}
File may be empty or invalid.
It can be deleted with "mprof rm {0}"r7   r   r   r   r   rD   )cygr   bkr   r   r   r   r   mslopeT %d / %m / %Y - start at %H:%M:%S.{0:03d}  z slope {0:.5f}+-r   r%         ?z#00e3d8)r   r   MbP?r   r   c                     g | ]
}|d          S r   r   rs   items     r   rv   zplot_file.<locals>.<listcomp>      8884tAw888r   c                     g | ]
}|d          S r   r   r  s     r   rv   zplot_file.<locals>.<listcomp>  r  r    z
child {}{}blackr   z %.3fs)r   r   r   r   colors
linestyles)$r   r   r   r   r   numpyr   r   rV   r   extendr   argsortr   maxargmaxhasattrr   r   r   r   r*   roundmathmodfpolyfitr   r   rT   itemsvlineshlinesr   function_labelskeysr   )(r7   r6   r   r   r   r   r   npmprofilerY   tmemchldr   vindglobal_startmax_memmax_mem_ind
all_colorsmem_line_colorsshow_trend_slopemem_line_label	mem_trendbottomtopcmpointidxr   datactscmem
cmem_trendchild_mem_trend_labelcmax_memfunc_numf_labelsr   exec_ts	executions(                                           r   	plot_filer<    s      2333a !(++H
8K !!Q&& 6 7=fZ 7" 7"	# 	# 	#
 	 
"	#BA
;
CJD
2ww{{iikk 	# 	#F # #2A2

1QqS6""""# **S//C


1A
))++C
c(C	#A 1;;L	LAggiiG**,,K*J9Od*bww/H/HbW]^bMb]#E#'>,#?#?A A!((U49\3J3J13MPT3T-U-U)V)VWWXN I PJJq#q))	 (*:*A*A)A,*O*OOGGAsD?533G3G+GHH   " " "  X
1Yq\>IaL0$#YWWW''))KFC
eOF5LC 4yy1}}}!*4::<<!8!8 	9 	9C$::88488899LHC::88488899DJ$&! OZZT155
(8(?(?
1(N(N% GGCtosQw#oBVBV6V&WW&--d4IJJ  L L L   dSA.A>PS[bccc xxzzH'!*$$t{{}}-x8 			'!*bggiil50"''))A,2FTRRR
		'!*bggiil50"''))A,2FTRRR 2ww{{z{"27799--((** 	 	JAw$ ` `	Yrr]IabbM,#-hZ.H#I#+A;%-1	!1L%M$NW^` ` ` ` ` MHH /
		'''))A,&		!u(< 	 	/ 	/ 	/ 			!K.&# 	 	/ 	/ 	/Or   )hovered_recthovered_textalphac                   -./01 	 dd l .nI# t          $ r<}t          d           t          |           t          j        d           Y d }~nd }~ww xY wdd l}t          |           }t          |d                   dk    r<t          d                    |d                              t          j        d           |d         }|d         }	|d         }
|d	         }t          |          dk    rV|	                                D ]A}|D ]<}|	
                    |d d
                    |

                    |d
d                    =B|                    |
          }
|                    |	          }	|	                                }|
|         }
|	|         }	|r/dt          d |	                                D                       z   0nd00fd--.fdt          0          D             }t          |	d                   }|	|z
  }	|
                                }|
                                }d}t#          j        dt#          j        |                    d                    t)          t+          t-          j        |          d         dz                                z   }.                    |	|
d||t          |          z           z   |           .                                \  }}|dz  }|dz  }.                                }|                    d           |                                11                    g            1                    d0dz   f           1                    d           t          |          dk    r|rd}t?          |                                           D ]\  }\  }}|                    d |D                       |z
  }|                    d |D                       }.                    ||d||dz   t          |          z           z   d                    |                     |                                }||d         k    r||                                         |f}Ή.!                    |d         .                                d         dz   .                                d         dz
  dd           ."                    |d         .#                                d         dz   .#                                d         dz
  dd           ./fd}./01fd } t          |          dk    r|rd}!tI          |%                                          }"i /|                                 D ]m\  }#}$|$D ]`}%|%d d
         \  }&}'|%d         }(|(dz   })|&|z  }&|'|z  }'tM          ||(                   }*tO          1|&|'|(|)|#|*!          \  }+},|#|,|+f/|&|(|'|)f<   a|!dz  }!nt          /          d"k     r-.(                                j)        *                    d#|           .(                                j)        *                    d$|            |rp."                    |.#                                d         dz   .#                                d         dz
  dd%           .!                    |	|         ||dd%           .+                    |           |S )&Nr   r   r   r   r   r7   r   r   r   r   rD   c              3   0   K   | ]}|D ]}|d          V  dS )rD   Nr   )rs   
executionsexs      r   	<genexpr>z flame_plotter.<locals>.<genexpr>;  s3      VVz:VVRRUVVVVVVVr   c                     dd| z  z  z
  S )Nr         ?r   )level
stack_sizes    r   level_to_saturationz*flame_plotter.<locals>.level_to_saturation>  s    4%<*,,,r   c                     g | ]j}t          j        j        j                            d  |          df          j        j                            d |          df          g          kS )r   r   皙?)	itertoolscycle
matplotlibr  
hsv_to_rgb)rs   rG  rI  r   s     r   rv   z!flame_plotter.<locals>.<listcomp>A  s         	M ++Q0C0CE0J0JA,NOOM ++S2E2Ee2L2La,PQQ
 	 	  r   r   r   r   r   r   r   r  TFr  c                     g | ]
}|d          S r  r   r  s     r   rv   z!flame_plotter.<locals>.<listcomp>i  r  r   c                     g | ]
}|d          S r
  r   r  s     r   rv   z!flame_plotter.<locals>.<listcomp>j  r  r   r   zchild {}r   r%   c                 l   | j         | j        }}|||                                D ]f\  }\  }}}|\  }}}	}
||cxk     r|	k     rGn "||cxk     r|
k     r6n 3t          d         |k    r d S t          d         kt          d                             t          d                    t          d                             d           t          d                             d           |t          d<   |t          d<   |                                t          d<   t          d                             d           t          d                             d           t          d                             d                                             d S ht          d         t          d                             d           t          d                             t          d                    t          d                             d                                            d t          d<   d t          d<   d S d S )	Nr=  r?  r>  r   r   r   r   r   皙?   )r   r   r   r   )	xdataydatar  FLAME_PLOTTER_VARS	set_alpha	set_colorset_linewidth	get_alphadraw)eventxr   coordr~   textrectx0y0x1y1r   
rectangless              r   mouse_motion_handlerz+flame_plotter.<locals>.mouse_motion_handlery  s
   {EK1=Q]-7-=-=-?-?  ))dD!&BB;;;;B;;;;;2;;;;B;;;;;).9TAA).9E*>:DDEWX_E`aaa*>:DD\RRR*>:HHKKK9=&~69=&~626..2B2B&w/&~6@@EEE&~6DDQGGG&~6@@NNNGGIIIFFn-9~.88FFF~.889KG9TUUU~.<<Q???GGIII15~.15~... :9r   c                    | j         | j        }}||d S                                 D ]\  }}|\  }}}}||cxk     r|k     rn ||cxk     r|k     rn ,
                                j        j        }	|	                                                     ||                               |dz              |	                                 
	                                  d S d S )Nr   )
rV  rW  r  gcfcanvastoolbarpush_currentset_xlimset_ylimr]  )r^  r_  r   r`  rB   rc  rd  re  rf  rl  r   rg  rH  timestamp_axs             r   mouse_click_handlerz*flame_plotter.<locals>.mouse_click_handler  s    {EK19	F"((** 		 		HE1"NBBA{{{{{{{{{rA{{{{{{{{{&&((/1$$&&&%%b"---%%b*q.999$$&&&					 		r   )r   d   motion_notify_eventbutton_release_eventr  ),r   r   r   r   r   r  r   r   rV   r   r  r   r  r  ranger   r  r   r   r   r*   r  r  r  r   r   gcagridtwinx
set_yticksro  rT   r  r  r  r   r  r  nextadd_timestamp_rectanglerj  rk  mpl_connectsca)2r7   r6   r   r   r   r   r  r   rY   r!  r"  r#  r   r$  r%  r  r&  r'  r(  r*  r,  r.  r/  axr0  r1  r   r2  r3  r4  r7  rh  rq  r8  r9  r   r:  r;  rc  re  rd  rf  r   rb  ra  rI  r   rg  rH  rp  s2                                                @@@@@r   flame_plotterr    s^      2333a !(++H
8K !!Q&& 6 7=fZ 7" 7"	# 	# 	#
 	 
"	#BA
;
CJD
2ww{{iikk 	# 	#F # #2A2

1QqS6""""# **S//C


1A
))++C
c(C	#A	 VVRYY[[VVVVVV


- - - - -     j))	  F 1;;L	LAggiiG**,,K :O]#E#'>,#?#?A A!((U49\3J3J13MPT3T-U-U)V)VWWXN GGAsC/%#o2F2F*FGG   " " " ''))KFC
eOF5LC	BGGDMMM88::LB1j1n-...e 4yy1}}}!*4::<<!8!8 	9 	9C$::88488899LHC::88488899D GGCtA_AUAU7U'VV%,,T22  4 4 4 xxzzH'!*$$t{{}}-x8 			'!*bggiil50"''))A,2FTRRR
		'!*bggiil50"''))A,2FTRRR6 6 6 6 6 6>       " 2ww{{z{"27799--
((** 	 	JAw$ ? ?	"2A2Bq\!Vl"l"VBZ((4 BA  
d
 124
BB+,,MHH z??S  FFHHO''(=?STTT
##$:<OPPP /
		'''))A,&		!u(< 	 	/ 	/ 	/ 			!K.&# 	 	/ 	/ 	/ FF2JJJOs    
A2AAnonec                 z    |                      ||f|||dd          }|                     |||ddd          }||fS )Nr  r   )r   r?  r   leftr/  rS  )horizontalalignmentverticalalignmentr   )fill_betweenxra  )	r~  rc  re  rd  rf  	func_namer   rb  ra  s	            r   r{  r{    sZ    RHb"EPQRRD772r9"   D
 :r   c                 2   i fd} || d           	 fdD             }|D ]0}|         d         }|         d         dz   }|=  |||           1t          |          dk    rnVt          d                                 D                       }|S )	Nc                     | D ]g}d                     |                    d          | d                    }                    |g |d          }|d                             |           hd S )N.)	functionsrG  r  )ry   rU   
setdefaultr-   )function_namesrG  fnr   label_statestates        r   set_state_forz&function_labels.<locals>.set_state_for  s      	0 	0BHHRXXc]]E677344E**5<A3C 3C D DK$++B////		0 	0r   r   Tc                 R    g | ]#}t          |         d                    dk    !|$S )r  r   )r   )rs   r   r  s     r   rv   z#function_labels.<locals>.<listcomp>  s5    [[[eE%L<U8V8VYZ8Z8ZE8Z8Z8Zr   r  rG  r   c              3   <   K   | ]\  }}|d          d         |fV  dS )r  r   Nr   )rs   r   r  s      r   rD  z"function_labels.<locals>.<genexpr>  s6      eeASK03e<eeeeeer   )r   dictr  )dotted_function_namesr  ambiguous_labelsambiguous_labelr  	new_levelfn_to_labelr  s          @r   r  r    s    E0 0 0 0 0 M'+++[[[[u[[[/ 	5 	5O"?3K@No.w7!;Io&M.)4444  A%% eeW\WbWbWdWdeeeeeKr   c            	      >   d } d}t          d|          }|                    ddt          j                   |                    dd	d
d t          dd           |                    ddddd           |                    ddd           |                    ddd| d           |                    ddddd            |                    d!d"d#dd$           |                    d%d&           |                    d'd(d)*           |                                }	 |j        d+d l}|                    |j                   d+d l	}nI# t          $ r<}t          d,           t          |           t          j        d-           Y d }~nd }~ww xY w|                                 t          |          }|                    d.d/0          }|j        s|                    g d1          }	n|                    g d2          }	|j        ,|                    |j        d+         |j        d-                    t)          |          d-k    s|j        rd3}
nd4}
t,          }|j        rt.          }t1          |          D ]\  }} ||||
|5          }|                    d6           |                    d7           |j        /t)          |          d-k    r|                    |d8                    n!|j        |                    |j                   |j        sR|	                    d9d:;          }|                                                    d<           |                                 |j         r|!                    |j                    d S |"                                 d S )=Nc                     	 d |                      d          D             }n#  t          d| z            xY wt          |          dk    rt          d| z            |S )Nc                 ,    g | ]}t          |          S r   )r   )rs   r_  s     r   rv   z2plot_action.<locals>.xlim_type.<locals>.<listcomp>  s    ;;;Qa;;;r   ,z;'%s' option must contain two numbers separated with a commar   )rU   r   r   )r   newvalues     r   	xlim_typezplot_action.<locals>.xlim_type  ss    	g;;%++c*:*:;;;HH	g ]`e efffx==A ]`e efffs   " 6zPlots using matplotlib the data file `file.dat` generated
using `mprof run`. If no .dat file is given, it will take the most recent
such file in the current directory.zmprof plot [options] [file.dat]r=   descriptionr>   r?   r@   z--titler   titler   zString shown as plot titler   z--no-function-tsz-nno_timestampsr^   z+Do not display function timestamps on plot.r   r   r   z+Save plot to file instead of displaying it.)rc   z--windowz-wr   zXPlot a time-subset of the data. E.g. to plot between 0 and 20.5 seconds: --window 0,20.5)ra   r   rc   z--flamez-f
flame_modezDPlot the timestamps as a flame-graph instead of the default bracketsz--slopez-sr   z)Plot a trend line and its numerical sloper   z%Specify the Matplotlib backend to user3   re   profiles made by mprof runrf   r   r   r   )rI   rE   Z   )figsizedpi)rK  rK  g333333?rF  )rK  rK  rT  rT  FT)r6   r   r   ztime (in seconds)zmemory used (in MiB)r   zcenter left)r   r  )locbbox_to_anchorr  )#r   rP   rQ   rR   strrS   r   rN  user   r   r   r   r   ioffget_profilesfigurer  add_axesr   r   r  r<  r  rT   xlabelylabelr  legend	get_framerY  rw  outputsavefigshow)r  descrW   r2   rN  r   r   r4   figr~  r   plotterrX   r7   r   legs                   r   plot_actionr    s,     'D "CQUVVVF
Ir~NNN
	4gt 9  ; ; ; *D|J  L L L

DJ  L L L

DvIw  y y y
	4l<c  e e e
	4glH  J J J
B  D D D

#9  ; ; ;D	<#NN4<(((   2333a GGIIIT""I
))G)
,
,C? 0\\///00\\...//y
	!dil+++
9~~T/


G   ++ S S8781TRRRII!"""II$%%%zc)nn11
*%&&&&:!HHTZ    ? iiM(iCC!!#&&&
			{ 


4;
					s   )E 
F2F		Fc                 <   || d         S || d         vrt          t          |          dz             | d         |         }g }t          | d         | d                   D ];\  }}|D ]3}|d         |cxk    r|d         k    rn |                    |           4<|S )Nr   r   z was not found.r   r   r   )r+   r  zipr-   )proffunctime_rangesfiltered_memorymibrY   rngs          r   %filter_mprofile_mem_usage_by_functionr  I  s    |K  4()))T%66777'(.KO
 tK(${*;<< , ,R 	, 	,C1v%%%%s1v%%%%%&&s+++	, r   c            	         d} t          d|           }|                    ddd           |                    dd	d d
           |                                }t          |          }|D ]}t	          |          }	 t          ||j                  }n8# t          $ r+ t          d	                    |d                              Y \w xY wt          d	                    |d         t          |                               |d                                         D ]A\  }}t          d |D                       }	t          d	                    ||	                     Bd S )NzPrints the peak memory used in data file `file.dat` generated
using `mprof run`. If no .dat file is given, it will take the most recent
such file in the current directory.zmprof peak [options] [file.dat]r  r3   re   r  rf   z--funcr  zBShow the peak for this function. Does not support child processes.r   z
{}	NaN MiBr7   z{}	{:.3f} MiBr   c                     g | ]
}|d          S r
  r   )rs   mem_tss     r   rv   zpeak_action.<locals>.<listcomp>s  s    ???Vvay???r   z  Child {}			{:.3f} MiB)r   rP   rS   r  r   r  r  r+   r   rV   r  r  )
r  rW   r2   r4   r7   r  r   childr   
child_peaks
             r   peak_actionr  ]  s   'D "CQUVVVF

#5  7 7 7
vte  g g gDT""I J J!(++	=dDINNII 	 	 	-&&tJ'788999H	 	%%d:&6IGGHHH!*-3355 	J 	JME6??v???@@J.55eZHHIIII	JJ Js   <B2CCc                    t          j         d          }|                                 t          | j                  dk    rOt          |          dk    r#t	          d           t          j        d           t	          d           |d         g}ng }| j        D ]}t          j        |          r||vr|	                    |           0	 t          |          }||         |vr|	                    ||                    f# t          $ r t	          d|z              Y w xY wt          |          s#t	          d           t          j        d           |S )Nr#   r   zhNo input file found. 
This program looks for mprofile_*.dat files, generated by the 'mprof run' command.rC   zUsing last profile data.zInput file not found: z No files found from given input.)r'   r(   r   r3   r   r   r   r   existsr-   r*   r+   )r2   r3   r4   r  rX   s        r   r  r  w  sl   y677HMMOOO
4=Qx==A ) * * * HRLLL()))b\N			M 
	; 
	;Dz$ 	;y(($$T***;D		A#A;)33!((!555! ; ; ;2T9:::::;y>> 0111s   
4C??DDc                  l   t          j        d          } t          t          j                  D ]<\  }}|                     |          r"t          j                            |d            n=t          t          t          t          t          t          t          d} |t                                            d S )Nz-[0-9]+r%   )r
   r   r   r	   r   r   r   )recompilerT   r   r   matchr   rl   rn   rZ   r   r   r  r  r!   )negintrX   r5   actionss       r   mainr    s     Z	""FCH%%  3<< 	HOOAt$$$E	 $" &""$ $G GJLLr   __main__)r   r   NN)r   TTN)r  )4r'   ri   os.pathpathr   r   r  r)   r   r  loggingrL  astr   collectionsr   argparser   r   r   r   	importlibr   rQ   r   r   	getLogger__name__r   basicConfigr   r!   r:   rZ   rl   rn   rz   r   r   r   r   r   r<  rX  r  r{  r  r  r  r  r  r  r   r   r   <module>r     s    				       



 				               # # # # # # S S S S S S S S S S S S        F 
	8	$	$       	 	 	7 7 7tD D D      2     (      
a a aH#* #* #* #*^:8 :8 :8z{ { { {@   u u u up     6T T Tl  (J J J4  >  " zDFFFFF r   