Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import numpy as np
- def prepare_order(current, target):
- """
- precalc the reordering of axes
- this need only be done once
- note; we need to allow for ... operator still.
- left of ... in target have plus or minus sign respectively
- """
- def calc(t):
- r = tuple(i for i,v in enumerate(current) if v==t) #all locactions of t in current
- if len(r)==0:
- return None
- if len(r)==1: #most common case; unpack for readability and performance
- return r[0]
- return r
- return map(calc, target)
- def reform(arr, current, target):
- """
- use as_strided to map current axes layout to target axes layout
- prepare an order object
- then apply it
- """
- order = prepare_order(current, target)
- def calc(o):
- if o is None: return (1,0) #broadcasting axis
- if isinstance(o, int): return arr.shape[o],arr.strides[o] #transposed axes
- return arr.shape[o[0]],sum(arr.strides[i] for i in o) #diag axis
- layout = map(calc, order)
- shape, strides = zip(*layout)
- return np.lib.index_tricks.as_strided(arr, shape, strides)
- Q = np.arange((3*3*3)).reshape(3,3,3)
- #reorder axes
- print reform(Q, ['a','b','c'], ['b','c','a'])
- #view higher order diagonal
- print reform(Q, ['a','a','a'], ['a'])
- #broadcast left and right
- Q = np.arange(3)
- print reform(Q, ['a'], ['a','b'])
- print reform(Q, ['a'], ['b','a'])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement