#!/usr/bin/env python
# -*- coding: utf-8 -*-
# generated by wxGlade 0.6 on Sun May 25 23:31:23 2008

# Copyright 2008 Martin Manns
# Distributed under the terms of the GNU General Public License
# generated by wxGlade 0.6 on Mon Mar 17 23:22:49 2008

# --------------------------------------------------------------------
# pyspread is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# pyspread is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with pyspread.  If not, see <http://www.gnu.org/licenses/>.
# --------------------------------------------------------------------

"""
_array_helper
=============

Provides:
---------
\tgetflatpos:   Gets Fortran style positions in flattened array
\tgetshapedpos: Gets Fortran style position in shaped array

"""

from itertools import izip
from operator import mul

def getflatpos(array, pos):
    """Get index of a cell in a flattened numpy array in Fortran order."""
    
    ashape = array.shape
    arange = xrange(1, len(ashape))
    
    cumgsr = [1]
    cumgsr += [reduce(mul, ashape[:i]) for i in arange]
    
    return sum(p * e for p, e in izip(pos, cumgsr))

def getshapedpos(array, pos):
    """Get cell index from a flattened array index in Fortran order."""
    
    shape = array.shape
    
    def _rek(i, pos):
        """Recursion that calculates one dimension per step"""
        
        try:
            currpos = pos % shape[i]
        except IndexError:
            return []
        
        return [currpos] + _rek(i+1, pos // shape[i])
        
    return tuple(_rek(0, pos))
