# -*- coding: utf-8 -*-
"""
Created on Tue Sep  9 14:29:38 2014

@author: jussi
"""

import scipy.io
import numpy as np

sum = np.sum

class Sensorarray:
    """ Generic sensor array class. """

    def __init__(self,datafile):
        """ Load specified sensor definition data from .mat file. """
        sdict = scipy.io.loadmat(datafile)
        self.datafile = datafile
        # must-have variables
        # TODO: rename variables?
        varset = {'Ipm','Iam','Snaug','Sc','Ipind'}
        if not sdict.keys() >=  varset:
            raise Exception('Sensor data file has missing variables')
        # optional variables
        optvars = {'Sx','Sy','Sf','Sn','Ip','Ia'}       
        # pick optional variables that actually exist in the data
        optvarset = sdict.keys() & optvars
        # set object attributes
        for x in varset:
            setattr(self,x,sdict[x])
        for x in optvarset:
            setattr(self,x,sdict[x])
        
        self.NIp = np.size(self.Ipm,0)
        self.Nsens = np.size(self.Ipind,0)
        
        
    def signalvec(self,source):
        """ Computes the signal vector corresponding to a specified source,  giving the response of each sensor. """
        # field at integration points dotted with normals and weighted by Iam
        sigall = self.Iam.flatten()*np.einsum('ij,ij->i',source.field(self.Ipm),self.Snaug)
        Itmp = np.zeros(np.shape(self.Ipind))
        # pick appropriate values and sum; -1 for zero-based indexing
        Itmp[np.nonzero(self.Ipind)] = sigall[self.Ipind[np.nonzero(self.Ipind)]-1]
        sigvec = sum(Itmp,1)        
        return sigvec

    def render():
        """ Render the sensors. mayavi for visualizations? """
    
    def multipolebasis():
        """ Compute a multipole basis for this array. """

    def info(self):
        """  Print some information about the sensor model. """
        print("Number of sensors:",self.Nsens)
        print("Total integration points:",self.NIp)

class Triplesensorarray(Sensorarray):
    """ Sensor array class for arrays with Elekta triple-sensors, comprising a magnetometer and two orthogonal gradiometers.
    """
    def __init__(self,datafile):
        Sensorarray.__init__(self,datafile)
        self.magscale = 100
        

        