410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558 | class NeuronProcessor:
"""Apply function across all neurons of a neuronlist.
This assumes that the first argument for the function accepts a single
neuron.
"""
def __init__(self,
nl: 'core.NeuronList',
function: Callable,
parallel: bool = False,
n_cores: int = os.cpu_count() // 2,
chunksize: int = 1,
progress: bool = True,
warn_inplace: bool = True,
omit_failures: bool = False,
exclude_zip: list = [],
desc: Optional[str] = None):
if utils.is_iterable(function):
if len(function) != len(nl):
raise ValueError('Number of functions must match neurons.')
self.funcs = function
self.function = function[0]
elif callable(function):
self.funcs = [function] * len(nl)
self.function = function
else:
raise TypeError('Expected `function` to be callable or list '
f'thereof, got "{type(function)}"')
self.nl = nl
self.desc = desc
self.parallel = parallel
self.n_cores = n_cores
self.chunksize = chunksize
self.progress = progress
self.warn_inplace = warn_inplace
self.exclude_zip = exclude_zip
self.omit_failures = omit_failures
# This makes sure that help and name match the functions being called
functools.update_wrapper(self, self.function)
def __call__(self, *args, **kwargs):
# Explicitly providing these parameters overwrites defaults
parallel = kwargs.pop('parallel', self.parallel)
n_cores = kwargs.pop('n_cores', self.n_cores)
# We will check, for each argument, if it matches the number of
# functions to run. If they it does, we will zip the values
# with the neurons
parsed_args = []
parsed_kwargs = []
for i, n in enumerate(self.nl):
parsed_args.append([])
parsed_kwargs.append({})
for k, a in enumerate(args):
if k in self.exclude_zip:
parsed_args[i].append(a)
elif not utils.is_iterable(a) or len(a) != len(self.nl):
parsed_args[i].append(a)
else:
parsed_args[i].append(a[i])
for k, v in kwargs.items():
if k in self.exclude_zip:
parsed_kwargs[i][k] = v
elif not utils.is_iterable(v) or len(v) != len(self.nl):
parsed_kwargs[i][k] = v
else:
parsed_kwargs[i][k] = v[i]
# Silence loggers (except Errors)
level = logger.getEffectiveLevel()
if level < 30:
logger.setLevel('WARNING')
# Apply function
if parallel:
if not ProcessingPool:
raise ModuleNotFoundError(
'navis relies on pathos for multiprocessing!'
'Please install pathos and try again:\n'
' pip3 install pathos -U'
)
if self.warn_inplace and kwargs.get('inplace', False):
logger.warning('`inplace=True` does not work with '
'multiprocessing ')
with ProcessingPool(n_cores) as pool:
combinations = list(zip(self.funcs,
parsed_args,
parsed_kwargs))
chunksize = kwargs.pop('chunksize', self.chunksize) # max(int(len(combinations) / 100), 1)
if not self.omit_failures:
wrapper = _call
else:
wrapper = _try_call
res = list(config.tqdm(pool.imap(wrapper,
combinations,
chunksize=chunksize),
total=len(combinations),
desc=self.desc,
disable=config.pbar_hide or not self.progress,
leave=config.pbar_leave))
else:
res = []
for i, n in enumerate(config.tqdm(self.nl, desc=self.desc,
disable=(config.pbar_hide
or not self.progress
or len(self.nl) <= 1),
leave=config.pbar_leave)):
try:
res.append(self.funcs[i](*parsed_args[i], **parsed_kwargs[i]))
except BaseException as e:
if self.omit_failures:
res.append(FailedRun(func=self.funcs[i],
args=parsed_args[i],
kwargs=parsed_kwargs[i],
exception=e))
else:
raise
# Reset logger level to previous state
logger.setLevel(level)
failed = np.array([isinstance(r, FailedRun) for r in res])
res = [r for r in res if not isinstance(r, FailedRun)]
if any(failed):
logger.warn(f'{sum(failed)} of {len(self.funcs)} runs failed. '
'Set logging to debug (`navis.set_loggers("DEBUG")`) '
'or repeat with `omit_failures=False` for details.')
failed_ids = self.nl.id[np.where(failed)].astype(str)
logger.debug(f'The following IDs failed to complete: {", ".join(failed_ids)}')
# If result is a list of neurons, combine them back into a single list
is_neuron = [isinstance(r, (core.NeuronList, core.BaseNeuron)) for r in res]
if all(is_neuron):
return self.nl.__class__(utils.unpack_neurons(res))
# If results are all None return nothing instead of a list of [None, ..]
if np.all([r is None for r in res]):
res = None
# If not all neurons simply return results and let user deal with it
return res
|