MCMC.py 5.87 KB
Newer Older
Dumoulin Nicolas's avatar
Dumoulin Nicolas committed
1
2
3
4
5
6
7
#!/usr/bin/python
# -*- coding: utf-8 -*-
import pandas as pd
import geopandas as gpd
import os, sys
import yaml
import numpy as np
8
9
10
from Indicator import Indicator
from overrides import overrides
from proximite import Proximite as Proximity
Dumoulin Nicolas's avatar
Dumoulin Nicolas committed
11
12
13
14
15
from resilience_list import Resilience
from productivite import Productivity
from indice_biodiversite_2 import Biodiversity
from social import Social
from tqdm import tqdm
16
from patutils import md5sum
Dumoulin Nicolas's avatar
Dumoulin Nicolas committed
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

47
48
49
50
51
52
53
54
55
class CulturalIndicator(Indicator):
    @overrides
    def __init__(self, config, initial_patches=None, patches_md5sum=None, targetPAT=None):
        self.cultgeopat = config

    @overrides
    def compute_indicator(self, patches):
        return patches[patches['cultgeopat']==self.cultgeopat]['SURF_PARC'].sum()

Dumoulin Nicolas's avatar
Dumoulin Nicolas committed
56
57
class Indicators:
    def __init__(self, config, initial_patches, patches_md5sum, targetPAT):
58
59
60
61
62
63
64
65
        self._indicators = {
            indicator.lower(): eval(indicator)(config.get(indicator.lower()), initial_patches, patches_md5sum, targetPAT)
            for indicator in ['Proximity', 'Resilience', 'Productivity', 'Biodiversity', 'Social']
            }
        self.indicators_names = list(self._indicators.keys())
        for cultgeopat in targetPAT.index.tolist():
            self._indicators[cultgeopat] = CulturalIndicator(cultgeopat)
            self.indicators_names.append(cultgeopat)
Dumoulin Nicolas's avatar
Dumoulin Nicolas committed
66
67

    def compute_indicators(self, patches):
68
        return [ind.compute_indicator(patches) for ind in self._indicators.values()]
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

    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)

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))