social.py 2.53 KB
Newer Older
1
2
#!/usr/bin/python3
# -*- coding: utf-8 -*-
3
import pandas as pd
4

5
class Social:
6
7
	'''
	This function is used to calculate the social indice.
8
9
	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.
10

11
12
13
	Each transition has a value between 0 and 1.
	These values were defined during reunions and with the review of our experts.
	'''
14

15
	def __init__(self, initial_patches, cost_matrix_filename, bdv_threshold):
16
17
18
19
20
21
22
		'''
		: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
23
		self.initial_patches = initial_patches[['ID_PARCEL','cultgeopat']]
24

25
	def compute_indicator(self, scenario_patches):
26
27
28
29
30
31
32
		'''
		: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']],
33
		 	self.initial_patches,
34
35
36
37
38
39
40
41
42
43
44
45
			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']]
46
		return 1/(1+cost)
47
48
49
50

if __name__ == '__main__':
	import geopandas as gpd
	patches = gpd.GeoDataFrame.from_file("../output/PAT_patches/PAT_patches.shp", encoding='utf-8')
51
	social = Social(patches, '../resources/matrice_transition.csv', 0.1)
52
	scenario_patches = patches.copy()
53
	print(social.compute_indicator(scenario_patches))
54
	scenario_patches.ix[2,'cultgeopat']='Protéagineux'
55
	print(social.compute_indicator(scenario_patches))
56
	# should give 0.5 the cost for one transition to Protéagineux
57
58
	scenario_patches['cultgeopat']='Fruits et légumes'
	print(social.compute_indicator(scenario_patches))