
    ni              
          S r \" 5       R                  5       rSrSrSSKJr  SSKJ	r	  SSK
JrJr  SSKJr  SSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKr\R6                  S	:X  a  S
rOSSKJr  SSKr SSKJ r J!r!   SSK$J%r%J&r&J'r'  \)" S5      r* SSK+r+Sr, " S S\(5      r-S[S jr.S\S jr/ " S S\ 5      r0   S]S jr1S r2 " S S\(5      r3 " S S5      r4 " S S \55      r6 " S! S"\(5      r7S^S$ jr8S% r9\' " S& S'\%5      5       r:S( r;S_S* jr<S`S+ jr=/ 4S, jr>/ 4S- jr? " S. S/\(5      r@\AS0:X  Ga  SS1KBJCrCJDrD  \C" \S29rE\ER                  S3S4\S59  \ER                  S6S7S8\)S9S:S;9  \ER                  S<S=\GS9S>S?S@9  \ER                  SASB\HS9SSCS@9  \ER                  SDSESSFSGSH9  \ER                  SISJSSFSKSH9  \ER                  SLSM\HS9/ SNQS)SOSP9  \ER                  SQ\DSRSS9  \ER                  5       rJ\K" \JR                  5      S:X  a  \M" ST5        \R                  " S#5        \JR                  S   rO\JR                  S#S rP\=" \JR                  5      rR\JR                  (       a  \4" \R\JR                  SU9rUO\7" \JR                  \RSV9rU \JR                  S   R                  SW5      (       a+  \2" \JR                  S   5      rX\>" \X\U\JR                  \P5        O\?" \O\U\JR                  \P5        \JR                  b  \Z" \JR                  SX5      r[O\R                  r[\JR                  (       a  \URq                  \[SY9  g\8" \U\JR                  \[SZ9  gg! \" a    SSK#J r J!r!   GNf = f! \" a    \(r%S r&S r' GNf = f! \" a    Sr, GNf = f! \JR                  b  \Z" \JR                  SX5      r[O\R                  r[\JR                  (       a  \URq                  \[SY9  f \8" \U\JR                  \[SZ9  f = f)az,Profile the memory usage of a Python programz0.61.0z(python -m memory_profiler script_file.py    )iscoroutinefunction)contextmanager)partialwraps)	coroutineNwin32)SIGKILL)ProcessPipe)Magicsline_cell_magicmagics_classc                     U $ N )funcs    I/home/james-whalen/.local/lib/python3.13/site-packages/memory_profiler.py<lambda>r   /   s    4    c                     U $ r   r   )clss    r   r   r   0   s    sr   i   TFc                   *    \ rS rSrSrS rS rS rSrg)MemitResult>   zAmemit magic run details.

Object based on IPython's TimeitResult
c                 L    Xl         X l        X0l        X@l        XPl        X`l        g r   )	mem_usagebaselinerepeattimeoutintervalinclude_children)selfr   r   r   r    r!   r"   s          r   __init__MemitResult.__init__D   s!    "   0r   c                 T    [        U R                  5      nXR                  -
  nSX4-  $ )Nz,peak memory: %.02f MiB, increment: %.02f MiB)maxr   r   )r#   max_memincs      r   __str__MemitResult.__str__M   s)    dnn%%=NNr   c                 H    [        U 5      nUR                  SU-   S-   5        g )Nz<MemitResult : >)strtext)r#   pcyclemsgs       r   _repr_pretty_MemitResult._repr_pretty_R   s"    $i	!C'$./r   )r   r"   r!   r   r   r    N)	__name__
__module____qualname____firstlineno____doc__r$   r*   r3   __static_attributes__r   r   r   r   r   >   s    
1O
0r   r   c              #   b  #    [        U [        5      (       a1  U S:X  a  [        R                  " 5       n [        R
                  " U 5      n U(       d  [        U S5      (       a  SOSn[        U S5      (       a  SOSn [        X5      " SS9 Hr  n[        U[        5      (       a2  [        XA5      " 5       nUR                  [        XR5      [        -  4v   MJ  UR                  [        XA5      " 5       U   [        -  4v   Mt     g	! [        R                  [        R                  4 a    Sv    g	f = f7f)
zA
Returns a generator that yields memory for all child processes.
r	   memory_infoget_memory_infochildrenget_childrenT	recursive)r   g        N)
isinstanceintosgetpidpsutilr   hasattrgetattrr.   pid_TWO_20NoSuchProcessAccessDenied)processmeminfo_attrmemory_metricchildren_attrchildmeminfos         r   _get_child_memoryrS   W   s     
 '3b=BIIK'..)(/(G(G}M^ #*':">">JNM	W4tDE---!%68ii!@7!JJJii!=!?!NQX!XXX E   &"5"56 s+   A8D/;BD  D/(D,)D/+D,,D/c                    ^ ^^^^	 T S:X  a  [         R                  " 5       m UU4S jnUU U4S jnUU U4S jm	UU U4S jnUS:X  a  Tb  TS:X  a  [        S5      eUUU	4S	 jU	4S
 jUS.nX   " 5       $ )Nr	   c                     > [        [        U4S j[        R                  " 5       R	                  S5      5      5      n U R
                  [        -  nT(       a  U[        R                  " 5       4$ U$ )Nc                 8   > [        U 5      R                  T5      $ r   )r.   
startswith)itemfilenames    r   r   7_get_memory.<locals>.tracemalloc_tool.<locals>.<lambda>|   s    D	(<(<X(Fr   rY   )nextfiltertracemalloctake_snapshot
statisticssizerJ   time)statmemrY   
timestampss     r   tracemalloc_tool%_get_memory.<locals>.tracemalloc_toolz   sW    FF&446AA*MO Pii'!		##Jr   c            	      v  > [         R                  " T5      n  [        U S5      (       a  SOSn[        X5      " 5       S   [        -  nT(       a,  U[        [        X5       VVs/ s H  u  p2UPM	     snn5      -  nT(       a  U[        R                  " 5       4$ U$ s  snnf ! [         R                   a     g f = f)Nr<   r=   r   )	rF   r   rG   rH   rJ   sumrS   ra   rL   )rM   rN   rc   rI   r"   rI   rd   s       r   ps_util_tool!_get_memory.<locals>.ps_util_tool   s    ..%	 -4G],K,K=& '0215?C3DW3[\3[ZcS3[\]]DIIK''
	 ]
 "" 		s*   A
B! #B1'B! B! B! !B87B8c           	        > [         R                  " T5      n [        US5      (       d  [        SR	                  U 5      5      eSn[        X5      " 5       n[        X05      (       d  [        SR	                  U 5      S-   5      e[        X05      [        -  nT(       a-  U[        [        XU 5       VVs/ s H  u  pTUPM	     snn5      -  nT(       a  U[        R                  " 5       4$ U$ s  snnf ! [         R                   a     g f = f)Nmemory_full_infoz$Backend `{}` requires psutil > 4.0.0z,Metric `{}` not available. For details, see:zhhttps://psutil.readthedocs.io/en/latest/index.html?highlight=memory_info#psutil.Process.memory_full_info)rF   r   rG   NotImplementedErrorformatrH   rJ   rh   rS   ra   rL   )	rO   rM   rN   rR   rc   rI   r"   rI   rd   s	         r   _ps_util_full_tool'_get_memory.<locals>._ps_util_full_tool   s     ..%	7$677)*P*W*WXe*fgg-Lg46G722)BII-X~@ @ '1G;C3DW\i3jk3jZcS3jkllDIIK''
 l "" 		s*   BC/ 1C)?'C/ 'C/ )C/ /DDc                    > T(       a  [        S5      e[        R                  " S5        [        R                  " SSS[        T5      /[        R                  S9R                  5       S   R                  S5      n  U S   R                  5       R                  S	5      n[        U S
   R                  5       U   5      S-  nT(       a  U[        R                  " 5       4$ U$ !   T(       a  S[        R                  " 5       4s $  g= f)NzMThe psutil module is required to monitor the memory usage of child processes.z5psutil module not found. memory_profiler will be slowpsvz-p)stdoutr      
s   RSS   i   r	   )rm   warningswarn
subprocessPopenr.   PIPEcommunicatesplitindexfloatra   )out	vsz_indexrc   r"   rI   rd   s      r   
posix_tool_get_memory.<locals>.posix_tool   s    %3 
 	MN c4S:&0oo!!,q227%, 		A,,V4IAy12T9CDIIK''
	499;&s   ;A!C C  Dr]   	<unknown>z:There is no access to source file of the profiled functionc                     > T " SS9$ )NpssrO   r   ro   s   r   r   _get_memory.<locals>.<lambda>       #5E#Jr   c                     > T " SS9$ )Nussr   r   r   s   r   r   r      r   r   r]   rF   
psutil_pss
psutil_ussposix)rD   rE   RuntimeError)
rI   backendrd   r"   rY   re   ri   r   toolsro   s
   ` ```    @r   _get_memoryr   u   su    
byiik&:< -[!8H
 	
 -#JJ 	"E
 >r   c                   6   ^  \ rS rSrSrSU 4S jjrS rSrU =r$ )MemTimer   z4
Fetch memory consumption from over a time interval
c                 V  > Xl         X l        X0l        SU l        X@l        XPl        SU l        UR                  SS5      U l        UR                  SS5      U l	        [        U R                   U R                  U R                  U R                  S9/U l        [        [        U ]:  " U0 UD6  g )NTrv   rd   Fr"   rd   r"   )monitor_pidr!   pipecontr   	max_usagen_measurementspoprd   r"   r   r   superr   r$   )	r#   r   r!   r   r   r   argskw	__class__s	           r   r$   MemTimer.__init__   s    & 		"&&u5 "'95 A (($,,4??)-)>)>@A 	h&33r   c                 h   U R                   R                  S5        Sn [        U R                  U R                  U R
                  U R                  S9nU R                  (       d  U R                  R                  U5        O%[        X R                  S   5      U R                  S'   U =R                  S-  sl        U(       a  O'U R                   R                  U R                  5      nM  U R                   R                  U R                  5        U R                   R                  U R                  5        g )Nr   Fr   rv   )r   sendr   r   r   rd   r"   r   r   appendr'   r   pollr!   )r#   stopcur_mems      r   runMemTimer.run   s    		q!  $,,4??!%!6!69G >>%%g.$'1B$Cq!1$99>>$--0D  			t~~&		t**+r   )
r   r   r"   r!   r   r   r   r   r   rd   F)	r5   r6   r7   r8   r9   r$   r   r:   __classcell__)r   s   @r   r   r      s    4&, ,r   r   c           
      
   [        U	5      n	Ub  SnU(       d  / nOSnUb  [        [        X!-  5      5      nO([        U [        5      (       a  SnO[	        S5      nU
b  U
n[        U 5      (       a  U S0 4n [        U [        [        45      (       Ga.  [        U 5      S:X  a	  U S   S0 pnO?[        U 5      S:X  a  U S   U S   0 pnO$[        U 5      S	:X  a  U S   U S   U S   pnO[        eSn US-  n[        5       u  nn[        [        R                  " 5       UUU	UUUS
9nUR                  5         UR                  5          U" U0 UD6nUR!                  S5        UR                  5       nUR                  5       nU(       a  US   nU(       a  UU4nUR1                  SU-  5        US:  d  UU:X  d  US:  a  GOUS-  nM  [        U [2        R4                  5      (       Gai  Sn U(       d  [7        U R,                  XUS9nU(       a}  Ubz  UR9                  SR:                  " U6 5        U(       aT  [=        U R,                  5       H;  u  nnUR9                  SR;                  UU[>        R>                  " 5       5      5        M=     OjU(       a3  U/n[=        U R,                  5       H  u  nnURA                  U5        M     URA                  U5        O[C        U[7        U R,                  XS95      n[>        RD                  " U5        US-  nUS:  a  SnUb  URG                  5         Ub  US-  nUS:X  a  GOCU RI                  5       b  GO0GMf  US:X  a  SnSnUU:  Ga  US-  nU(       d  [7        X	UUS9nUbp  UR9                  SR:                  " U6 5        U(       aJ  [=        U 5       H;  u  nnUR9                  SR;                  UU[>        R>                  " 5       5      5        M=     OWU(       a)  U/n[=        U 5       H  u  nnURA                  U5        M     URA                  U5        O[C        U[7        X	US9/5      n[>        RD                  " U5        US-  S:X  a  Ub  URG                  5         UU:  a  GM  U(       a  gU$ ! ["         aw    [$        R&                  " [        R                  " 5       5      nUR)                  SS9 H(  n[        R*                  " UR,                  [.        5        M*     UR1                  S5        e f = f)a  
Return the memory usage of a process or piece of code

Parameters
----------
proc : {int, string, tuple, subprocess.Popen}, optional
    The process to monitor. Can be given by an integer/string
    representing a PID, by a Popen object or by a tuple
    representing a Python function. The tuple contains three
    values (f, args, kw) and specifies to run the function
    f(*args, **kw).
    Set to -1 (default) for current process.

interval : float, optional
    Interval at which measurements are collected.

timeout : float, optional
    Maximum amount of time (in seconds) to wait before returning.

max_usage : bool, optional
    Only return the maximum memory usage (default False)

retval : bool, optional
    For profiling python functions. Save the return value of the profiled
    function. Return value of memory_usage becomes a tuple:
    (mem_usage, retval)

timestamps : bool, optional
    if True, timestamps of memory usage measurement are collected as well.

include_children : bool, optional
    if True, sum the memory of all forked processes as well

multiprocess : bool, optional
    if True, track the memory usage of all forked processes.

stream : File
    if stream is a File opened with write access, then results are written
    to this file instead of stored in memory and returned at the end of
    the subprocess. Useful for long-running processes.
    Implies timestamps=True.

backend : str, optional
    Current supported backends: 'psutil', 'psutil_pss', 'psutil_uss', 'posix', 'tracemalloc'
    If `backend=None` the default is "psutil" which measures RSS aka "Resident Set Size". 
    For more information on "psutil_pss" (measuring PSS) and "psutil_uss" please refer to:
    https://psutil.readthedocs.io/en/latest/index.html?highlight=memory_info#psutil.Process.memory_full_info 

max_iterations : int
    Limits the number of iterations (calls to the process being monitored). Relevant
    when the process is a python function.

Returns
-------
mem_usage : list of floating-point values
    memory usage, in MiB. It's length is always < timeout / interval
    if max_usage is given, returns the two elements maximum memory and
    number of measurements effectuated
ret : return value of the profiled function
    Only returned if retval is set to True
NTr	   rv   infr   r         )rd   r   r"   r@         gư>g      $@r   zMEM {0:.6f} {1:.4f}
zCHLD {0} {1:.6f} {2:.4f}
r"   2   )%choose_backendrC   roundrB   r   callablelisttuplelen
ValueErrorr   r   rD   rE   startrecvr   	ExceptionrF   r   r>   killrI   r
   joinry   rz   r   writern   rS   ra   r   r'   sleepflushr   )procr!   r    rd   r"   multiprocessr   retvalstreamr   max_iterationsretmax_iterfr   r   current_iter
child_connparent_connr0   returnedr   parentrQ   
line_countr   idxchldmem_counters                                 r   memory_usager     s   @ W%G
uW/01	D#		 <%%H~~b"~$u&&t9>7BRARY!^7DGRRARY!^7DGT!WRARAL&*f#Jh
G$.#,*:<A GGId>b>  #!&&(!,!1!1!3a&Cx-C FF1x< "(@hQUoOHC D 
D***	+	+
'HHg%57	 !3LL!8!?!?!KL $,=dhh,GLC"LL)E)L)LSRY[_[d[d[f)gh -H $%.K	*;DHH*EJAw%,,W5 +F JJy)#%"hhTU JJx !OJB
%LLN"Aq=yy{&M R r>H qLG'j%57	 %LL!8!?!?!KL $,=d,CLC"LL)E)L)LSRY[_[d[d[f)gh -D $%.K	*;D*AJAw%,,W5 +B JJy)3&tGWX  JJx |q V%7=  > Jy  		4#__t_<EGGEIIw/ =q	s   ?AQ> >BS?c                    [         R                  R                  U 5      (       a  U $ [         R                  " S[         R                  5      R                  [         R                  5      nU HS  nU(       d  M  [         R                  R                  X 5      n[         R                  R                  U5      (       d  MQ  Us  $    [        R                  R                  SR                  U 5      5        [        S5      e)zKFind the script.

If the input is not a file, then $PATH will be searched.
PATHzCould not find script {0}
rv   )rD   pathisfilegetenvdefpathr}   pathsepr   sysstderrr   rn   
SystemExit)script_namer   folderfns       r   _find_scriptr     s    
 
ww~~k""99VRZZ(..rzz:DWW\\&.77>>"I  JJ299+FG
Q-r   c                   2    \ rS rSrSr  SS jrS rS rSrg)	_TimeStamperCMi  zTime-stamping context manager.Nc                 L    Xl         X l        X0l        X@l        XPl        X`l        g r   )rd   rY   r   tsr   r"   )r#   rd   rY   r   timestamperr   r"   s          r   r$   _TimeStamperCM.__init__  s!    $ 	 0r   c           
         U R                   be  U R                   =R                  S-  sl        U R                   R                  U R                     R	                  U R                   R                  5        U R
                  R	                  [        [        R                  " 5       U R                  SU R                  U R                  S95        g Nrv   Trd   r"   rY   )r   current_stack_levelstackr   r   rd   r   rD   rE   r   r"   rY   r#   s    r   	__enter___TimeStamperCM.__enter__  s    77GG''1,'GGMM$))$++DGG,G,GH		T\\d)-)>)>X	Yr   c           
      
   U R                   b  U R                   =R                  S-  sl        U R                  R                  [	        [
        R                  " 5       U R                  SU R                  U R                  S95        g r   )
r   r   rd   r   r   rD   rE   r   r"   rY   )r#   r   s     r   __exit___TimeStamperCM.__exit__  s\    77GG''1,'		T\\d)-)>)>X	Yr   )r   rY   r   r"   rd   r   )NNF)	r5   r6   r7   r8   r9   r$   r   r   r:   r   r   r   r   r     s    (MQ"'1YYr   r   c                   \    \ rS rSrSrSS jrSS jrSS jrS rS r	\
S	 5       rSS
 jrSrg)TimeStamperi  zWA profiler that just records start and end execution times for
any decorated function.
c                 F    0 U l         Xl        X l        SU l        0 U l        g )Nr	   )	functionsr   r"   r   r   )r#   r   r"   s      r   r$   TimeStamper.__init__  s#     0#% 
r   Nc                 N  ^ ^ Ub  [        U5      (       d  [        S5      eT R                  U5        T R                  U5      nUR                  Ul        UR
                  Ul        UR                  Ul        UR                  R                  [        US0 5      5        U$ UU 4S jnU$ )NzValue must be callable__dict__c                 $   > TR                  U TS9$ N)	precision__call__r   r  r#   s    r   inner_partial+TimeStamper.__call__.<locals>.inner_partial1      }}Q)}<<r   )
r   r   add_functionwrap_functionr6   r5   r9   r   updaterH   r#   r   r  r   r  s   ` `  r   r  TimeStamper.__call__$  s    D>> !9::d#""4(A??ALAJAIJJgdJ;<H= ! r   c                    S nSUl         Xl        U R                  U5        / nU R                  U   R	                  U5         [
        R                  " U5      n[        UUU R                  U US9$ ! [         a    Sn N%f = f)z;Returns a context manager for timestamping a block of code.c                     U $ r   r   )xs    r   r   'TimeStamper.timestamp.<locals>.<lambda>9  s    r    r   )r   r   )
r6   r5   r  r   r   inspectgetsourcefile	TypeErrorr   r   )r#   namer   rd   rY   s        r   	timestampTimeStamper.timestamp6  s     $
t##J/	#,,T2H LL
 	
  	#"H	#s   A0 0A?>A?c                 `    XR                   ;  a  / U R                   U'   / U R                  U'   g g r   )r   r   )r#   r   s     r   r  TimeStamper.add_functionM  s-    ~~%#%DNN4 !DJJt &r   c                    ^ ^ UU 4S jnU$ )z)Wrap a function to timestamp it.
        c                    >  [         R                  " T5      n[        [        R
                  " 5       TR                  STR                  US9/nTR                  T   R                  U5         TR                  " T/U Q70 UD6 nUsS S S 5        UR                  [        [        R
                  " 5       TR                  STR                  US95        $ ! [         a    Sn Nf = f! , (       d  f       O= f UR                  [        [        R
                  " 5       TR                  STR                  US95        g ! UR                  [        [        R
                  " 5       TR                  STR                  US95        f = f)Nr   Tr   )r  r  r  r   rD   rE   r   r"   r   r   call_on_stack)r   kwdsrY   rd   resultr   r#   s        r   r   $TimeStamper.wrap_function.<locals>.fV  sM   '"006 BIIK$-1-B-BXWXJ NN4 ''
3B''<t<t<! =< !!+biik4<<TX?C?T?T7?#A B  '&' =<< !!+biik4<<TX?C?T?T7?#A B
!!+biik4<<TX?C?T?T7?#A Bs6   C -D: C$	D: C! C!$
C2.D: :AE?r   r#   r   r   s   `` r   r	  TimeStamper.wrap_functionR  s    	B& r   c              /      #    U =R                   S-  sl         U R                  U   R                  U R                   5        U" U0 UD6v   U =R                   S-  sl         g 7fNrv   )r   r   r   )r#   r   r   r  s       r   r  TimeStamper.call_on_stackk  sT       A% 

4 8 89D!D!!  A% s   AA c                 6   Uc  [         R                  nU R                  R                  5        Hh  u  p#UR                  < SUR
                  < 3n[        X0R                  U   5       H*  u  pVUR                  SU4US   -   US   -   U4-   -  5        M,     Mj     g )N.zFUNC %s %.4f %.4f %.4f %.4f %d
r   rv   )	r   rt   r   itemsr6   r5   zipr   r   )r#   r   r   rd   function_namer   levels          r   show_resultsTimeStamper.show_resultst  s    >ZZF $ 4 4 6D'+FM ZZ-=>	?"$r!u,r!u4x?A B ? !7r   )r   r   r   r"   r   r   )NN)z<block>r   )r5   r6   r7   r8   r9   r$   r  r  r  r	  r   r  r+  r:   r   r   r   r   r     s:    !$
."
2 & &Br   r   c                   0    \ rS rSrS rSS jrS rS rSrg)	CodeMapi  c                 *    Xl         / U l        X l        g r   )r"   	_toplevelr   )r#   r"   r   s      r   r$   CodeMap.__init__  s     0r   Nc                 4   X;   a  g Uc  UR                   nUR                  S5      (       a  US S n[        R                  R	                  U5      (       d0  [        SU-   5        UR                  S5      (       a  [        S5        g Un[        R                  " U5      u  pE[        UU[        U5      -   5      nU R                  R                  X1U45        0 X'   OX   X'   [        [        R                  UR                  5       H  nU R!                  XrS9  M     g )N)z.pycz.pyor	   zERROR: Could not find file )zipython-inputz<ipython-inputziNOTE: %mprun can only be used on functions defined in physical files, and not in the IPython environment.)toplevel_code)co_filenameendswithrD   r   existsprintrW   r  getsourcelinesranger   r0  r   r\   iscode	co_constsadd)r#   coder3  rY   	sub_lines
start_linelinenossubcodes           r   r<  CodeMap.add  s    < ''H  !122#CR=77>>(++3h>?&&'JKKOP  M&-&<&<T&B#YJ&Y79GNN!!87";<DJ,DJgnndnn=GHHWH: >r   c                 l   [        SU R                  U R                  UR                  S9nX   R	                  US 5      nU(       a  US   OSnU(       a  US   OSnU(       a  X   R	                  US 5      OS nU(       a  US   OSn	X U   ;   a  X   U   S   S-   OSn
XtU	-
  -   [        XF5      U
4X   U'   g )Nr	   )r"   rY   rv   r   r   )r   r   r"   r4  getr'   )r#   r=  linenoprev_linenomemory
prev_valueprevious_memoryprevious_incprev_line_valueprev_line_memory	occ_counts              r   traceCodeMap.trace  s    R@U@U&*&6&68Z^^FD1
+5*Q-1(2z!}?J$*..d;PT1@?1-a17:1EDJv&q)A-1	%556(

6r   c              #   v   ^#    U R                    H$  u  pnX   mT(       d  M  U4S jU 5       nX4v   M&     g7f)z$Iterate on the toplevel code blocks.c              3   H   >#    U  H  oTR                  U5      4v   M     g 7fr   )rD  ).0linemeasuress     r   	<genexpr> CodeMap.items.<locals>.<genexpr>  s     LGDHLL$67Gs   "N)r0  )r#   rY   r=  r@  line_iteratorrT  s        @r   r'  CodeMap.items  s9     )-%XWzHLGLM++ *8s   69)r0  r   r"   r   )	r5   r6   r7   r8   r$   r<  rN  r'  r:   r   r   r   r.  r.    s    
;8
 ,r   r.  c                   z    \ rS rSrSrS rSS jrS r\S 5       r	S r
S	 rS
 rS rS rS rS rS rS rS rSrg)LineProfileri  z;A profiler that records the amount of memory for each line c                     UR                  SS5      nUR                  SS5      n[        X#S9U l        SU l        UR                  SS 5      U l        / U l        [        UR                  SS 5      5      U l        S U l        g )Nr"   Fr   rF   )r"   r   r   r(   )	rD  r.  code_mapenable_countr(   	prevlinesr   r   rF  )r#   r   r"   r   s       r   r$   LineProfiler.__init__  st    66"4e<&&H--@vvi.%bffY&=>r   Nc                   ^ ^ Ub}  T R                  U5        T R                  U5      nUR                  Ul        UR                  Ul        UR                  Ul        UR
                  R                  [        US0 5      5        U$ UU 4S jnU$ )Nr   c                 $   > TR                  U TS9$ r   r  r  s    r   r  ,LineProfiler.__call__.<locals>.inner_partial  r  r   )r  r	  r6   r5   r9   r   r
  rH   r  s   ` `  r   r  LineProfiler.__call__  su    d#""4(A??ALAJAIJJgdJ;<H= ! r   c                      UR                   nU R                  R                  U5        g! [         a    [        R
                  " SU-  5         gf = f)zIRecord line profiling information for the given Python function.
        z1Could not extract a code object for the object %rN)__code__r\  r<  AttributeErrorrw   rx   )r#   r   r=  s      r   r  LineProfiler.add_function  sL    	$==D
 MMd#	  	"MMM ! "	"s   * #AAc              #      #    U R                  5          S v   U R                  5         g ! U R                  5         f = f7fr   )enable_by_countdisable_by_countr   s    r   _count_ctxmgrLineProfiler._count_ctxmgr  s1     	$!!#D!!#s   >) >;>c                 \   ^ ^ [        T5      (       a  [        UU 4S j5       nU$ UU 4S jnU$ )z'Wrap a function to profile it.
        c               ?      >#    TR                  5          T" U 0 UD6 S h  vN nUsS S S 5        $  N! , (       d  f       g = f7fr   rk  )r   kwargsresr   r#   s      r   r   %LineProfiler.wrap_function.<locals>.f  s:     '')%)4%:6%::C *): *)s$   A202
A2
A Ac                  j   > TR                  5          T" U 0 UD6sS S S 5        $ ! , (       d  f       g = fr   ro  )r   r  r   r#   s     r   r   rr    s(    '').. *))s   $
2)r   r   r   s   `` r   r	  LineProfiler.wrap_function  s5     t$$  	/ r   c                     U R                  5          [        XU5        U R                  5         U $ ! U R                  5         f = f)zGProfile a single executable statement in the given namespaces.
        )ri  execrj  )r#   cmdglobalslocalss       r   runctxLineProfiler.runctx  s@     		$v&!!# !!#s	   0 Ac                 n    U R                   S:X  a  U R                  5         U =R                   S-  sl         g)z>Enable the profiler if it hasn't been enabled before.
        r   rv   N)r]  enabler   s    r   ri  LineProfiler.enable_by_count  s,     !KKMQr   c                     U R                   S:  a7  U =R                   S-  sl         U R                   S:X  a  U R                  5         ggg)z^Disable the profiler if the number of disable requests matches the
number of enable requests.
r   rv   N)r]  disabler   s    r   rj  LineProfiler.disable_by_count  sD     q "  A% & !r   c                 t   UR                   U R                  ;   a  US:X  a&  U R                  R                  UR                  5        OUS:X  al  U R                  R                  UR                   U R                  S   U R                  5        U R                  S   U l        UR                  U R                  S'   OVUS:X  aP  U R                  R                  5       nU R                  R                  UR                   X@R                  5        X@l        U R                  b  U R                  XU5        U R                  $ )zCallback for sys.settracecallrS  r	   return)
f_coder\  r^  r   f_linenorN  rF  r   _original_trace_functiontrace_memory_usage)r#   frameeventargrE  s        r   r  LineProfiler.trace_memory_usage  s    <<4==(%%enn5&##ELL$..2DdFVFVW#'>>"#5 %*^^r"("++-##ELL&:J:JK#) ((4))%<&&&r   c                    US;   Ga  UR                   U R                  ;   a  [        SU R                  UR                   R                  S9nX@R
                  :  a  SR                  X@R
                  5      n[        R                  R                  U5        [        R                  R                  S5        U=R                  S-  sl
        [        R                  " 5       nSUl        Xl        S Ul        UR                  S-
  Ul        S Ul        UR$                  $ U R&                  b  U R'                  XU5        U R(                  $ )	N)rS  r  r	   )rY   z?Current memory {0:.2f} MiB exceeded the maximum of {1:.2f} MiB
zStepping into the debugger 
r   Fr   )r  r\  r   r   r4  r(   rn   r   rt   r   r  pdbPdbquitting	stopframereturnframe
stoplinenobotframetrace_dispatchr  trace_max_mem)r#   r  r  r  ctr0   s          r   r  LineProfiler.trace_max_mem-  s    &&5<<4==+HBu||7O7OPALL 006q,,0G 

  #

  !@A!#GGI"
# $$~~1!
'''((4**E#>!!!r   c                 $    U R                  5         g r   )ri  r   s    r   r   LineProfiler.__enter__D  s    r   c                 $    U R                  5         g r   )rj  )r#   exc_typeexc_valexc_tbs       r   r   LineProfiler.__exit__G  s    r   c                     [         R                  " 5       U l        U R                  b!  [         R                  " U R
                  5        g [         R                  " U R                  5        g r   )r   gettracer  r(   settracer  r  r   s    r   r}  LineProfiler.enableJ  s>    (+%<<#LL++,LL001r   c                 D    [         R                  " U R                  5        g r   )r   r  r  r   s    r   r  LineProfiler.disableQ  s    T223r   )r  r   r\  r]  r(   rF  r^  r#  )r5   r6   r7   r8   r9   r$   r  r  r   rk  r	  rz  ri  rj  r  r  r   r   r}  r  r:   r   r   r   rZ  rZ    sZ    F	 !
$ $ $"',". 24r   rZ  rv   c                    Uc  [         R                  nSnU R                  R                  5        GH  u  pEUR	                  SSSSS5      nUR                  SU-   S-   5        UR                  US	-   5        UR                  S
[        U5      -  S	-   5        [        R                  " U5      nSR	                  US-   U5      nSU-   S-   n	U Hm  u  pU(       a2  US   nUS   nU	R	                  U5      nUS   nU	R	                  U5      nOSnSnSnUR	                  XXXzS-
     5      nUR                  U5        Mo     UR                  S5        GM      g )Nz'{0:>6} {1:>12} {2:>12}  {3:>10}   {4:<}zLine #z	Mem usage	IncrementOccurrencesLine Contentsz
Filename: z


=z{0}.{1}fr   z{0:z} MiBr   rv   r   r  )	r   rt   r\  r'  rn   r   r   	linecachegetlines)profr   r  templaterY   linesheader	all_linesfloat_formattemplate_memrE  rc   r)   	total_memoccurrencestmps                   r   r+  r+  U  sM   ~8H!]]002;]!02 	]X-67Ve^$TCK'$./&&x0	")))a-C,w6"MV!fF	(//	:	!!f"))#.	!//&SyZ[Q[G\]CLL # 	W3 3r   c                     [        X5        g r   )rv  )stmtnss     r   
_func_execr  v  s     	Nr   c                   L    \ rS rSr\SS j5       r\SS j5       r\S 5       rSr	g)MemoryProfilerMagicsi|  Nc           
         SSK Jn  SSKJnJn  SSKJn  SSKnU" UR                  5      nUS:  a  SSK	J
n	  SSKJn
  SS	KJn  OSSKJ
n	  SSKJn
  SS	KJn  U
" S
// S9nUR%                  SS5      R%                  SS5      nU R'                  USSS9u  pUR)                  U5        U R*                  R,                  nU R*                  R.                  nUb  USU-   -  n/ nUR0                   H   n UR3                  [5        UUU5      5        M"     SU;   nU" US9nU H  nU" U5        M     S[<        R>                  ;   a  Sn[<        R>                  S   nOSnSnU[<        R>                  S'    URA                  XU5        S
nU(       a  U[<        R>                  S'   U" 5       nU" UU5        URG                  5       nURI                  5       nUS:  a&  U	" UU R*                  RJ                  RL                  S9  OU	" U5        [O        U5        URP                  S   nU(       a9  [S        US5       nURU                  U5        SSS5        [O        SU< S U< 35        SnS!U;   a  UnU$ ! [6         a-  nU" SU< SUR8                  R:                  < SU< 35      eSnAff = f! [B         a    Sn GN-[D         a    Sn GN;f = f! U(       a  U[<        R>                  S'   f f = f! , (       d  f       N= f)"a	  Execute a statement under the line-by-line memory profiler from the
memory_profiler module.

Usage, in line mode:
  %mprun -f func1 -f func2 <statement>

Usage, in cell mode:
  %%mprun -f func1 -f func2 [statement]
  code...
  code...

In cell mode, the additional code lines are appended to the (possibly
empty) statement in the first line. Cell mode allows you to easily
profile multiline blocks without having to put them in a separate
function.

The given statement (which doesn't require quote marks) is run via the
LineProfiler. Profiling is enabled for the functions specified by the -f
options. The statistics will be shown side-by-side with the code through
the pager once the statement has completed.

Options:

-f <function>: LineProfiler only profiles functions and methods it is told
to profile.  This option tells the profiler about these functions. Multiple
-f options may be used. The argument may be any expression that gives
a Python function or method object. However, one must be careful to avoid
spaces that may confuse the option parser. Additionally, functions defined
in the interpreter at the In[] prompt or via %run currently cannot be
displayed.  Write these functions out to a separate file and import them.

One or more -f options are required to get any useful results.

-T <filename>: dump the text-formatted statistics with the code
side-by-side out to a text file.

-r: return the LineProfiler object after it has completed profiling.

-c: If present, add the memory usage of any children process to the report.
r   )StringIO)r+  rZ  LooseVersionNz0.11)page)Struct)
UsageErrorr  )Tr   "z\"'z\'zrf:T:cT)list_allr  zCould not find function z.
z: r  r   profileFz7*** SystemExit exception caught in code being profiled.z>*** KeyboardInterrupt exception caught in code being profiled.)screen_lineswz)
*** Profile printout saved to text file z. r)+ior  memory_profilerr+  rZ  distutils.versionr  IPython__version__IPython.genutilsr  IPython.ipstructr  IPython.ipapir  IPython.core.pageIPython.utils.ipstructIPython.core.errorreplaceparse_optionsmergeshelluser_global_nsuser_nsr   r   evalr   r   r5   builtinsr   rz  r   KeyboardInterruptgetvaluerstriprcscreen_lengthr7  r  openr   )r#   parameter_scellr  r+  rZ  r  r  ipython_versionr  r  r  opts_defoptsarg_str	global_nslocal_nsfuncsr  er"   r  r   had_profileold_profilemessagestdout_trapoutput	text_filepfilereturn_values                                  r   mprunMemoryProfilerMagics.mprun  s   T 	 > 	3&w':':;V#-/0.55 RDB'!))#u5==c5I**;48 + :

8JJ--	::%%td{"G FFDNT$	8<=  $;0@ADDM  )))K"++I6KKK'.)$
	;NN7x8G /:!!), jWk*%%'V#djjmm&A&ABLgFF1I	i%F# &  $;"Lo  N $JK++J^J^JK"M N NN,  	POG  	$#G	$ /:!!), " &%sT   -I#+J *K#
J-(JJJ;)J> ,J;7J> :J;;J> >K
K,c           	         SSK JnJn  U R                  USSSS9u  pVUc  SnOUnUn[	        [        USS	5      5      nUS	:  a  US	:H    [	        [        US
S5      5      n	U	S::  a  Sn	[        [        USS5      5      n
SU;   nSU;   nSU;   nSSKnUR                  5         U" XpR                  R                  5        / nSnU" 5       S   nUU:  a?  US	-  nU" XFU R                  R                  44XSS	US9nUR                  U5        UU:  a  M?  [        UUXU
U5      nU(       d  U(       a  [        U5        O[        S5        U(       a  U$ g)a(  Measure memory usage of a Python statement

Usage, in line mode:
  %memit [-r<R>t<T>i<I>] statement

Usage, in cell mode:
  %%memit [-r<R>t<T>i<I>] setup_code
  code...
  code...

This function can be used both as a line and cell magic:

- In line mode you can measure a single-line statement (though multiple
  ones can be chained with using semicolons).

- In cell mode, the statement in the first line is used as setup code
  (executed but not measured) and the body of the cell is measured.
  The cell body has access to any variables created in the setup code.

Options:
-r<R>: repeat the loop iteration <R> times and take the best result.
Default: 1

-t<T>: timeout after <T> seconds. Default: None

-i<I>: Get time information at an interval of I times per second.
    Defaults to 0.1 so that there is ten measurements per second.

-c: If present, add the memory usage of any children process to the report.

-o: If present, return a object containing memit run details

-q: If present, be quiet and do not output a result.

Examples
--------
::

  In [1]: %memit range(10000)
  peak memory: 21.42 MiB, increment: 0.41 MiB

  In [2]: %memit range(1000000)
  peak memory: 52.10 MiB, increment: 31.08 MiB

  In [3]: %%memit l=range(1000000)
     ...: len(l)
     ...:
  peak memory: 52.14 MiB, increment: 0.08 MiB

r   )r   r  z	r:t:i:coqF)r   strictNpassr  rv   r  i皙?r  oqT)r    r!   r   r   r"   zPERROR: could not read memory usage, try with a lower interval or more iterations)r  r   r  r  rC   rH   r   gccollectr  r  r   r   r7  )r#   rS  r  r   r  r  r  setupr   r    r!   r"   return_resultquietr  r   r   r   r  r  s                       r   memitMemoryProfilerMagics.memit  sz   h 	=''k/4 ( 6
 <EEDWT3*+A:aKgdC+,a<GsC01$;tt 	


5**,,-	>!$qLG
4::3E3E,FG'.)-a0@BC S!  Y&8-/ f : ; M r   c                 2   SSK Jn  SS KnU" UR                  5      nUS:  aH   UR                  nU" SU R                  R                  5        U" SU R                  R                  5        g UR                  U 5        g ! [
         a    UR                  n Nef = f)Nr   r  z0.13r  r  )r  r  r  r  define_magicrf  expose_magicr  __func__r  register_magics)r   ipr  r  r  _register_magics         r   r  $MemoryProfilerMagics.register_magicsl  s    2&w':':;V#2"$// GSYY%7%78GSYY%7%78s# " 2"$//2s   A= =BBr   )r  N)
r5   r6   r7   r8   r   r  r  classmethodr  r:   r   r   r   r  r  |  sD     A AH e eN $ $r   r  c                 .    [         R                  U 5        g)z:This is called to load the module as an IPython extension.N)r  r  )r  s    r   load_ipython_extensionr    s     ((,r   rF   c                   ^ ^^^^^ [        T5      mTS:X  a:  [        (       a/  [        R                  " 5       (       d  [        R                  " 5         T bb  [        [        TS9m[        [        TTS9m[        T 5      (       a  [        T S9[        U UU4S j5       5       nU$ [        T S9U UU4S j5       nU$ UUU4S jnU$ )zG
Decorator that will run the function and print a line-by-line profile
r]   )r   )r   r  )wrappedc               ?   ^   >#    T" 5       nU" T5      " U 0 UD6 S h  vN nT" U5        U$  N7fr   r   r   rp  r  valr   get_profshow_results_bounds       r   wrapperprofile.<locals>.wrapper  s7       z!%dT!<V!<<"4(
 =s   -+-c                  B   > T" 5       nU" T5      " U 0 UD6nT" U5        U$ r   r   r  s       r   r  r    s*    z4j$1&1"4(
r   c                    > [        U TTTS9$ )N)r   r  r   r  )r   r   r  r   s    r   inner_wrapperprofile.<locals>.inner_wrapper  s    1Vy#*, ,r   )r   has_tracemallocr]   
is_tracingr   r   rZ  r+  r   r   r   )r   r   r  r   r  r   r  r  s   ````  @@r   r  r    s     W%G-OO%%''<9$9
 t$$4   !  4  ! 	, r   c                 R   SnSSSS[         R                  S:H  4S[        4/n[        S [	        U5       5       5      nU b#  UR                  SUR                  X0   5      5        U H  u  pEU(       d  M  Un  O   X:w  a(  U b%  [        R                  " S	R                  X5      5        U$ )
zj
Function that tries to setup backend, chosen by user, and if failed,
setup one of the allowable backends

no_backend)rF   T)r   T)r   Tr   r]   c              3   4   #    U  H  u  pUS    U4v   M     g7f)r   Nr   )rR  r  bs      r   rU  !choose_backend.<locals>.<genexpr>  s     J2I$!QqT1I2Is   r   z%{0} can not be used, {1} used instead)
rD   r  r"  dict	enumerateinsertr   rw   rx   rn   )new_backend_backendall_backendsbackends_indices	n_backendis_availables         r   r   r     s     H	"''W$%	(L J)L2IJJA|//0@0MNO#/	< H $0 ;#:=DD# 	$Or   c                    SSK Jn  U[        R                  S'   [	        [
        UU S9n[        R                  R                  S[        R                  R                  [        5      5        [        U5      nU /U-   [        l         US:X  a   [        (       a  [        R                   " 5         ["        R$                  " U SS9 n['        [)        UR+                  5       U S5      XU5        S S S 5        [        (       a1  [        R,                  " 5       (       a  [        R.                  " 5         g g g ! , (       d  f       NK= f! [        (       a1  [        R,                  " 5       (       a  [        R.                  " 5         f f f = f)	Nr   
run_moduler  )r  __file__r]   zutf-8)encodingrv  )runpyr4  r  r   r)  _CLEAN_GLOBALSr   r   r+  rD   dirnamescript_filenamer   argvr"  r]   r   r  r  rv  compilereadr#  r   )rY   profilerr   passed_argsr4  r  r-  r   s           r   exec_with_profilerr@    s    #+Hi 	n  	
!B HHOOArww78g&HzK'CH}$WWX0A8V4b= 1 ?{5577  8? 10 ?{5577  8?s$   ;D<  &D+&D< +
D95D< <>E:c                    SSK Jn  U[        R                  S'   [	        [
        US9n[        U5      nU /U-   [        l        US:X  a   [        (       a  [        R                  " 5          U" U SUS9  [        (       a1  [        R                  " 5       (       a  [        R                  " 5         g g g ! [        (       a1  [        R                  " 5       (       a  [        R                  " 5         f f f = f)Nr   r3  r  r  r]   __main__)run_nameinit_globals)r7  r4  r  r   r)  r8  r   r   r;  r"  r]   r   r#  r   )moduler>  r   r?  r4  r  r-  s          r   run_module_with_profilerrF    s     #+Hi 	nh	/Bg&Hx+%CH= __6JR@?{5577  8???{5577  8?s   )B. .>C,c                   H    \ rS rSrSrSS jr\R                  4S jrS r	Sr
g)	LogFilei  z]File-like object to log text using the `logging` module and the log
report can be customised.Nc                 F    [         R                  " U5      U l        X l        g)z
:param name: name of the logger module
       reportIncrementFlag: This must be set to True if only the steps
       with memory increments are to be reported

:type self: object
      name: string
      reportIncrementFlag: bool
N)logging	getLoggerloggerreportIncrementFlag)r#   r  rM  s      r   r$   LogFile.__init__  s     ''-#6 r   c                    U R                   (       a  SU;   aK  [        UR                  S5      S   R                  5       5      S:  a  U R                  R                  X!5        g UR                  S5      (       d  UR                  S5      (       a  U R                  R                  X!5        g g U R                  R                  X!5        g )NMiBrv   r   z	Filename:r  )rM  r   r}   striprL  log__contains__)r#   r2   r*  s      r   r   LogFile.write
  s    ##|cii&6q&9&?&?&A BQ F+!!+..#2B2B#3% 3%+3% KKOOE'r   c                 ^    U R                   R                   H  nUR                  5         M     g r   )rL  handlersr   )r#   handlers     r   r   LogFile.flush  s    {{++GMMO ,r   )rL  rM  )NF)r5   r6   r7   r8   r9   r$   rJ  INFOr   r   r:   r   r   r   rH  rH    s    !7  '|| (r   rH  rB  )ArgumentParser	REMAINDER)usagez	--versionversion)actionr]  z
--pdb-mmemr(   MAXMEMstorez1step into the debugger when memory exceeds MAXMEM)destmetavartyper^  helpz--precisionr  r   z:precision of memory output in number of significant digits)ra  rc  r^  defaultrd  z-oout_filenamez,path to a file where results will be writtenz--timestampr  
store_truezMprint timestamp instead of memory measurement for
        decorated functions)ra  re  r^  rd  z--include-childrenr"   z+also include memory used by child processesz	--backendr   r   znbackend using for getting memory info (one of the {tracemalloc, psutil, posix, psutil_pss, psutil_uss, posix}))ra  rc  r^  choicesre  rd  programzApython script or module followed by command line arguments to run)nargsrd  z2A program to run must be provided. Use -h for helpr   )r(   r   z.pya)r   )r  r   )Nr   )FFN)r	   r  NFFFFFNNNr#  )NNrv   rF   r   )^r9   rx  copyr8  r  
_CMD_USAGEasyncior   
contextlibr   	functoolsr   r   typesr   r  r  r  rJ  rD   r  r  ry   r   ra   	tracebackrw   platformr
   signalrF   multiprocessingr   r   ImportErrormultiprocessing.dummyIPython.core.magicr   r   r   objectr   rJ   r]   r"  r   rS   r   r   r   r   r   r   r)  r.  rZ  r+  r  r  r  r  r   r@  rF  rH  r5   argparserZ  r[  parseradd_argumentrC   r.   
parse_argsr   r   ri  r7  exittargetscript_argsr   r-  r  r"   r  r(   r5  r:  rf  r  out_filert   r  r   r   r   <module>r     sa   2 !7
 ' % $      	 	 
  
   <<7 G 4-#HH .O
0& 02<hV*,w *,Z AFGLIMSt&YV Y<dB dBN9,d 9,xW46 W4tB ~$6 ~$ ~$P-#LB AC 0 EG f @ z2*-F
I{K
9h7@  B KcI  K >;  = K    ,3El:  < )#gNX`X  Y 	P  RD
4<<ABC\\!_F,,qr"Kdll+H~~8d6K6KLDLL(CJ<<?##E***4<<?;OdllKP$VT4<<M(D--s3HzzH>>X.Iu e'  4334
  #F'O"L	#  Ob( (D--s3HzzH>>X.IsD   M 
M'  M< A#N M$#M$'M98M9<NNA"O-