dkq.py 5.35 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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
126
127
128
"""
python program for quering MNP draagkracht file
Hans Roelofsen, jan 2022
"""

import pandas as pd
import os

from fix_bt import fix_bt
from snl_beheertypen import get_snl_beheertypen_list
from snl_beheertypen import btcode2description
from Classes import Species as species
# from Classes.Species import TabSpeciesInstance as mnps

species_table = species.TabularSpecies()

class DraagKracht:

    def __init__(self):
        self.dkdir = r'W:\PROJECTS\QMAR\MNP-SNL-ParameterSet\Parameters_v05_2021_04_08'
        self.defaultdk = r'03_MNP_versie5_par_density_factors_BT2021_v3.csv'
        self.snl_bt = get_snl_beheertypen_list(of='full')
        self.use_default = True
        self.bt_column = 'Land_type_code'
        self.dk = None

    def read_dk(self, dk_file='default', bt_column=None):
        """
        Read a draagkrachten file
        :param dk_file: name of a draagrkachten file
        :param bt_column: name of column in non-default file with BT codes
        :return: pd dataframe
        """

        if dk_file != 'default':
            self.use_default = False
            self.bt_column = bt_column
            target = dk_file
        else:
            target = self.defaultdk
        setattr(self, "dk", pd.read_csv(os.path.join(self.dkdir, target)))

    def query4bt(self, bt_lst: list, of, sp_sel='281'):
        """
        query the draagkrachten for a specific beheertype
        :param bt_lst: beheertype code
        :param of: output format
        :param sp_sel: use which species list? 1018, 468 or 281?
        :return: str to stdout
        """

        for bt in bt_lst:
            query = '({0} in {1}) and selection == True'.format(self.bt_column, [fix_bt(bt, as_mnp=True)])
            sel = self.dk.assign(selection=self.dk.Species_code.map(getattr(species_table, 'code2sel{}'.format(sp_sel)))) \
                      .query(query)
            counts = sel.Species_code.map(species_table.code2taxon).value_counts()
            print('{0}-{1}: {2} vogel, {3} vlinder {4} plant. {5} total (out of {6}).'\
                  .format(bt, btcode2description(bt), counts.get('V', 0), counts.get('E', 0), counts.get('P', 0),
                          sel.shape[0], sp_sel if sp_sel != 'all' else '1081'))

            if of == 'full':
                print(sel.assign(local=sel.Species_code.map(species_table.code2local),
                                 taxon=sel.Species_code.map(species_table.code2taxon))\
                         .sort_values(by=['taxon', 'local']) \
                         .loc[:, ['Species_code', 'taxon', 'Land_type_quality', 'local']] \
                         .to_csv(sep='\t', index=False, header=False))

    def query4species(self, species_lst: list, of):
        """
        query draagkrachten for one or more species
        :param species_lst:
        :param of:
        :return:
        """

        for x in species_lst:
            sp = species.IndividualSpecies(x)
            query = 'Species_code in ["{0}"]'.format(sp.code)
            sel = self.dk.query(query)
            print("{0} ({1}-{2}. Listed in: {3}): {4} beheertypen".format(sp.local, sp.scientific, sp.code,
                                                                          sp.groupinfo, sel.shape[0]))
            if of == 'full':
                print(sel.assign(desc=getattr(sel, self.bt_column).map(btcode2description)) \
                         .loc[:, ['Land_type_quality', self.bt_column, 'desc']] \
                         .sort_values(by=self.bt_column) \
                         .to_csv(sep='\t', index=False, header=False))


if __name__ == '__main__':
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument('--qbt', nargs='+', type=str)
    parser.add_argument('--qsp', nargs='+', type=str)
    parser.add_argument('--of', choices=['full', 'sparse'], default='full')
    parser.add_argument('--sp_list', choices=['281', '468', '146', 'all'], default='281', type=str)
    args = parser.parse_args()

    hans = DraagKracht()
    hans.read_dk()
    if args.qbt:
        hans.query4bt(bt_lst=args.qbt, of=args.of, sp_sel=args.sp_list)
    if args.qsp:
        hans.query4species(species_lst=args.qsp, of=args.of)



# d = {'S02': 'V',
#      'S06': 'E',
#      'S09': 'P'}
# full = pd.read_csv(r'w:\PROJECTS\QMAR\MNP-SNL-ParameterSet\Parameters_v06_2019_12_09\01_Base_species_name.csv', sep=',', comment='#')
# full.set_index(keys='Species_code', drop=False, inplace=True)
# full['taxon'] = full.index.str.slice(0,3).map(d)
# sel468 = pd.read_csv(r'W:\PROJECTS\QMAR\MNP-SNL-ParameterSet\Parameters_v05_2021_04_08\09_MNP_versie4_Group_Species_valid model_468.csv', sep=',', index_col='Species_code')
# sel281 = pd.read_csv(r'W:\PROJECTS\QMAR\MNP-SNL-ParameterSet\Parameters_v05_2021_04_08\09_MNP_versie4_Species_group_valid_model_280.csv', sep=',', index_col='Species_code')
# sel146 = pd.read_csv(r'W:\PROJECTS\QMAR\MNP-SNL-ParameterSet\Parameters_v06_2019_12_09\09_MNP_versie4_Species_group_valid_model_typisch_146.csv', sep=',', index_col='Species_code')
# in468 = full.index.intersection(sel468.index)
# in281 = full.index.intersection(sel281.index)
# in146 = full.index.intersection(sel146.index)
# full.loc[:, 'sel468'] = 0
# full.loc[in468, 'sel468'] = 1
# full.loc[:, 'sel281'] = 0
# full.loc[in281, 'sel281'] = 0
# full.loc[:, 'sel1018'] = 1
# full.loc[:, 'sel146'] = 0
# full.loc[in146, 'sel146'] = 1
# full.loc[:, 'selall'] = 1
# full.to_clipboard(sep=',', index=False)