
    @-Ph              	       2   d Z  e                                            ZdZdZddlmZ ddlm	Z	 ddl
mZm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ZddlZddlZddlZddlZej        d	k    rd
ZnddlmZ ddlZ	 ddlm Z m!Z! n# e"$ r ddl#m Z m!Z! Y nw xY w	 ddl$m%Z%m&Z&m'Z' n# e"$ r e(Z%d Z&d Z'Y nw xY w e)d          Z*	 ddl+Z+dZ,n# e"$ r dZ,Y nw xY w G d de(          Z-d\dZ.d]dZ/ G d de           Z0	 	 	 d^dZ1d Z2 G d de(          Z3 G d d          Z4 G d  d!e5          Z6 G d" d#e(          Z7d_d%Z8d& Z9e' G d' d(e%                      Z:d) Z;d`d+Z<dad,Z=g fd-Z>g fd.Z? G d/ d0e(          Z@eAd1k    rdd2lBmCZCmDZD  eCe3          ZEeEF                    d4d5e6           eEF                    d7d8d9e)d:d;<           eEF                    d=d>eGd:d?d@A           eEF                    dBdCeHd:ddDA           eEF                    dEdFddGdHI           eEF                    dJdKddGdLI           eEF                    dMdNeHd:g dOd*dPQ           eEF                    dReDdST           eEI                                ZJ eKeJjL                  dk    r eMdU            ejN        d$           eJjL        d         ZOeJjL        d$d         ZP e=eJjQ                  ZReJjS        r e4eReJjT        V          ZUn e7eJjV        eRW          ZU	 eJjL        d         W                    dX          r* e2eJjL        d                   ZX e>eXeUeJjQ        eP           n e?eOeUeJjQ        eP           eJjY         eZeJjY        dY          Z[nej\        Z[eJjS        reU8                    e[Z           dS  e8eUeJj]        e[[           dS # eJjY         eZeJjY        dY          Z[nej\        Z[eJjS        reU8                    e[Z           w  e8eUeJj]        e[[           w xY wdS )bz,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                     | S N )funcs    O/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/memory_profiler.py<lambda>r   /   s    4     c                     | S r   r   )clss    r   r   r   0   s    s r   i   TFc                   $    e Zd ZdZd Zd Zd ZdS )MemitResultzImemit magic run details.

    Object based on IPython's TimeitResult
    c                 Z    || _         || _        || _        || _        || _        || _        d S r   )	mem_usagebaselinerepeattimeoutintervalinclude_children)selfr   r   r   r   r    r!   s          r   __init__zMemitResult.__init__D   s3    "   0r   c                 L    t          | j                  }|| j        z
  }d||fz  S )Nz,peak memory: %.02f MiB, increment: %.02f MiB)maxr   r   )r"   max_memincs      r   __str__zMemitResult.__str__M   s,    dn%%%=#NNr   c                 Z    t          |           }|                    d|z   dz              d S )Nz<MemitResult : >)strtext)r"   pcyclemsgs       r   _repr_pretty_zMemitResult._repr_pretty_R   s0    $ii	!C'$./////r   N)__name__
__module____qualname____doc__r#   r(   r0   r   r   r   r   r   >   sN         
1 1 1O O O
0 0 0 0 0r   r   c              #   f  K   t          | t                    r-| dk    rt          j                    } t	          j        |           } |st          | d          rdnd}t          | d          rdnd}	  t          | |          d          D ]}t          |t                    r: t          ||                      }|j	        t          ||          t          z  fV  Q|j	         t          ||                      |         t          z  fV  d	S # t          j        t          j        f$ r dV  Y d	S w xY w)
zI
    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_memoryrM   W   sk     
 '3 *b==BIKK'.)) _(/(G(G^}}M^ #*':">">RJJNM	4WWm44tDDD 	Y 	YE--- Y6'%6688i-!@!@7!JJJJJJi!=!=!=!?!?!NQX!XXXXXX	Y 	Y  &"56   s   0BD D0/D0c                     	  dk    rt          j                     fd} fd} fd	 fd}|dk    rdk    rt          d          ||	fd		fd
|d} ||                     S )Nr	   c                      t          t          fdt          j                                        d                              } | j        t          z  }r|t          j                    fS |S )Nc                 H    t          |                                         S r   )r+   
startswith)itemfilenames    r   r   z7_get_memory.<locals>.tracemalloc_tool.<locals>.<lambda>|   s    D		(<(<X(F(F r   rS   )nextfiltertracemalloctake_snapshot
statisticssizerD   time)statmemrS   
timestampss     r   tracemalloc_toolz%_get_memory.<locals>.tracemalloc_toolz   sr    FFFFF&466AA*MMO O P Pi'! 		##Jr   c                  X   t          j                  } 	 t          | d          rdnd} t          | |                      d         t          z  }r*|t          d t          | |          D                       z  }r|t          j                    fS |S # t           j        $ r Y d S w xY w)Nr6   r7   r   c                     g | ]\  }}|S r   r   .0rC   r\   s      r   
<listcomp>z5_get_memory.<locals>.ps_util_tool.<locals>.<listcomp>   s    \\\Zc3S\\\r   )	r@   r   rA   rB   rD   sumrM   rZ   rF   )rG   rH   r\   r!   rC   r]   s      r   ps_util_toolz!_get_memory.<locals>.ps_util_tool   s    .%%	 -4G],K,K '==& 0''<002215?C ^\\3DWl3[3[\\\]]] DIKK''
" 	 	 	DD	s   A<B B B)(B)c           	         t          j                  }	 t          |d          s"t          d                    |                     d} t          ||                      }t          ||           s%t          d                    |           dz             t          ||           t          z  }r+|t          d t          |||           D                       z  }r|t          j	                    fS |S # t           j
        $ r Y d S w xY w)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_infoc                     g | ]\  }}|S r   r   ra   s      r   rc   z;_get_memory.<locals>._ps_util_full_tool.<locals>.<listcomp>   s    kkkZc3Skkkr   )r@   r   rA   NotImplementedErrorformatrB   rD   rd   rM   rZ   rF   )rI   rG   rH   rL   r\   r!   rC   r]   s        r   _ps_util_full_toolz'_get_memory.<locals>._ps_util_full_tool   s:    .%%	7$677 h)*P*W*WXe*f*fggg-L4gg|4466G7M22 @)BII-XX~@ @ @ '=11G;C mkk3DWl\i3j3jkkklll DIKK''
" 	 	 	DD	s   CC6 4C6 6D	D	c                  6   rt          d          t          j        d           t          j        dddt                    gt          j                                                  d                             d          } 	 | d                                         	                    d	          }t          | d
                                         |                   dz  }r|t          j                    fS |S #  rdt          j                    fcY S Y dS xY w)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	   )ri   warningswarn
subprocessPopenr+   PIPEcommunicatesplitindexfloatrZ   )out	vsz_indexr\   r!   rC   r]   s      r   
posix_toolz_get_memory.<locals>.posix_tool   s    	%3  
 	MNNN c4S:&0o! ! !!,q227%,, 		A,,V44IAy122T9C DIKK''
	 49;;&&&rrs   A3C: 8C: :DrV   	<unknown>z:There is no access to source file of the profiled functionc                        d          S )NpssrI   r   rk   s   r   r   z_get_memory.<locals>.<lambda>       #5#5E#J#J#J r   c                        d          S )Nussr   r   r   s   r   r   z_get_memory.<locals>.<lambda>   r   r   rV   r@   
psutil_pss
psutil_ussposix)r>   r?   RuntimeError)
rC   backendr]   r!   rS   r^   re   r}   toolsrk   s
   ` ```    @r   _get_memoryr   u   s   
byyikk           &      :      < -[!8!8H
 
 	
 -#JJJJJJJJ 	" "E
 5>r   c                   *     e Zd ZdZd fd	Zd Z xZS )MemTimerz<
    Fetch memory consumption from over a time interval
    Fc                 p   || _         || _        || _        d| _        || _        || _        d| _        |                    dd          | _        |                    dd          | _	        t          | j         | j        | j        | j	                  g| _         t          t          |           j        |i | d S )NTrq   r]   Fr!   r]   r!   )monitor_pidr    pipecontr   	max_usagen_measurementspopr]   r!   r   r   superr   r#   )	r"   r   r    r   r   r   argskw	__class__s	           r   r#   zMemTimer.__init__   s    & 		"&&u55 "'95 A A ($,4?)-)>@ @ @A 	'h&333333r   c                    | j                             d           d}	 t          | j        | j        | j        | j                  }| j        s| j        	                    |           n#t          || j        d                   | j        d<   | xj        dz  c_        |rn | j                             | j                  }| j                             | j                   | j                             | j                   d S )Nr   FTr   rq   )r   sendr   r   r   r]   r!   r   r   appendr%   r   pollr    )r"   stopcur_mems      r   runzMemTimer.run   s    	q	1! $,4?!%!69 9 9G > D%%g....$'1B$C$Cq!1$ 9>>$-00D	1 		t~&&&	t*+++++r   F)r1   r2   r3   r4   r#   r   __classcell__)r   s   @r   r   r      sV         4 4 4 4 4 4&, , , , , , ,r   r   皙?c           	      
   t          |	          }	|d}|sg }nd}| t          t          ||z                      }n+t          | t                    rd}nt	          d          }|
|
}t          |           r| di f} t          | t          t          f          rt          |           dk    r| d         di }}}nYt          |           dk    r| d         | d         i }}}n3t          |           d	k    r| d         | d         | d         }}}nt          d}	 |dz  }t                      \  }}t          t          j                    |||	|||
          }|                                 |                                 	  ||i |}|                    d           |                                }|                                }|r|d         }|r||f}n# t"          $ rt t%          j        t          j                              }|                    d          D ]!}t          j        |j        t.                     "|                    d            w xY w|                    d|z             |dk    s||k    s|dk     rn|dz  }ont          | t2          j                  rcd}	 |st7          | j        |	||          }|rw|u|                     dj        |            |rUt=          | j                  D ]@\  }}|                    d                    ||t?          j                                         Ano|r2|g}t=          | j                  D ]\  }}|                     |           |                     |           n%tC          |t7          | j        |	|                    }t?          j"        |           |dz  }|dk    rd}||#                                 ||dz  }|dk    rn| $                                n^n=|dk    rd}d}||k     r,|dz  }|st7          | |	||          }|p|                     dj        |            |rPt=          |           D ]@\  }}|                    d                    ||t?          j                                         Anf|r-|g}t=          |           D ]\  }}|                     |           |                     |           n!tC          |t7          | |	|          g          }t?          j"        |           |dz  dk    r||#                                 ||k     ,|rdS |S )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	   rq   infr   r         )r]   r   r!   r:         gư>g      $@r   zMEM {0:.6f} {1:.4f}
zCHLD {0} {1:.6f} {2:.4f}
r!   2   )%choose_backendr=   roundr<   rz   callablelisttuplelen
ValueErrorr   r   r>   r?   startrecvr   	Exceptionr@   r   r8   killrC   r
   joinrt   ru   r   writerj   rM   rZ   r   r%   sleepflushr   )procr    r   r]   r!   multiprocessr   retvalstreamr   max_iterationsretmax_iterfr   r   current_iter
child_connparent_connr-   returnedr   parentrK   
line_countr   idxchldmem_counters                                 r   memory_usager     sG   @ W%%G
 uWx/0011	D#		 & <<%%H~~ b"~$u&& zt99>>7BRtAAYY!^^7DGRRtAAYY!^^7DGT!WRtAA!	AL&*ff#Jh
G$.#,*:< < <A GGIII1d>b>>  ###!&&((!,!1!1!3!3 !a&C (x-C   	44#__t_<< 0 0EGEIw////q			 FF1x<   ""(@(@hQUooOHC!	@ 	D**	+	+ M
&	 U'Hg*%57 7 7	  *!3LL!?!8!?!KLLL $ i,=dh,G,G i iLC"LL)E)L)LSRY[_[d[f[f)g)ghhhh $ 6%.K	*;DH*E*E 6 6JAw%,,W5555 JJy))))#%"hBRT T TU U Jx   !OJB
%LLNNN"Aq==yy{{&M&	R r>>H  qLG ''j%57 7 7	 %LL!?!8!?!KLLL $ i,=d,C,C i iLC"LL)E)L)LSRY[_[d[f[f)g)ghhhh $ 6%.K	*;D*A*A 6 6JAw%,,W5555 JJy))))3&tWGWXXX   Jx   |q  V%7=   >  tJs   ;AG A>Ic                    t           j                            |           r| S t          j        dt           j                                      t           j                  }|D ]H}|st           j                            ||           }t           j                            |          r|c S It          j	        
                    d                    |                      t          d          )zT Find the script.

    If the input is not a file, then $PATH will be searched.
    PATHzCould not find script {0}
rq   )r>   pathisfilegetenvdefpathrx   pathsepr   sysstderrr   rj   
SystemExit)script_namer   folderfns       r   _find_scriptr     s    
 
w~~k"" 9VRZ((..rz::D   	W\\&+..7>>" 	III	 J299+FFGGG
Q--r   c                   *    e Zd ZdZ	 	 ddZd Zd ZdS )_TimeStamperCMzTime-stamping context manager.NFc                 Z    || _         || _        || _        || _        || _        || _        d S r   )r]   rS   r   tsr   r!   )r"   r]   rS   r   timestamperr   r!   s          r   r#   z_TimeStamperCM.__init__  s3    $ 	 0r   c           	      >   | j         I| j         xj        dz  c_        | j         j        | j                                     | j         j                   | j                            t          t          j                    | j	        d| j
        | j                             d S Nrq   Tr]   r!   rS   )r   current_stack_levelstackr   r   r]   r   r>   r?   r   r!   rS   r"   s    r   	__enter__z_TimeStamperCM.__enter__  s    7G''1,''GM$)$++DG,GHHH	T\d)-)>X X X	Y 	Y 	Y 	Y 	Yr   c           	          | j         | j         xj        dz  c_        | j                            t	          t          j                    | j        d| j        | j	                             d S r   )
r   r   r]   r   r   r>   r?   r   r!   rS   )r"   r   s     r   __exit__z_TimeStamperCM.__exit__  sv    7G''1,''	T\d)-)>X X X	Y 	Y 	Y 	Y 	Yr   )NNF)r1   r2   r3   r4   r#   r   r   r   r   r   r   r     sZ        ((MQ"'1 1 1 1Y Y YY Y Y Y Yr   r   c                   T    e Zd ZdZddZddZddZd Zd	 Ze	d
             Z
ddZdS )TimeStamperz` A profiler that just records start and end execution times for
    any decorated function.
    Fc                 L    i | _         || _        || _        d| _        i | _        d S )Nr	   )	functionsr   r!   r   r   )r"   r   r!   s      r   r#   zTimeStamper.__init__  s+     0#% 


r   Nc                 H    |t          |          st          d                               |                                |          }|j        |_        |j        |_        |j        |_        |j                            t          |di                      |S  fd}|S )NzValue must be callable__dict__c                 2                         |           S N)	precision__call__r   r   r"   s    r   inner_partialz+TimeStamper.__call__.<locals>.inner_partial1      }}Q)}<<<r   )
r   r   add_functionwrap_functionr2   r1   r4   r   updaterB   r"   r   r   r   r   s   ` `  r   r   zTimeStamper.__call__$  s    D>> ; !9:::d###""4((A?ALAJAIJgdJ;;<<<H= = = = = = ! r   <block>c                    d }d|_         ||_        |                     |           g }| j        |                             |           	 t          j        |          }n# t          $ r d}Y nw xY wt          ||| j	        | |          S )z;Returns a context manager for timestamping a block of code.c                     | S r   r   )xs    r   r   z'TimeStamper.timestamp.<locals>.<lambda>9  s     r    r~   )r   r   )
r2   r1   r   r   r   inspectgetsourcefile	TypeErrorr   r   )r"   namer   r]   rS   s        r   	timestampzTimeStamper.timestamp6  s     {$
t##J///	#,T22HH 	# 	# 	#"HHH	#L
 
 
 	
s   
A A.-A.c                 D    || j         vrg | j         |<   g | j        |<   d S d S r   )r   r   )r"   r   s     r   r   zTimeStamper.add_functionM  s5    t~%%#%DN4 !DJt &%r   c                       fd}|S )z* Wrap a function to timestamp it.
        c                     	 t          j                  }n# t          $ r d}Y nw xY wt          t	          j                    j        dj        |          g}j                 	                    |           	  j
        g| R i |5 }|cd d d            |	                    t          t	          j                    j        dj        |                     S # 1 swxY w Y   	 |	                    t          t	          j                    j        dj        |                     d S # |	                    t          t	          j                    j        dj        |                     w xY w)Nr~   Tr   )r  r  r  r   r>   r?   r   r!   r   r   call_on_stack)r   kwdsrS   r]   resultr   r"   s        r   r   z$TimeStamper.wrap_function.<locals>.fV  s   '"066 ' ' '&' BIKK$-1-BXW W WXJ N4 ''
333B'T'<t<<<t<< "!" " " " " " " !!+bikk4<TX?C?T7?#A #A #A B B B B	" " " " " " " " " !!+bikk4<TX?C?T7?#A #A #A B B B B B
!!+bikk4<TX?C?T7?#A #A #A B B B Bs=    '';D- CD- C!!D- $C!%D- -AE1r   r"   r   r   s   `` r   r   zTimeStamper.wrap_functionR  s/    	B 	B 	B 	B 	B 	B& r   c              /      K   | xj         dz  c_         | j        |                             | j                     ||i |V  | xj         dz  c_         d S Nrq   )r   r   r   )r"   r   r   r  s       r   r  zTimeStamper.call_on_stackk  sm        A%  
4 8999dD!D!!!!!  A%    r   c                 "   |t           j        }| j                                        D ]f\  }}|j        d|j        }t          || j        |                   D ]4\  }}|                    d|f|d         z   |d         z   |fz   z             5gd S )N.zFUNC %s %.4f %.4f %.4f %.4f %d
r   rq   )	r   ro   r   itemsr2   r1   zipr   r   )r"   r   r   r]   function_namer   levels          r   show_resultszTimeStamper.show_resultst  s    >ZF $ 4 4 6 6 	B 	BD*'+FM TZ-=>> B B	E?"$r!u,r!u4x?A B B B BB	B 	Br   r   )NN)r   r   )r1   r2   r3   r4   r#   r   r  r   r   r   r  r  r   r   r   r   r     s            ! ! ! !$
 
 
 
." " "
  2 & & ^&B B B B B Br   r   c                   (    e Zd Zd ZddZd Zd ZdS )CodeMapc                 0    || _         g | _        || _        d S r   )r!   	_toplevelr   )r"   r!   r   s      r   r#   zCodeMap.__init__  s     0r   Nc                 P   || v rd S ||j         }|                    d          r
|d d         }t          j                            |          s8t          d|z              |                    d          rt          d           d S |}t          j        |          \  }}t          ||t          |          z             }| j                            |||f           i | |<   n| |         | |<   t          t          j        |j                  D ]}|                     ||           d S )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endswithr>   r   existsprintrQ   r  getsourcelinesranger   r  r   rU   iscode	co_constsadd)r"   coder  rS   	sub_lines
start_linelinenossubcodes           r   r&  zCodeMap.add  sU   4<<F 'H  !122 )#CRC=7>>(++ 3h>???&&'JKK POP P P  M&-&<T&B&B#Y
J&Y79 9GN!!8T7";<<<DJJm,DJgndn== 	; 	;GHHWMH::::	; 	;r   c                    t          d| j        | j        |j                  }| |                             |d           }|r|d         nd}|r|d         nd}|r| |                             |d           nd }|r|d         nd}	|| |         v r| |         |         d         dz   nd}
|||	z
  z   t          ||          |
f| |         |<   d S )Nr	   )r!   rS   rq   r   r   )r   r   r!   r  getr%   )r"   r'  linenoprev_linenomemory
prev_valueprevious_memoryprevious_incprev_line_valueprev_line_memory	occ_counts              r   tracezCodeMap.trace  s    R@U&*&68 8 8$Z^^FD11
+5<*Q--1(29z!}}?JT$t*..d;;;PT1@G?1--a174:1E1EDJv&q)A--1	F%556((
T
6r   c              #   f   K   | j         D ]%\  }}}| |         sfd|D             }||fV  &dS )z$Iterate on the toplevel code blocks.c              3   F   K   | ]}|                     |          fV  d S r   )r-  )rb   linemeasuress     r   	<genexpr>z CodeMap.items.<locals>.<genexpr>  s4      LLDdHLL$6$67LLLLLLr   N)r  )r"   rS   r'  r*  line_iteratorr;  s        @r   r  zCodeMap.items  sj      )- 	, 	,%XtWDzH LLLLGLLLM]+++++	, 	,r   r   )r1   r2   r3   r#   r&  r7  r  r   r   r   r  r    sU          
; ; ; ;8
 
 
 , , , , ,r   r  c                   x    e Zd ZdZd ZddZd Zed             Zd Z	d	 Z
d
 Zd Zd Zd Zd Zd Zd Zd ZdS )LineProfilerz< A profiler that records the amount of memory for each line c                 :   |                     dd          }|                     dd          }t          ||          | _        d| _        |                     dd           | _        g | _        t          |                     dd                     | _        d | _        d S )Nr!   Fr   r@   )r!   r   r   r&   )	r-  r  code_mapenable_countr&   	prevlinesr   r   r/  )r"   r   r!   r   s       r   r#   zLineProfiler.__init__  s    66"4e<<&&H---w@ @ @vvi..%bffY&=&=>>r   Nrq   c                     |y                      |                                |          }|j        |_        |j        |_        |j        |_        |j                            t          |di                      |S  fd}|S )Nr   c                 2                         |           S r   r   r   s    r   r   z,LineProfiler.__call__.<locals>.inner_partial  r   r   )r   r   r2   r1   r4   r   r   rB   r   s   ` `  r   r   zLineProfiler.__call__  s    d###""4((A?ALAJAIJgdJ;;<<<H= = = = = = ! r   c                     	 |j         }| j                            |           dS # t          $ r t	          j        d|z             Y dS w xY w)zJ Record line profiling information for the given Python function.
        z1Could not extract a code object for the object %rN)__code__rA  r&  AttributeErrorrr   rs   )r"   r   r'  s      r   r   zLineProfiler.add_function  sw    	$=D
 Md#####	  	" 	" 	"MM ! " " " " " "	"s   % !A
	A
c              #      K   |                                   	 d V  |                                  d S # |                                  w xY wr   )enable_by_countdisable_by_countr   s    r   _count_ctxmgrzLineProfiler._count_ctxmgr  sV      	$EEE!!#####D!!####s	   2 Ac                 \     t                    rt           fd            }n fd}|S )z( Wrap a function to profile it.
        c               ?      K                                    5   | i |E d {V }|cd d d            S # 1 swxY w Y   d S r   rL  )r   kwargsresr   r"   s      r   r   z%LineProfiler.wrap_function.<locals>.f  s      ''))  %)T4%:6%:%:::::::C                 s   599c                  p                                     5   | i |cd d d            S # 1 swxY w Y   d S r   rO  )r   r  r   r"   s     r   r   z%LineProfiler.wrap_function.<locals>.f  s    '')) / /4.../ / / / / / / / / / / / / / / / / /s   +//)r   r   r  s   `` r   r   zLineProfiler.wrap_function  sh     t$$ 		/     Y 
/ / / / / / r   c                     |                                   	 t          |||           |                                  n# |                                  w xY w| S )zH Profile a single executable statement in the given namespaces.
        )rJ  execrK  )r"   cmdglobalslocalss       r   runctxzLineProfiler.runctx  s_     		$gv&&&!!####D!!####s	   < Ac                 d    | j         dk    r|                                  | xj         dz  c_         dS )z? Enable the profiler if it hasn't been enabled before.
        r   rq   N)rB  enabler   s    r   rJ  zLineProfiler.enable_by_count  s9     !!KKMMMQr   c                     | j         dk    r1| xj         dz  c_         | j         dk    r|                                  dS dS dS )zo Disable the profiler if the number of disable requests matches the
        number of enable requests.
        r   rq   N)rB  disabler   s    r   rK  zLineProfiler.disable_by_count  sS     q  " A%% ! %%r   c                    |j         | j        v r|dk    r | j                            |j                   n|dk    rS| j                            |j         | j        d         | j                   | j        d         | _        |j        | j        d<   nL|dk    rF| j                                        }| j                            |j         || j                   || _        | j        |                     |||           | j	        S )zCallback for sys.settracecallr:  r	   return)
f_coderA  rC  r   f_linenor7  r/  r   _original_trace_functiontrace_memory_usage)r"   frameeventargr.  s        r   rc  zLineProfiler.trace_memory_usage  s    <4=((%%en5555&##EL$.2DdFVWWW#'>"#5 %*^r""(""++--##EL&$:JKKK#) (4))%<<<&&r   c                 $   |dv r|j         | j        v rt          d| j        |j         j                  }|| j        k    rd                    || j                  }t          j        	                    |           t          j        	                    d           |xj
        dz  c_
        t          j                    }d|_        ||_        d |_        |j
        dz
  |_        d |_        |j        S | j        |                     |||           | j        S )	N)r:  r_  r	   )rS   z?Current memory {0:.2f} MiB exceeded the maximum of {1:.2f} MiB
zStepping into the debugger 
r   Fr   )r`  rA  r   r   r  r&   rj   r   ro   r   ra  pdbPdbquitting	stopframereturnframe
stoplinenobotframetrace_dispatchrb  trace_max_mem)r"   rd  re  rf  ctr-   s          r   rp  zLineProfiler.trace_max_mem-  s   &&&5<4=+H+HBu|7OPPPADL  006q$,0G0G 
  ###
  !@AAA!#GII"
# $$~1!
''(4**E5#>>>!!r   c                 .    |                                   d S r   )rJ  r   s    r   r   zLineProfiler.__enter__D  s    r   c                 .    |                                   d S r   )rK  )r"   exc_typeexc_valexc_tbs       r   r   zLineProfiler.__exit__G  s    r   c                     t          j                    | _        | j        t          j        | j                   d S t          j        | j                   d S r   )r   gettracerb  r&   settracerp  rc  r   s    r   rZ  zLineProfiler.enableJ  sJ    (+%<#L+,,,,,L011111r   c                 8    t          j        | j                   d S r   )r   rz  rb  r   s    r   r\  zLineProfiler.disableQ  s    T233333r   r  )r1   r2   r3   r4   r#   r   r   r   rL  r   rX  rJ  rK  rc  rp  r   r   rZ  r\  r   r   r   r?  r?    s        FF	  	  	 ! ! ! !
$ 
$ 
$ $ $ ^$  "      ' ' '," " ".       2 2 24 4 4 4 4r   r?  rq   c                    |t           j        }d}| j                                        D ]N\  }}|                    ddddd          }|                    d|z   dz              |                    |d	z              |                    d
t          |          z  d	z              t          j        |          }d                    |dz   |          }d|z   dz   }	|D ]\  }
}|rC|d         }|d         }|	                    |          }|d         }|	                    |          }nd}d}d}|                    |
|||||
dz
                     }|                    |           |                    d           Pd S )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   rq   r   r  )	r   ro   rA  r  rj   r   r   	linecachegetlines)profr   r   templaterS   linesheader	all_linesfloat_formattemplate_memr.  r\   r'   	total_memoccurrencestmps                   r   r  r  U  s   ~8H!]0022  5;]!02 2 	]X-6777Ve^$$$TCKK'$.///&x00	")))a-CC,w6" 	 	MVS 	"!fF	(//	::	!!f"))#..	!//&)S+yQWZ[Q[G\]]CLLW3 r   c                 &    t          | |           d S r   )rT  )stmtnss     r   
_func_execr  v  s     	rNNNNNr   c                   T    e Zd Zedd            Zedd            Zed             ZdS )MemoryProfilerMagicsr  Nc           
         ddl m} ddlm}m} ddlm} ddl} ||j                  }|dk     rddl	m
}	 ddlm}
 dd	lm} nddlm
}	 ddlm}
 dd	lm}  |
d
gg           }|                    dd                              dd          }|                     |dd          \  }}|                    |           | j        j        }| j        j        }||d|z   z  }g }|j        D ]W}	 |                    t5          |||                     (# t6          $ r#} |d|d|j        j        d|          d}~ww xY wd|v } ||          }|D ]} ||           dt<          j        v rd}t<          j        d         }nd}d}|t<          j        d<   	 |                     |||           d
}n# tB          $ r d}Y ntD          $ r d}Y nw xY w|r|t<          j        d<   n# |r|t<          j        d<   w xY w |            } |||           |#                                }|$                                }|dk     r |	|| j        j%        j&                   n |	|           tO          |           |j(        d         }|rRtS          |d          5 }|*                    |           ddd           n# 1 swxY w Y   tO          d|d |           d}d!|v r|}|S )"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  r?  LooseVersionNz0.11)page)Struct)
UsageErrorr  )Tr   "z\"'z\'zrf:T:cT)list_allr  zCould not find function z.
z: rq  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  r?  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   r1   builtinsr   rX  r   KeyboardInterruptgetvaluerstriprcscreen_lengthr!  r  openr   )r"   parameter_scellr  r  r?  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   mprunzMemoryProfilerMagics.mprun  ss   T 	 >>>>>>>> 	322222&,w':;;V##------//////0000000......555555555555 6RDB'''!))#u55==c5II**;48 + : :g

8J-	:%td{"G F 	N 	NDNT$	8<<==== N N N jj$$$JK+J^J^J^JK!"M N N NN
 $;,0@AAA 	 	DGDMMMM )))K"+I6KKKK'.)$
	;NN7Ix888GG 	P 	P 	POGGG  	$ 	$ 	$#GGG	$  ;/:!),  ;/:!),:::: hjjWk***%%''V##Ddjm&ABBBBBDLLLgF1I	 	i%% $F###$ $ $ $ $ $ $ $ $ $ $ $ $ $ $E		    $;;"Ls`   *$D
D<D77D<F0 /G! 0G<G! >G	G! GG! !G4J33J7:J7c                    ddl m}m} |                     |ddd          \  }}|d}n|}|}t	          t          |dd	                    }|d	k     r|d	k     t	          t          |d
d                    }	|	dk    rd}	t          t          |dd                    }
d|v }d|v }d|v }ddl}|                                  ||| j	        j
                   g }d} |            d         }||k     r?|d	z  } |||| j	        j
        ff|	|
dd	|          }|                    |           ||k     ?t          ||||	|
|          }|s!|rt          |           nt          d           |r|S dS )a0  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  rq   rr  ir   rq  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  r=   rB   rz   gccollectr  r  r   r   r!  )r"   r:  r  r   r  r  r  setupr   r   r    r!   return_resultquietr  r   r   r   r  r  s                       r   memitzMemoryProfilerMagics.memit  s   h 	=<<<<<<<''k/4 ( 6 6
d <EEEDWT3**++A::aKKgdC++,,a<<GsC0011$;tt 				



5$*,---	<>>!$qLG,
T4:3E,FG'.)-a0@B B BC S!!!  Y&'8-/ /  	; ;f : ; ; ;  	M	 	r   c                    ddl m} dd l} ||j                  }|dk     rN	 |j        }n# t
          $ r
 |j        }Y nw xY w |d| j        j                    |d| j	        j                   d S |
                    |            d S )Nr   r  z0.13r  r  )r  r  r  r  define_magicrH  expose_magicr  __func__r  register_magics)r   ipr  r  r  _register_magics         r   r  z$MemoryProfilerMagics.register_magicsl  s    222222&,w':;;V##2"$/! 2 2 2"$/2 OGSY%7888OGSY%788888s#####s   * >>)r  N)r1   r2   r3   r   r  r  classmethodr  r   r   r   r  r  |  sy         A A A _AH e e e _eN $ $ [$ $ $r   r  c                 :    t                               |            dS )z:This is called to load the module as an IPython extension.N)r  r  )r  s    r   load_ipython_extensionr    s     ((,,,,,r   r@   c                     t                    dk    r-t          r&t          j                    st          j                      t          t                    t          t                    t                     r+t                     t           fd                        }nt                      fd            }|S fd}|S )	zO
    Decorator that will run the function and print a line-by-line profile
    rV   N)r   )r   r   )wrappedc               ?   d   K                }  |          | i |E d {V } |           |S r   r   r   rP  r  valr   get_profshow_results_bounds       r   wrapperzprofile.<locals>.wrapper  sX        xzz!+dT!<V!<!<<<<<<<""4(((
r   c                  T                 }  |          | i |} |           |S r   r   r  s       r   r  zprofile.<locals>.wrapper  s@    xzz dd4jj$1&11""4(((
r   c                 *    t          |           S )N)r   r   r   r  )r   r   r   r   s    r   inner_wrapperzprofile.<locals>.inner_wrapper  s#    1Vy#*, , , ,r   )r   has_tracemallocrV   
is_tracingr   r   r?  r  r   r   r   )r   r   r   r   r  r  r  r  s   ````  @@r   r  r    sB    W%%G-O%'' 	 <999$9
 
 
 t$$ 	4         Y !   4         !  	, 	, 	, 	, 	, 	, 	, r   c                 p   d}ddddt           j        dk    fdt          fg}t          d t	          |          D                       }| /|                    d	|                    ||                               |D ]\  }}|r|} n|| k    r*| (t          j        d
	                    | |                     |S )zv
    Function that tries to setup backend, chosen by user, and if failed,
    setup one of the allowable backends
    
no_backend)r@   T)r   T)r   Tr   rV   c              3   0   K   | ]\  }}|d          |fV  dS )r   Nr   )rb   r  bs      r   r<  z!choose_backend.<locals>.<genexpr>  s.      JJ$!QQqT1IJJJJJJr   Nr   z%{0} can not be used, {1} used instead)
r>   r  r  dict	enumerateinsertr   rr   rs   rj   )new_backend_backendall_backendsbackends_indices	n_backendis_availables         r   r   r     s     H	"'W$%	(L JJ)L2I2IJJJJJA|//0@0MNNOOO#/  	< 	 HE	 ;;#:=DD# # 	$ 	$ 	$Or   c                    ddl m} |t          j        d<   t	          t
          ||           }t          j                            dt          j        
                    t                               t          |          }| g|z   t          _        	 |dk    rt          rt          j                     t#          j        | d          5 }t'          t)          |                                | d          ||           d d d            n# 1 swxY w Y   t          r(t          j                    rt          j                     d S d S d S # t          r't          j                    rt          j                     w w w xY w)	Nr   
run_moduler  )r  __file__rV   zutf-8)encodingrT  )runpyr  r  r   r  _CLEAN_GLOBALSr   r   r  r>   dirnamescript_filenamer   argvr  rV   r   r  r  rT  compilereadr  r   )rS   profilerr   passed_argsr  r  r  r   s           r   exec_with_profilerr    s         #+Hi 	n  	
! 
! 
!B HOOArw77888g&&HzK'CH}$$$WX000 	>A8V44b"===	> 	> 	> 	> 	> 	> 	> 	> 	> 	> 	> 	> 	> 	> 	>  	{577 		 	 	 	? 	{577 		 	s0   6E 3D8E DE DE 1E3c                    ddl m} |t          j        d<   t	          t
          |          }t          |          }| g|z   t          _        |dk    rt          rt          j                     	  || d|           t          r(t          j                    rt          j                     d S d S d S # t          r't          j                    rt          j                     w w w xY w)Nr   r  r  r  rV   __main__)run_nameinit_globals)r  r  r  r   r  r  r   r   r	  r  rV   r   r  r   )moduler  r   r  r  r  r  s          r   run_module_with_profilerr    s         #+Hi 	nh	/	/	/Bg&&Hx+%CH=  _ 
6JR@@@@ 	{577 		 	 	 	? 	{577 		 	s   ,B- -1Cc                   4    e Zd ZdZddZej        fdZd ZdS )LogFilezaFile-like object to log text using the `logging` module and the log
    report can be customised.NFc                 F    t          j        |          | _        || _        dS )a  
        :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  r  s      r   r#   zLogFile.__init__  s$     '--#6   r   c                    | j         rd|v r[t          |                    d          d                                                   dk    r| j                            ||           d S |                    d          s|                    d          r| j                            ||           d S d S | j                            ||           d S )NMiBrq   r   z	Filename:r  )r  rz   rx   stripr  log__contains__)r"   r/   r  s      r   r   zLogFile.write
  s    # 	(||cii&6&6q&9&?&?&A&A B BQ F Fs+++++!!+.. ,#2B2B#3% 3% ,s+++++, , KOOE3'''''r   c                 L    | j         j        D ]}|                                 d S r   )r  handlersr   )r"   handlers     r   r   zLogFile.flush  s/    {+ 	 	GMMOOOO	 	r   )NF)	r1   r2   r3   r4   r#   r  INFOr   r   r   r   r   r  r    s\        ! !7 7 7 7  '| ( ( ( (    r   r  r  )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)r,  r.  r)  defaultr/  z-oout_filenamez,path to a file where results will be writtenz--timestampr  
store_truezMprint timestamp instead of memory measurement for
        decorated functions)r,  r0  r)  r/  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}))r,  r.  r)  choicesr0  r/  programzApython script or module followed by command line arguments to run)nargsr/  z2A program to run must be provided. Use -h for helpr   )r&   r   z.pya)r   )r   r   )Nr   )FFN)r	   r   NFFFFFNNNr  )NNrq   r@   r   )^r4   rV  copyr  r  
_CMD_USAGEasyncior   
contextlibr   	functoolsr   r   typesr   r  r  r  r  r>   r  rh  rt   r   rZ   	tracebackrr   platformr
   signalr@   multiprocessingr   r   ImportErrormultiprocessing.dummyIPython.core.magicr   r   r   objectrz   rD   rV   r  r   rM   r   r   r   r   r   r   r  r  r?  r  r  r  r  r  r   r  r  r  r1   argparser%  r&  parseradd_argumentr=   r+   
parse_argsr   r   r4  r!  exittargetscript_argsr   r  r  r!   r  r&   r  r  r1  r  out_filero   r   r   r   r   <module>rM     s6   2 2 !!7
 ' ' ' ' ' ' % % % % % % $ $ $ $ $ $ $ $              				 				 



     



      <7 GG 4--------- 4 4 433333333334#HHHHHHHHHHH # # #F''O"?LLL	# %..OO   OOO0 0 0 0 0& 0 0 02   <h h h hV*, *, *, *, *,w *, *, *,Z AFGLIMS S S St  &Y Y Y Y YV Y Y Y<dB dB dB dB dB dB dB dBN9, 9, 9, 9, 9,d 9, 9, 9,xW4 W4 W4 W4 W46 W4 W4 W4t   B   ~$ ~$ ~$ ~$ ~$6 ~$ ~$ ~$P- - -# # # #L   B AC    0 EG        f   @ z22222222^*---F
I{KKK
9h7@  B B B KcI  K K K >;  = = = K        ,3El:  < < < )#gNNNX`X  Y Y Y 	P  R R RD
s4<ABCCC\!_F,qrr"K~dl++H~ D{8d6KLLL|DL(CCCJ<?##E** 	N*l4<?;;OdlKPPPP$$VT4<MMM(tD-s33HHzH> 	JX.....LIIIIII (tD-s33HHzH> 	JX....LIIIIIu sD   B BB#
B. .B>=B>C CCAO AP