Ejemplo n.º 1
0
    def create_climate_covariates(self, climate_dir, start_year, end_year,
                                  key_min, key_max, key_pcp, out_dir):
        abstemp = 273.15

        year_list = cc.getYearList(start_year, end_year)
        climate_covariate = cc.ClimaticCovariates(year_list, climate_dir)
        ref_raster = climate_covariate.ref_raster

        out_raster = Raster()

        crops_id = []
        crops = []

        with self.conn as cur:
            rows = cur.execute("select * from crop").fetchall()

        if rows:
            print('Start to generate climate covariates...')
            for row in rows:
                crops_id.append(row['id'])
                crops.append(row['crop'])

            for crop_id, crop in zip(crops_id, crops):

                print(crop)
                with self.conn as cur:
                    covariates = cur.execute(
                        "select * from covariate_threshold where crop_id=?",
                        (crop_id, )).fetchall()

                if covariates:
                    for covariate in covariates:
                        with self.conn as cur:
                            covariate_name = cur.execute(
                                "select covariate from Covariate where id=?",
                                (covariate['covariate_id'],
                                 )).fetchone()['covariate']
                        print('Generate {} at {} ...'.format(
                            covariate_name, dt.datetime.now()))

                        if covariate['t_below'] is not None:
                            try:
                                t_below = float(covariate['t_below']) + abstemp
                            except ValueError:
                                t_below = None
                        else:
                            t_below = None

                        if covariate['t_above'] is not None:
                            try:
                                t_above = float(covariate['t_above']) + abstemp
                            except ValueError:
                                t_above = None
                        else:
                            t_above = None

                        if covariate['pcp_above'] is not None:
                            try:
                                pcp_above = float(covariate['pcp_above'])
                            except ValueError:
                                pcp_above = None
                        else:
                            pcp_above = None

                        if covariate['pcp_below'] is not None:
                            try:
                                pcp_below = float(covariate['pcp_below'])
                            except ValueError:
                                pcp_below = None
                        else:
                            pcp_below = None

                        out_sub_dir = join(out_dir, crop)
                        if not os.path.exists(out_sub_dir):
                            os.makedirs(out_sub_dir, exist_ok=True)

                        covariate_array = cc.generate(
                            covariate['covariate_id'], year_list, climate_dir,
                            covariate['start_date'], covariate['end_date'],
                            key_min, key_max, key_pcp, t_below, t_above,
                            pcp_above, pcp_below, out_sub_dir, crop_id,
                            covariate['covariate_id'], ref_raster)

                        try:
                            if covariate_array is not None:

                                out_raster_file = join(
                                    out_sub_dir, '{}_{}_{}_{}.tif'.format(
                                        crop_id, covariate['covariate_id'],
                                        start_year, end_year))
                                out_raster.array2Raster(
                                    covariate_array, ref_raster,
                                    out_raster_file)
                        except:
                            pass
Ejemplo n.º 2
0
    def mapping(self, crop_id, covariate_rasters, conn, covariate_root_dir,
                suit_root_dir):

        raster = Raster()
        self.no_data = raster.getNoDataValue(covariate_rasters[-1])
        ref_rst = covariate_rasters[-1]
        covariate_id_list = []
        suit_array_stack = []

        filepath = strip_end(ref_rst, ref_rst.split('\\')[-1])
        out_dir = join(
            suit_root_dir,
            strip_start(filepath, covariate_root_dir)[1:]
        )  # the [1:] is for removing the first and the last '\' of string

        if not os.path.exists(out_dir):
            os.makedirs(out_dir, exist_ok=True)

        for rst in covariate_rasters:

            filename = rst.split('\\')[-1].split('.')[0]

            if len(filename.split('_')) == 1:
                covariate_id = filename
                covariate_id_list.append(covariate_id)
                out_raster = join(
                    out_dir,
                    'suitability_{}_{}.tif'.format(crop_id, covariate_id))
            else:
                covariate_id = filename.split('_')[1]
                covariate_id_list.append(covariate_id)
                time_span = '{}_{}'.format(
                    filename.split('_')[-2],
                    filename.split('_')[-1])
                out_raster = join(
                    out_dir,
                    'suitability_{}_{}_{}.tif'.format(crop_id, covariate_id,
                                                      time_span))

            with conn as cur:
                rows = cur.execute(
                    "select * from suitability_rule where crop_id=? and covariate_id=? order by suitability_level",
                    (
                        crop_id,
                        covariate_id,
                    )).fetchall()
                is_continual = cur.execute(
                    "select * from Covariate where id=?",
                    (covariate_id, )).fetchone()['iscontinual']

            # If the query returns none then move to the next covariate
            if rows:
                covariate_array = raster.getRasterArray(
                    rst)  # array of the covariate

                if is_continual == 1:
                    suit_array = self.__reclassify_contianual__(
                        covariate_array, rows)
                else:
                    suit_array = self.__reclassify_catorgorical__(
                        covariate_array, rows)

                suit_array[np.where(
                    covariate_array == self.no_data)] = self.no_data

                raster.array2Raster(suit_array, ref_rst, out_raster)

                suit_array_stack.append(suit_array)
            else:
                print(
                    'Warning! Suitability ruleset for {}, {} not found! Please check the database.'
                    .format(crop_id, covariate_id))

        if len(suit_array_stack) > 0:
            crop_suit_array = ExtractMaxValueOfStack(suit_array_stack)
            ref_array = homogenize_nodata_area(suit_array_stack, self.no_data)
            crop_suit_array[np.where(ref_array == self.no_data)] = self.no_data
            crop_suit_raster = join(out_dir,
                                    '{}_suitability.tif'.format(crop_id))
            raster.array2Raster(crop_suit_array, ref_rst, crop_suit_raster)

            print('create dominant worst covariate raster at {}...'.format(
                dt.datetime.now()))
            worst_dominant_array, worst_count_array, worst_dominant_legend_list = ExtractMaxValueIndexBinaryOfStack(
                suit_array_stack, covariate_id_list, 4)

            worst_dominant_array[np.where(
                ref_array == self.no_data)] = self.no_data
            worst_dominant_raster_file = join(
                out_dir, '{}_worst_dominant.tif'.format(crop_id))
            raster.array2Raster(worst_dominant_array, ref_rst,
                                worst_dominant_raster_file)

            worst_count_array[np.where(
                ref_array == self.no_data)] = self.no_data
            worst_count_raster_file = join(
                out_dir, '{}_worst_count.tif'.format(crop_id))
            raster.array2Raster(worst_count_array, ref_rst,
                                worst_count_raster_file)

            worst_dominant_legend_csv = join(
                out_dir, '{}_worst_dominant_legend.csv'.format(crop_id))
            csvw = CSVOperation.CSVWriting()
            headers = ['raster value', 'number of restriction', 'covariates']
            csvw.WriteLines(worst_dominant_legend_csv, headers,
                            worst_dominant_legend_list)
        else:
            print('Warning! No suitability map for {} was created!'.format(
                crop_id))