#!/usr/bin/python3 # -*- coding: utf-8 -*- import pandas as pd class Social: ''' This function is used to calculate the social indice. The idea is to propose a transition matrix for each type of culture and use it to visualize the conversion cost of the total conversion between the initial scenario and the old one. Each transition has a value between 0 and 1. These values were defined during reunions and with the review of our experts. ''' def __init__(self, initial_patches, cost_matrix_filename, bdv_threshold): ''' :param cost_matrix_filename input file containing the matrix in CSV format (separator: \t) :param bdv_threshold proportion of a cultural type needed for considering that this cultural type is suffisantly present in the locality for ignoring the conversion cost. ''' self.matrice_transition = pd.read_csv(cost_matrix_filename, sep='\t',index_col=0) self.bdv_threshold = bdv_threshold self.initial_patches = initial_patches[['ID_PARCEL','cultgeopat']] def compute_indicator(self, scenario_patches): ''' :param initial_patches: Initial patches :param scenario: The scenario to analyse ''' cost = 0 filter1 = pd.merge( scenario_patches[['ID_PARCEL','cultgeopat','Bdv','SURF_PARC','id_expl']], self.initial_patches, on='ID_PARCEL') for bdv,grouped in filter1.groupby('Bdv'): grouped=grouped.copy() surfaces_initial = grouped.groupby('cultgeopat_y')['SURF_PARC'].sum() cult_threshold = surfaces_initial > surfaces_initial.sum() * self.bdv_threshold filter2 = grouped[grouped['cultgeopat_y'] != grouped['cultgeopat_x']] for i,row in filter2.iterrows(): # patches that have different farming that others in same Bdv if cult_threshold[row['cultgeopat_y']]: # patches that have different farming that others of the same farmer if row['cultgeopat_y'] not in filter1[filter1['id_expl']==row['id_expl']]['cultgeopat_x']: cost += self.matrice_transition[row['cultgeopat_x']][row['cultgeopat_y']] return cost if __name__ == '__main__': import geopandas as gpd patches = gpd.GeoDataFrame.from_file("../output/PAT_patches/PAT_patches.shp", encoding='utf-8') scenario_patches = patches.copy() scenario_patches.ix[2,'cultgeopat']='Protéagineux' social = Social(patches, '../resources/matrice_transition.csv', 0.1) print(social.compute_indicator(scenario_patches)) # should give 0.5 the cost for one transition to Protéagineux