
    3j*                        d dl mZ g dZd dlZd dlZd dlZddddddZddddddZd	 Zdd
Z	d Z
d Z G d dej                        Zedk(  rd dlZ ej                   e       yy)    )annotations)cpusrunParallelrunNonParallelsafeToParallizeN   FupdateFunctionupdateMultiplyunpackIterableupdateSendsIterablec                   t               st         ||      S t               t               d}g  fd} |d       ddlm}m}	  |      5 }
 |	|      |k  rft        |z  z         }t        ||      }|r |
 fd|D              }n |
 fd|D              }|}j                  |        ||       |k  rfddd       S # 1 sw Y   S xY w)	a3  
    runs parallelFunction over iterable in parallel, optionally calling updateFunction after
    each common.cpus * updateMultiply calls.

    Setting updateMultiply too small can make it so that cores wait around when they
    could be working if one CPU has a particularly hard task.  Setting it too high
    can make it seem like the job has hung.

    updateFunction should take three arguments: the current position, the total to run,
    and the most recent results.  It does not need to be pickleable, and in fact,
    a bound method might be very useful here.  Or updateFunction can be "True"
    which just prints a generic message.

    If unpackIterable is True then each element in iterable is considered a list or
    tuple of different arguments to parallelFunction.

    If updateSendsIterable is True then the update function will get the iterable
    content, after the output.

    As of Python 3, partial functions are pickleable, so if you need to pass the same
    arguments to parallelFunction each time, make it a partial function before passing
    it to runParallel.

    Note that parallelFunction, iterable's contents, and the results of calling parallelFunction
    must all be pickleable, and that if pickling the contents or
    unpickling the results takes a lot of time, you won't get nearly the speedup
    from this function as you might expect.  The big culprit here is definitely
    music21 streams.

    >>> files = ['bach/bwv66.6', 'schoenberg/opus19', 'AcaciaReel']
    >>> def countNotes(fn):
    ...     c = corpus.parse(fn)  # this is the slow call that is good to parallelize
    ...     return len(c.recurse().notes)
    >>> #_DOCS_SHOW outputs = common.runParallel(files, countNotes)
    >>> outputs = common.runNonParallel(files, countNotes) #_DOCS_HIDE cannot pickle doctest funcs.
    >>> outputs
    [165, 50, 131]

    Set updateFunction=True to get an update every 3 * numCpus (-1 if > 2)

    >>> #_DOCS_SHOW outputs = common.runParallel(files, countNotes, updateFunction=True)
    >>> outputs = common.runNonParallel(files, countNotes, updateFunction=True) #_DOCS_HIDE
    Done 0 tasks of 3
    Done 3 tasks of 3

    With a custom updateFunction that gets each output:

    >>> def yak(position, length, output):
    ...     print(f'{position}:{length} {output} is a lot of notes!')
    >>> #_DOCS_SHOW outputs = common.runParallel(files, countNotes, updateFunction=yak)
    >>> outputs = common.runNonParallel(files, countNotes, updateFunction=yak) #_DOCS_HIDE
    0:3 165 is a lot of notes!
    1:3 50 is a lot of notes!
    2:3 131 is a lot of notes!

    Or with updateSendsIterable, we can get the original files data as well:

    >>> def yik(position, length, output, fn):
    ...     print(f'{position}:{length} ({fn}) {output} is a lot of notes!')
    >>> #_DOCS_SHOW outputs = common.runParallel(files, countNotes, updateFunction=yik,
    >>> outputs = common.runNonParallel(files, countNotes, updateFunction=yik, #_DOCS_HIDE
    ...             updateSendsIterable=True)
    0:3 (bach/bwv66.6) 165 is a lot of notes!
    1:3 (schoenberg/opus19) 50 is a lot of notes!
    2:3 (AcaciaReel) 131 is a lot of notes!

    unpackIterable is useful for when you need to send multiple values to your function
    call as separate arguments.  For instance, something like:

    >>> def pitchesAbove(fn, minPitch):  # a two-argument function
    ...     c = corpus.parse(fn)  # again, the slow call goes in the function
    ...     return len([p for p in c.pitches if p.ps > minPitch])

    >>> inputs = [('bach/bwv66.6', 60),
    ...           ('schoenberg/opus19', 72),
    ...           ('AcaciaReel', 66)]
    >>> #_DOCS_SHOW outputs = common.runParallel(inputs, pitchesAbove, unpackIterable=True)
    >>> outputs = common.runNonParallel(inputs, pitchesAbove, unpackIterable=True) #_DOCS_HIDE
    >>> outputs
    [99, 11, 123]
    r	   r   Nc                    du rt        | g      }t        d| d        y dvrOt        | 	z  z
  |       D ]9  }|dk  r	|t              k\  rd }n|   }
s ||       , |||          ; y y )NTDone 
 tasks of FNr   minprintrangelen)ii	tasksDonethisPosition
thisResult
iterLengthiterablenumCpusresultsListr
   r   r   s       D/DATA/.local/lib/python3.12/site-packages/music21/common/parallel.py
callUpdatezrunParallel.<locals>.callUpdate   s    T!R,-IE)Jzl;<=0 %bNW,D&Er J!#3{#33!%J!,\!:J*"<ZH"<ZR^I_` !K 1    )Paralleldelayed)n_jobsc              3  .   K   | ]  } |      y wN .0idelayFunctionr   s     r    	<genexpr>zrunParallel.<locals>.<genexpr>   s     Hx!-!5xs   c              3  4   K   | ]  } |           y wr'   r(   r)   s     r    r-   zrunParallel.<locals>.<genexpr>   s     Gh-4hs   )
r   r   r   r   joblibr#   r$   r   r   extend)r   parallelFunctionr
   r   r   r   totalRunr!   r#   r$   paraendPositionrangeGen_rr,   r   r   r   s   ` `` `        @@@@r    r   r      s   p h(8-;-;-;2E	G 	G fGXJH# Ka a& qM(		!T 01#h>)AA:NKX{3HHxHHGhGG"Hr"x  # 
"  
" s   %A3C##C-c                   	
 t               	g 
	 
fd} |d       t        	      D ]4  }|r	 | |    }n | |         }
j                  |        ||dz          6 
S )z
    This is intended to be a perfect drop in replacement for runParallel, except that
    it runs on one core only, and not in parallel.

    Used automatically if we're already in a parallelized function.
    c                    | z  dk7  ry du rt        | g      }t        d| d        y dvrLt        | z
  |       D ]9  }|dk  r	|t              k\  rd }n|   }	s ||       , |||          ; y y )Nr   Tr   r   r   r   )
r   r   r   r   r   r   r   r
   r   r   s
       r    r!   z"runNonParallel.<locals>.callUpdate   s    !#T!R,-IE)Jzl;<=0 %b>&92 >!#3{#33!%J!,\!:J*"<ZH"<ZR^I_` !? 1r"   r      )r   r   append)r   r1   r
   r   r   r   r!   r+   r6   r   r   s   ` `` `   @@r    r   r      sx     XJKa a, qM:!8A;/B!(1+.B21q5  r"   c                 B    t        j                         } | dk\  r| dz
  S | S )zf
    Returns the number of CPUs or if >= 3, one less (to leave something out for multiprocessing)
    r   r9   )multiprocessing	cpu_count)cpuCounts    r    r   r      s(     ((*H1}!|r"   c                 r    t               dkD  xr) t        j                          xr dt        j                  vS )a   
    Check to see if it is safe or even useful to start a parallel process.

    Will return False if we are in a multiprocessing child process or if
    there is only one CPU or if pytest's x-dist worker flag is in the environment.

    * New in v10.
    r9   PYTEST_XDIST_WORKER)r   r<   parent_processosenvironr(   r"   r    r   r      s7     	
 	4..00	4!3r"   c                v    ddl m} |j                  |       }t        |j	                         j
                        S )Nr   )corpus)music21rE   parser   recursenotes)fnrE   cs      r    _countNrL     s*    RAqyy{  !!r"   c                    | dk\  ry|dvryy)Nr   Fzbach/bwv66.6zschoenberg/opus19
AcaciaReelTr(   )r+   rJ   s     r    _countUnpackedrP     s    Av	DDr"   c                      e Zd Zd Zd Zd Zy)Testc                X   g d}ddl m}m} t        ||      }| j	                  |g d       t        ||| j
                         t        ||| j                  d       t        t        t        |            |d      }| j	                  t        |      d	       | j                  d
|       y )NrN   r   )rL   rP      2      )r
   T)r
   r   )r   r   F)music21.common.parallelrL   rP   r   assertEqual_customUpdate1_customUpdate2list	enumerater   assertNotIn)selffilesrL   rP   outputpasseds         r    &x_figure_out_segfault_testMultiprocessz+Test.x_figure_out_segfault_testMultiprocess  s    CCUG,0E#'#6#6	8 	E#'#6#6(,	. T)E"23+,02 	Va('r"   c                t    | j                  |d       | j                  |d       | j                  |g d       y )Nr   rT   )rY   
assertLessassertIn)r_   r+   totalra   s       r    rZ   zTest._customUpdate1&  s.    "1fn-r"   c                ,    | j                  |g d       y )NrN   )rf   )r_   r+   unused_totalunused_outputrJ   s        r    r[   zTest._customUpdate2+  s    bMNr"   N)__name__
__module____qualname__rc   rZ   r[   r(   r"   r    rR   rR     s    ((.
Or"   rR   __main__)returnbool)
__future__r   __all__r<   rB   unittestr   r   r   r   rL   rP   TestCaserR   rk   rF   mainTestr(   r"   r    <module>rv      s    #  	   $ $$)Nh #'"#"'',1h6"O8 O> zGT r"   