MCMC.py 6 KB
Newer Older
Dumoulin Nicolas's avatar
Dumoulin Nicolas committed
1
2
3
4
5
6
7
8
9
10
11
12
13
#!/usr/bin/python
# -*- coding: utf-8 -*-
import pandas as pd
import geopandas as gpd
import os, sys
import yaml
import numpy as np
from proximite import Proximite
from resilience_list import Resilience
from productivite import Productivity
from indice_biodiversite_2 import Biodiversity
from social import Social
from tqdm import tqdm
14
from patutils import md5sum
Dumoulin Nicolas's avatar
Dumoulin Nicolas committed
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46

class Scenario:
    def __init__(self, patches):
        self.patches = patches

    def load_shp(shpfilename):
        '''
        Return an instance of class Patches by loading a shapefile of initial patches.
        '''
        scenario = Scenario(gpd.GeoDataFrame.from_file(shpfilename, encoding='utf-8'))
        scenario.patches['init_cult'] = scenario.patches['cultgeopat']
        return scenario

    def reallocate(self, rng, targetPAT, ratioNbPatches):
        nbPatches = int(len(self.patches)*ratioNbPatches)
        surfDelta = targetPAT - self.patches.groupby('cultgeopat')['SURF_PARC'].sum()
        cult_to_decrease = surfDelta[surfDelta<0].sort_values(ascending=True).keys().tolist()
        cult_to_increase = surfDelta[surfDelta>0].sort_values(ascending=False).keys().tolist()
        # Sampling the patches to reallocate
        samples = self.patches[self.patches['cultgeopat'].isin(cult_to_decrease)].sample(n=nbPatches, random_state=rng)#.reset_index(drop=True)
        # Building the new culture reallocated
        factors = surfDelta[cult_to_increase]
        factors = (factors*len(samples)/factors.sum()).map(round) # normalize on nb samples
        newCult = pd.Series(cult_to_increase).repeat(factors)
        if len(newCult) < len(samples): # may be due to factors rounding
            newCult = newCult.append(newCult.sample(n=len(samples)-len(newCult), random_state=rng), ignore_index=True)
        newCult = newCult.sample(frac=1, random_state=rng)[:len(samples)].reset_index(drop=True) # shuffle and cut extra elements
        # Doing the reallocation
        self.patches.loc[samples.index.values,'cultgeopat'] = newCult.values

class Indicators:
    def __init__(self, config, initial_patches, patches_md5sum, targetPAT):
47
        self._proximity = Proximite(None, initial_patches, None, targetPAT)
Dumoulin Nicolas's avatar
Dumoulin Nicolas committed
48
49
        self._resilience = Resilience(config['resilience'], initial_patches)
        self._productivity = Productivity()
50
51
        self._biodiversity = Biodiversity(config['biodiversity'], initial_patches, patches_md5sum)
        self._social = Social(config['social'], initial_patches, patches_md5sum)
Dumoulin Nicolas's avatar
Dumoulin Nicolas committed
52
53
54
55
56
57
58
59
60
61
62
63
64
        self.indicators_names = ['proximity', 'resilience', 'productivity', 'biodiversity', 'social']

    def compute_indicators(self, patches):
        return [self.proximity(patches), self.resilience(patches),
                self.productivity(patches), self.biodiversity(patches), self.social(patches)]

    def compute_indicators_pool(self, scenarios):
        rows=[]
        for patches in scenarios:
            rows.append(self.compute_indicators(patches))
        return pd.DataFrame(rows, columns=self.indicators_names)

    def proximity(self, patches):
65
        return self._proximity.compute_indicator(patches)
Dumoulin Nicolas's avatar
Dumoulin Nicolas committed
66
67

    def resilience(self, patches):
68
	       return self._resilience.compute_indicator(patches)
Dumoulin Nicolas's avatar
Dumoulin Nicolas committed
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125

    def productivity(self, patches):
	       return self._productivity.compute_indicator(patches)

    def biodiversity(self, patches):
	       return self._biodiversity.compute_indicator(patches)

    def social(self, patches):
        return self._social.compute_indicator(patches)

class MCMC:
    def __init__(self, mcmc_config_filename):
        if not os.path.isfile(mcmc_config_filename):
        	print('Error: file not found "{}"'.format(mcmc_config_filename))
        	print('Please copy the template file "MCMC_config.sample.yml" and adjust to your settings and run again this program')
        	sys.exit(1)
        self.mcmc_config = yaml.load(open(mcmc_config_filename,'r'))
        if 'rng_seed' in self.mcmc_config:
            self.rng = np.random.RandomState(self.mcmc_config['rng_seed'])
        else:
            self.rng = np.random.RandomState(42)
            print('MCMC initialized with default seed') # self.rng.get_state()
        self.patches_md5sum = md5sum(self.mcmc_config['patches'])
        self.patches = gpd.GeoDataFrame.from_file(self.mcmc_config['patches'], encoding='utf-8')
        self.patches = self.patches[self.patches['cultgeopat']!='Non Considérée']
        self.patches['init_cult'] = self.patches['cultgeopat']
        self.target = pd.read_csv(self.mcmc_config['target'], sep=';',index_col=0)
        targetRatio = (self.target['2050']-self.target['2016'])/self.target['2016']
        self.targetPAT = self.patches.groupby('cultgeopat')['SURF_PARC'].sum()*(1+targetRatio)
        self.indicators = Indicators(self.mcmc_config['indicators_config'], self.patches, self.patches_md5sum, self.targetPAT)

    def run(self):
        # Initial sampling and evaluation
        scores = []
        for i in tqdm(range(self.mcmc_config['initial_nb_particles'])):
            scenario = Scenario(self.patches.copy()) # 0.2 ms
            scenario.reallocate(self.rng, self.targetPAT, self.mcmc_config['ratio_patches_to_modify']) # 3.8 ms
            scores.append(self.indicators.compute_indicators(scenario.patches))
        scores = pd.DataFrame(scores, columns=self.indicators.indicators_names)
        scores.to_csv('../output/mcmc2.csv')
        # TODO
        # Storing variation of indicators
        init_var = scores.std()
        # Selecting particles
        # sequential optimization loop

if __name__ == '__main__':
    # scenario = Scenario.load_shp('../output/PAT_patches/PAT_patches.shp')
    # target = pd.read_csv('../resources/targetPAT.csv', sep=';',index_col=0)
    # targetRatio = (target['2050']-target['2016'])/target['2016']
    # targetPAT = scenario.patches.groupby('cultgeopat')['SURF_PARC'].sum()*(1+targetRatio)
    # rng = np.random.RandomState()
    # scenario.reallocate(rng, targetPAT, 50)
    mcmc = MCMC('MCMC_config.yml')
    mcmc.run()
    # print(mcmc.indicators.biodiversity(mcmc.patches))
    # print(mcmc.indicators.proximity(mcmc.patches))