forked from JostTim/pGenUtils
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathiters.py
More file actions
82 lines (67 loc) · 2.41 KB
/
iters.py
File metadata and controls
82 lines (67 loc) · 2.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# -*- coding: utf-8 -*-
"""Boilerplate:
Created on Mon Mar 30 17:48:42 2020
@author: Timothe
"""
#import sys
#import numpy as np
def argmax(iterable):
return max(enumerate(iterable), key=lambda x: x[1])[0]
def unique_pairs(a,b,redundant = False):
"""Produce pairs of values from two iterables"""
seen = set()
for i in a:
for j in b:
pair = sorted([i, j])
if repr(pair) not in seen:
seen.add(repr(pair))
if pair[0] != pair[1] or redundant :
yield pair
def nest_iter(dimension,current_dimension=None,slicing = False,**kwargs):
"""
Recursive function that produces a generator meant to yield nested index values to target every possible array sub_unit, whatever the number of provided dimensions
Parameters
----------
dimension : TYPE
DESCRIPTION.
current_dimension : TYPE, optional
Internal only parameter.
Specifies the current state of the iteration for the yielder.
The default is None.
slicing : Bool, optional
dimensions indices are returns in the format of a tuple of slices objects (for better compatibility with numpy arrays)
The default is False.
**kwargs : TYPE
DESCRIPTION.
Raises
------
StopIteration
DESCRIPTION.
Yields
------
TYPE
DESCRIPTION.
"""
if current_dimension is None :
current_dimension = [0,]*len(dimension)
slicing = kwargs.get("slices",False)
for i in range(dimension[len(dimension)-1]):
current_dimension[len(dimension)-1] = i
if slicing :
outuple = tuple()
for j in range(len(dimension)):
outuple = outuple + (slice(current_dimension[j],current_dimension[j]+1),)
yield outuple
else :
yield tuple(current_dimension)
for j in range(len(dimension)):
if current_dimension[j] == dimension[j]-1:
if j == 0 :
return #python 3.5 equivelent of raise StopIteration
#https://stackoverflow.com/questions/43617399/how-to-get-rid-of-warning-deprecationwarning-generator-ngrams-raised-stopiter
for u in range(j,len(dimension)):
current_dimension[u] = 0
current_dimension[j-1] = current_dimension[j-1] + 1
yield from nest_iter(dimension,current_dimension,slicing)
if __name__ == "__main__":
pass