import numpy as np
import pandas as pd

from .BaseMatrix import BaseMatrix

class SudarshanIyengar(BaseMatrix):
    ''' Calculates Vulnerability Index using Sudarshan & Iyengar's method (1982)
        
        Attributes:
            df (DataFrame) takes a pandas dataframe containing Vulnerability Indicators for given region
            relations (list or dict) of functional relation of indicators to vulnerability 
            scaled_df (DataFrame) Calculates scled DF based on indicator relations using UNDP's method for HDI calculation
            Wj (Series) of weights corresponding to each indicator
    '''
    
    def __init__(self, df, relations):
        BaseMatrix.__init__(self, df)
        self.relations = relations
        self.feed_indicator_relations(relations)
        self.scaled_df = self.calculate_scaled_df()
        
    def calculate_weights(self):
        '''Calulates weights corresponding to each indicator
        
            Args:
                None
            Returns:
                Series of weights with corresponding indicators as indices
                   
        '''
        
        W = np.sqrt(1/self.scaled_df.var())
        c = sum(np.sqrt(1/self.scaled_df.var()))**-1
        self.Wj = W*c
        return W*c
    
    def vi_matrix(self):
        ''' Calculates the Vulnerability Index Matrix
            
            Args:
                None
            Returns:
                vi_matrix (DataFrame) the product of weights and scaled dataframe  
            
        '''
        
        vi_matrix = self.scaled_df * self.calculate_weights()
        return vi_matrix
    
    def DevelopmentLevel(self):
        ''' Calulates the development level by summing over performances with resepct to various indicators for each region
            
            Args:
                None
            Returns:
                Development Level (Series) containing Development level of each region
        '''
        
        return self.vi_matrix().sum(axis=1)
    
    def rank(self):
        ''' Ranks the regions by the Development Level
            
            Args:
                None
            Returns:
                Rank (Series) of different regions in terms of vulnerability 
        '''
        
        return self.DevelopmentLevel().rank(ascending=False)
        
    