Skip to content
Snippets Groups Projects
03.Calc_coef.R 24.31 KiB
### R for RStudio*, utf8
### 30/10/2023 ALungarska

### This script calculates the coeficients for all combinations of CP, amm, and occsol
### BNVDs interface development app.

#### Parametres annuels ####
annees = paste(2015:2020)
ephy = "ephy_v6"

#### Fonctions et packages ####
library(tidyverse)
library(RPostgreSQL)
library(here)
library(readxl)

`%ni%` = Negate(`%in%`)

selfName = "obnvds/src/03.Calc_coef.R"

#### Connection to the psql database ####
source("src/00.connexion_sql.R")
con_rpsql = con_atelier


for (annee in annees){
  
  timestamp()
  print(annee)
  
  bdd_target = paste0("obnvds_", annee)
  
  ######################selection amm dans la base ephy##########################
  #amm dont les doses initiales dans ephy sont inconnues ou non spatialiables. 
  #On leur attribue la dose de 1kg/ha
  
  ### amm et unite dans le registre
  table_registre_bnvd = paste0("SELECT DISTINCT amm, conditionnement, eaj 
                               FROM ", bdd_target, ".bnvd_amm;") %>% 
    dbGetQuery(con_rpsql, .)
  
  #Verification si table existe
  if(dbExistsTable(con_rpsql, name = c(bdd_target, "amm_cult_dhom_ephy_initial"))){
    
    dbRemoveTable(con_rpsql, name = c(bdd_target, "amm_cult_dhom_ephy_initial"))
    
  }
  
  dbSendQuery(con_rpsql, paste0("CREATE TABLE ", bdd_target, ".amm_cult_dhom_ephy_initial AS
                          SELECT amm, unaccent_string(split_part(intitule,'*',1)) culture, 
                          dose_spatialisable AS dhom, unite_spatialisable AS unite 
	                        FROM base_amm.", ephy, " 
	                        WHERE dose_spatialisable IS NOT NULL 
                            AND split_part(intitule,'*',1) != 'Porte graine'  
                          ORDER BY amm, culture;"))
  
  ## rajoute les amm non spatialisées avec de dose=1 kg/ha
  amm_ns = dbGetQuery(con_rpsql, paste0("SELECT DISTINCT amm, unite_spatialisable
                                        FROM base_amm.", ephy, 
                                        " WHERE amm IN (
                                            SELECT DISTINCT amm
                                            FROM base_amm.", ephy, " 
                                            WHERE dose_spatialisable IS NULL
                                            AND split_part(intitule,'*',1) != 'Porte graine'
                                        );")) %>% 
    group_by(amm) %>% 
    tally() %>% 
    filter(n == 1) %>% 
    inner_join(table_registre_bnvd %>% 
                 select(-eaj), by = "amm") %>% 
    mutate(dhom = 1,
           unite = ifelse(conditionnement == "kg", "kg/ha", "L/ha")) %>% 
    select(amm, dhom, unite)
  
  amm_ns_add = dbGetQuery(con_rpsql, paste0("SELECT amm, unaccent_string(split_part(intitule,'*',1)) culture
                        FROM base_amm.", ephy, " 
                        WHERE amm IN (
                          '", paste(amm_ns$amm, collapse = "', '"), "'
                        ) AND split_part(intitule,'*',1) != 'Porte graine'
                        ORDER BY amm, culture;")) %>% 
    inner_join(amm_ns, by = "amm")
  
  dbWriteTable(con_rpsql, name = c(bdd_target, "amm_cult_dhom_ephy_initial"), 
                value = amm_ns_add, append = T, row.names = F)
  
  ###########selection des amm de la base ephy qui sont aussi dans le registre############

  amm_cult_dhom_ephy_select = dbGetQuery(con_rpsql, paste0("SELECT * FROM ", 
                                                           bdd_target, ".amm_cult_dhom_ephy_initial;"))
  amm_cult_dhom_ephy_select = amm_cult_dhom_ephy_select[
    which(amm_cult_dhom_ephy_select$amm %in% unique(table_registre_bnvd$amm)), ]
  
  ## on enleve les amm dont les usages sont strictement du traitement post recolte:
  ephy_table = dbGetQuery(con_rpsql, paste0("SELECT DISTINCT amm, split_part(intitule,'*',2) usage 
                                      FROM base_amm.", ephy, " 
                                      WHERE amm IN (
                                        SELECT DISTINCT amm 
                                        FROM base_amm.", ephy, " 
                                        WHERE intitule LIKE '%Trt Prod%'
                                      ) GROUP BY amm, usage  
                                      ORDER BY amm;"))
  
  ephy_table = aggregate(usage ~ amm, ephy_table, unique)
  
  produit_post_rec = amm_cult_dhom_ephy_select[
    which(amm_cult_dhom_ephy_select$amm %in% 
            ephy_table$amm[which(ephy_table$usage == "Trt Prod. Réc.")]), ]
  
  amm_cult_dhom_ephy_select = amm_cult_dhom_ephy_select[
    -which(amm_cult_dhom_ephy_select$amm %in% 
             unique(ephy_table$amm[which(ephy_table$usage == "Trt Prod. Réc.")])), ]
  
  ## on enleve les amm dont les usages sont strictement du trt généraux pour de la désinfection de matériel, etc:
  ephy_table = dbGetQuery(con_rpsql, paste0("SELECT DISTINCT amm, split_part(intitule, '*', 2) usage 
                                      FROM base_amm.", ephy, " 
                                      WHERE amm IN (
                                        SELECT DISTINCT amm 
                                        FROM base_amm.", ephy, " 
                                        WHERE intitule LIKE 'Traitement%'
                                      ) GROUP BY amm, usage 
                                     ORDER BY amm;"))
  
  ephy_table = aggregate(usage ~ amm, ephy_table, unique)
  
  produit_post_rec = rbind(produit_post_rec, amm_cult_dhom_ephy_select[
    which(amm_cult_dhom_ephy_select$amm %in%
            ephy_table$amm[which(ephy_table$usage %in% c("Désinsectisation",
                                                         "Fumigation (désinsectisation)", 
                                                         "Désinfection"))]), ])
  
  amm_cult_dhom_ephy_select = amm_cult_dhom_ephy_select[
    -which(amm_cult_dhom_ephy_select$amm %in%
             unique(ephy_table$amm[which(ephy_table$usage %in% c("Désinsectisation",
                                                                 "Fumigation (désinsectisation)", 
                                                                 "Désinfection"))])), ]
  
  dbWriteTable(con_rpsql, c(bdd_target, "produit_stockage_exclu"), 
               value = produit_post_rec, 
               append = FALSE, row.names = FALSE, overwrite = T)
  
  paste0("COMMENT ON TABLE ", bdd_target, ".produit_stockage_exclu  IS 'creation : ",
                   date(), " par ", username ," via le script ", selfName , "';") %>% 
    dbSendQuery(con_rpsql, .)
  
  ################# dose mediane par amm, culture, unite ########################
  
  amm_cult_dhmed = aggregate(dhom ~ amm + culture + unite, amm_cult_dhom_ephy_select, median)
  
  colnames(amm_cult_dhmed) = sub("dhom", "dhmed", colnames(amm_cult_dhmed))
  
  dbWriteTable(con_rpsql, c(bdd_target, "amm_cult_dhmed"), 
               value = amm_cult_dhmed, 
               append = FALSE, row.names = FALSE, overwrite = T)

  paste0("COMMENT ON TABLE ", bdd_target, ".amm_cult_dhmed  IS 'creation : ",
         date(), " par ", username ," via le script ", selfName , "';") %>% 
    dbSendQuery(con_rpsql, .)
  
  ######### on recupere les surfaces des cultures de saa ##########################
  
  saa_region = dbGetQuery(con_rpsql, paste0("SELECT substring(region from 3 for 4) region, 
                                     n306_lib AS cult_saa, origine, SUM(valeur) surface_ha 
                                     FROM agreste.saa_2010_2021 
                                     WHERE annref = '", annee, "' 
                                     GROUP BY region, cult_saa, origine;"))
  
  saa_region = saa_region[-which(saa_region$surface_ha == 0), ]
  
  ################## doses moyennes, ponderees par surface #######################
  
  
  ############################### calc_int #######################################
  conv_ephy_saa = dbGetQuery(con_rpsql, "SELECT unaccent_string(cult_ephy) cult_ephy, 
                            cult_saa, origine_saa, code_gp 
                            FROM donnees_references.conv_ephy6_saa_2010_2021 
                            WHERE code_gp NOT LIKE 'PP' 
                            AND code_gp NOT LIKE 'STH' 
                            AND code_gp NOT LIKE 'PT' 
                            AND code_gp NOT LIKE 'GEL';")
  
  
  amm_dhmed_cultephy_saa = left_join(amm_cult_dhmed, conv_ephy_saa, 
                                     by = c("culture" = "cult_ephy"),
                                     relationship = "many-to-many")
  
  amm_dhmed_cult_surf_saa = left_join(amm_dhmed_cultephy_saa, saa_region, 
                                      by = c("cult_saa" = "cult_saa"),
                                      relationship = "many-to-many")
  
  calc_int = aggregate(surface_ha ~ amm + region + culture + code_gp + unite + dhmed,
                        amm_dhmed_cult_surf_saa, sum)
  
  calc_int$sommeprod = calc_int$surface_ha * calc_int$dhmed
  colnames(calc_int)[7] = "surf_cult"
  colnames(calc_int)[4] = "occsol"
  
  ############################# dhref ###########################################
  
  amm_occsol_dhref = calc_int %>% 
    group_by(amm, region, occsol, unite) %>% 
    summarise(sum_sommeprod = sum(sommeprod, na.rm = T),
              sum_surf_cult = sum(surf_cult), 
              .groups = "drop")
  
  amm_occsol_dhref$dhref = amm_occsol_dhref$sum_sommeprod / amm_occsol_dhref$sum_surf_cult
  amm_occsol_dhref = amm_occsol_dhref[, -c(5, 6)]
  
  dbWriteTable(con_rpsql, c(bdd_target, "amm_occsol_dhref"), 
               value = amm_occsol_dhref, 
               append = FALSE, row.names = FALSE, overwrite = T)
  
  paste0("COMMENT ON TABLE ", bdd_target, ".amm_occsol_dhref  IS 'creation : ",
         date(), " par ", username ," via le script ", selfName , "';") %>% 
    dbSendQuery(con_rpsql, .)
  
  dbSendQuery(con_rpsql, paste0("CREATE INDEX i_amm2 ON ", bdd_target, ".amm_occsol_dhref(amm);"))
  dbSendQuery(con_rpsql, paste0("CREATE INDEX i_unit2 ON ", bdd_target, ".amm_occsol_dhref(unite);"))
  dbSendQuery(con_rpsql, paste0("CREATE INDEX i_occsol2 ON ", bdd_target, ".amm_occsol_dhref(occsol);"))
  dbSendQuery(con_rpsql, paste0("CREATE INDEX i_dhref2 ON ", bdd_target, ".amm_occsol_dhref(dhref);"))
  
  ###############################################################################################
  ####################################### TG ####################################################
  ###############################################################################################
  
  ############################## APPLICATION AGRICOLE ###########################################
  
  #insertion de csv des dhref et TG pour application agricole
  # amm_occsol_dhref = dbGetQuery(con_rpsql, paste0("SELECT * FROM ", bdd_target, ".amm_occsol_dhref;"))
  
  #Verification si table existe
  if(dbExistsTable(con_rpsql, name = c(bdd_target, "amm_traitementgeneraux_agri"))){
    
    dbRemoveTable(con_rpsql, name = c(bdd_target, "amm_traitementgeneraux_agri"))
    
  }
  
  dbSendQuery(con_rpsql, paste0("CREATE TABLE ", bdd_target, ".amm_traitementgeneraux_agri AS
                            SELECT DISTINCT amm FROM base_amm.", ephy, " 
                            WHERE LEFT(split_part(intitule, '*', 1), 11) = 'Traitements' 
                            AND (gamme_usages = 'Professionnel' OR gamme_usages IS NULL)  
                            ORDER BY amm;"))
  
  #Verification si table existe
  if(dbExistsTable(con_rpsql, name = c(bdd_target, "dhmed_traitementsgeneraux"))){
    
    dbRemoveTable(con_rpsql, name = c(bdd_target, "dhmed_traitementsgeneraux"))
    
  }
  
  dbSendQuery(con_rpsql, paste0("CREATE TABLE ", bdd_target, ".dhmed_traitementsgeneraux AS
	                          SELECT * FROM ", bdd_target, ".amm_cult_dhmed 
	                          WHERE amm IN (
	                            SELECT amm FROM ", bdd_target, ".amm_traitementgeneraux_agri
	                          ) AND culture LIKE '%raitements%' 
	                          AND amm NOT IN (
	                          SELECT DISTINCT amm FROM ", bdd_target, ".produit_stockage_exclu
	                          ) ORDER BY 1;"))
  
  dhmed_traitementsgeneraux = dbGetQuery(con_rpsql, 
                                         paste0("SELECT * FROM ", bdd_target, ".dhmed_traitementsgeneraux;"))
  
  
  #creation des vecteurs pour les classes d'occupation du sol (creees par camille) + regions
  vect_occsol = c("BETT", "BLE", "CEREALES", "COLZA", "COQUE", "DIVERS", "FEV", 
                  "FIBRE", "FOURR", "INDUS", "LEGU", "LFOURR", "LGRAIN", "MAIS",
                  "OLEA", "OLIVE", "ORGE", "PDT", "POIS", "PROTEA", "RIZ", "SOJA",
                  "TOUR", "VERGERS", "VIGNES")
  
  if (annee == 2021){
    
    vect_reg = c("11", "24", "27", "28", "32", "44", "52", 
                  "53", "75", "76", "84", "93", "94")  
    
  } else {
    vect_reg = c("01", "02", "03", "04", "06", "11", "24", "27", "28", 
                  "32", "44", "52", "53", "75", "76", "84", "93", "94")
    #vect_reg<-paste("R",vect_reg,sep="")
  }
  
  # application des produits en TG sur les differentes occupations du sol, pour toutes les regions. sortie: amm_occsol_dhref_tg
  amm = dhmed_traitementsgeneraux$amm
  unite = dhmed_traitementsgeneraux$unite
  dhmed = dhmed_traitementsgeneraux$dhmed
  
  tab_amm = data.frame(amm = amm[gl(length(amm), length(vect_occsol) * length(vect_reg))], 
                       unite = unite[gl(length(unite), length(vect_occsol) * length(vect_reg))],
                       dhref = dhmed[gl(length(dhmed), length(vect_occsol) * length(vect_reg))]) 
  
  region = rep(vect_reg[gl(length(vect_reg), length(vect_occsol))], times = length(amm))
  occsol = rep(vect_occsol, length(amm) * length(vect_reg)) 
  amm_occsol_dhref_tg = cbind(tab_amm, region, occsol)
  
  
  #on regroupe les deux tableaux pour pouvoir faire une moyenne des dhref pour chaque amm+region+occsol 
  amm_occsol_dhref_tg = rbind(amm_occsol_dhref, amm_occsol_dhref_tg)
  amm_occsol_dhref_2 = aggregate(dhref ~ amm + region + occsol + unite, amm_occsol_dhref_tg, mean)
  
  
  ############### APPLICATION NON AGRICOLE - professionnel ######################
  
  amm_cult_dhmed = dbGetQuery(con_rpsql, paste0("SELECT * FROM ", bdd_target, ".amm_cult_dhmed;"))
  
  amm_zna_pro = amm_cult_dhmed[which(amm_cult_dhmed$culture %in% c("Traitements generaux",
                                                                   "Usages non agricoles", 
                                                                   "JEVI")), ]
  
  amm_zna_pro_mean = as.data.frame(aggregate(dhmed ~ amm + unite, amm_zna_pro, mean))
  
  amm_zna_pro_dhref = amm_zna_pro_mean[rep(1:nrow(amm_zna_pro_mean), length(vect_reg)), ]
  amm_zna_pro_dhref[, "region"] = vect_reg[gl(length(vect_reg), length(unique(amm_zna_pro_mean$amm)))]
  amm_zna_pro_dhref[, "occsol"] = "zna_pro"
  colnames(amm_zna_pro_dhref) = sub("dhmed", "dhref", colnames(amm_zna_pro_dhref))
  
  #on rajoute au tableau contenant les dhref des cultures les dhref des zna_pro
  amm_occsol_dhref_2 = rbind(amm_occsol_dhref_2, amm_zna_pro_dhref)
  
  ################ APPLICATION NON AGRICOLES - non professionnel  #################
  
  amm_ZNA_non_pro_dhmed = dbGetQuery(con_rpsql, paste0("SELECT * FROM ", bdd_target, ".amm_cult_dhmed 
                                                WHERE (culture LIKE 'Jardin%' 
                                                      OR culture LIKE 'Trai%' 
                                                      OR culture LIKE 'Usa%');"))
                                                      # OR culture LIKE 'JEVI%');")) # Issue #2 GIT
  
  amm_ZNA_non_pro_dhmed = amm_ZNA_non_pro_dhmed[
    which(amm_ZNA_non_pro_dhmed$amm %in% 
            unique(table_registre_bnvd$amm[which(table_registre_bnvd$eaj == "Oui")])), ]
  
  amm_ZNA_non_pro_dhref = aggregate(dhmed ~ amm + unite, amm_ZNA_non_pro_dhmed, mean)
  
  amm_ZNA_non_pro_dhref[, 'occsol'] = "zna_non_pro"
  amm_ZNA_non_pro_dhref = amm_ZNA_non_pro_dhref[rep(1:nrow(amm_ZNA_non_pro_dhref), length(vect_reg)), ]
  amm_ZNA_non_pro_dhref[, "region"] = vect_reg[gl(length(vect_reg), length(unique(amm_ZNA_non_pro_dhmed$amm)))] 
  colnames(amm_ZNA_non_pro_dhref) = sub("dhmed", "dhref", colnames(amm_ZNA_non_pro_dhref))
  
  #on rajoute au tableau contenant les dhref des cultures les dhref des zna_non_pro
  amm_occsol_dhref_2 = rbind(amm_occsol_dhref_2, amm_ZNA_non_pro_dhref)
  #amm_occsol_dhref_2$region<-substr(amm_occsol_dhref_2$region,2,3)
  
  dbWriteTable(con_rpsql, c(bdd_target, "amm_occsol_dhref_2"),
               value = amm_occsol_dhref_2, 
               append = FALSE, row.names = FALSE, overwrite = T) 
  
  paste0("COMMENT ON TABLE ", bdd_target, ".amm_occsol_dhref_2  IS 'creation : ",
         date(), " par ", username ," via le script ", selfName , "';") %>% 
    dbSendQuery(con_rpsql, .)
  
  dbSendQuery(con_rpsql, paste0("CREATE INDEX dhref_amm ON ", bdd_target, ".amm_occsol_dhref_2(amm);"))
  dbSendQuery(con_rpsql, paste0("CREATE INDEX dhref_unit ON ", bdd_target, ".amm_occsol_dhref_2(unite);"))
  dbSendQuery(con_rpsql, paste0("CREATE INDEX dhref_occsol ON ", bdd_target, ".amm_occsol_dhref_2(occsol);"))
  dbSendQuery(con_rpsql, paste0("CREATE INDEX dhref_dhref ON ", bdd_target, ".amm_occsol_dhref_2(dhref);"))
  
  rm(amm_ZNA_non_pro_dhref, amm_ZNA_non_pro_dhmed, amm_zna_pro_dhref, amm_occsol_dhref_tg, 
     calc_int, tab_amm,amm_occsol_dhref, amm_dhmed_cult_surf_saa, 
     amm_cult_dhmed, amm_cult_dhom_ephy_select)
  
  gc()
  
  ###################################################################################################
  ########################### SURFACES PAR CP ET OCCUPATION DU SOL ##################################
  ###################################################################################################
  
  #Verification si table existe
  if(dbExistsTable(con_rpsql, name = c(bdd_target, "surf_cp"))){
    
    dbRemoveTable(con_rpsql, name = c(bdd_target, "surf_cp"))
    
  }
  
  dbSendQuery(con_rpsql, paste0("CREATE TABLE ", bdd_target, ".surf_cp AS (
                                          SELECT region, cp_adm, occsol, 
                                    SUM(a.surf_ha) AS surf_gc_cp
                                  FROM ", bdd_target, ".parcelles a
                                  INNER JOIN (
                                    SELECT DISTINCT code_region region, 
                                      code_commune_insee com_adm
                                   FROM donnees_references.com_dep_reg) regs
                                  USING(com_adm)
                                  GROUP BY region, cp_adm, occsol);")) 
  
  dbSendQuery(con_rpsql, paste0("CREATE INDEX i_occsol ON ", bdd_target, ".surf_cp (occsol);"))
  dbSendQuery(con_rpsql, paste0("CREATE INDEX i_cp ON ", bdd_target, ".surf_cp (cp_adm);"))
  
  #ajout d'un coef du fait qu'un cp puisse avoir deux regions
  surf_cp = dbReadTable(con_rpsql, name = c(bdd_target, "surf_cp"))
  surf_cp_all = surf_cp
  
  surf_cp = aggregate(surf_gc_cp ~ cp_adm + region, surf_cp, sum)
  colnames(surf_cp)[3] = "surf_cp_reg"
  surf_cp_1 = aggregate(surf_cp_reg ~ cp_adm, surf_cp,sum)
  colnames(surf_cp_1)[2] = "surf_tot_cp"
  surf_cp = left_join(surf_cp, surf_cp_1, by = "cp_adm")
  surf_cp$coef = surf_cp$surf_cp_reg / surf_cp$surf_tot_cp
  
  dbWriteTable(con_rpsql, c(bdd_target, "surf_cp_b"),
               value = surf_cp, append = FALSE, row.names = FALSE, overwrite = T)
  
  surf_cp_bireg = surf_cp %>% 
    filter(coef != 1) %>% 
    select(cp_adm, region) %>% 
    left_join(surf_cp_all, by = c("cp_adm", "region")) %>% 
    filter(surf_gc_cp > 0) %>% 
    left_join(amm_occsol_dhref_2, by = c("region", "occsol"),
              relationship = "many-to-many")  %>% 
    mutate(surf_dose = surf_gc_cp * dhref) %>% 
    group_by(cp_adm, region, amm, unite) %>% 
    summarise(surf_reg_cp_amm = sum(surf_dose, na.rm = T), .groups = "drop")
  
  surf_cp_bireg_1 = surf_cp_bireg %>% 
    group_by(amm, cp_adm) %>% 
    summarise(surf_tot_cp_amm = sum(surf_reg_cp_amm, na.rm = T), .groups = "drop")
  
  surf_cp_bireg = surf_cp_bireg %>% 
    left_join(surf_cp_bireg_1, by = c("cp_adm", "amm")) %>% 
    mutate(coef = surf_reg_cp_amm/surf_tot_cp_amm) %>% 
    filter(coef != 1) %>% 
    select(cp_adm, region, amm, unite, coef)
  
  dbWriteTable(con_rpsql, c(bdd_target, "surf_cp_bireg"),
               value = surf_cp_bireg, append = FALSE, row.names = FALSE, overwrite = T)
  
  
  ########### CALCUL DES COEF PAR CODE POSTAL, PAR AMM et PAR OCCSOL #############
  
  timestamp()
  print("calcul des coefs")
  
  #Verification si table existe
  if(dbExistsTable(con_rpsql, name = c(bdd_target, "amm_surf_cp"))){
    
    dbRemoveTable(con_rpsql, name = c(bdd_target, "amm_surf_cp"))
    
  }
  
  dbSendQuery(con_rpsql,
              paste0("CREATE TABLE ", bdd_target, ".amm_surf_cp AS
                                    SELECT region, occsol, amm, unite, 
                                           dhref, cp_adm, surf_gc_cp,
                                           dhref*surf_gc_cp AS dhref_surf
                                      FROM ", bdd_target,
                     ".amm_occsol_dhref_2 
                                    INNER JOIN ", bdd_target,
                     ".surf_cp USING(region, occsol)
                                    WHERE dhref IS NOT NULL 
                                     AND dhref > 0 
                                     AND surf_gc_cp > 0;"))
  
  #Verification si table existe
  if(dbExistsTable(con_rpsql, name = c(bdd_target, "coef_amm_cp"))){
    
    dbRemoveTable(con_rpsql, name = c(bdd_target, "coef_amm_cp"))
    
  }
  
  dbSendQuery(con_rpsql, 
              paste0("CREATE TABLE ", bdd_target, ".coef_amm_cp AS (
                                    WITH a AS (
                                    SELECT SUM(dhref_surf) AS qph, 
                                          region, cp_adm, amm, unite
                                      FROM ", bdd_target, ".amm_surf_cp
                                      GROUP BY region, cp_adm, amm, unite
                                    )
                                    SELECT cp_adm, region, amm, unite, occsol, surf_gc_cp, qph,
                                    CASE WHEN scpb.coef IS NULL THEN (dhref/qph) 
                                          ELSE (dhref/qph)*scpb.coef END AS coef
                                    FROM ", bdd_target, ".amm_surf_cp
                                    INNER JOIN a USING(region, cp_adm, amm, unite)
                                    LEFT JOIN ", bdd_target, ".surf_cp_bireg scpb USING(region, cp_adm, amm, unite)
                              );"))
  
  dbSendQuery(con_rpsql, paste0("ALTER TABLE ", bdd_target, ".coef_amm_cp 
                        ADD CONSTRAINT pk_coef PRIMARY KEY (cp_adm, region, amm, unite, occsol);"))
  
  paste0("COMMENT ON TABLE ", bdd_target, ".coef_amm_cp  IS 'creation : ",
         date(), " par ", username ," via le script ", selfName , "';") %>% 
    dbSendQuery(con_rpsql, .)
  
  #16/07/20: check-up occsol
  occsol_coef = dbGetQuery(con_rpsql, paste0("SELECT DISTINCT occsol 
                                      FROM ", bdd_target, ".coef_amm_cp 
                                      WHERE occsol IN (
                                        SELECT DISTINCT occsol 
                                        FROM ", bdd_target, ".parcelles) 
                                      ORDER BY occsol;"))
  
  occsol_coef = occsol_coef$occsol
  
  for(i in 1:length(vect_occsol)){
    
    if(isTRUE(vect_occsol[i] %ni% occsol_coef)){
      
      print("error occsol_coef")
      
    }
    
  }
  
  
  
  somme_coef = dbGetQuery(con_rpsql, paste0("SELECT a.cp_adm, a.region, amm, unite,  
                                        SUM(coef*a.surf_gc_cp) AS somme1
                                      FROM ", bdd_target, ".coef_amm_cp a
                                      JOIN ", bdd_target, ".surf_cp 
                                        USING(cp_adm, region, occsol)
                                      GROUP BY a.cp_adm, a.region, amm, unite;"))
  
  somme_coef = left_join(somme_coef, surf_cp_bireg, by = c("cp_adm", "region", "amm", "unite")) %>% 
    mutate(somme = ifelse(is.na(coef), somme1, somme1/coef))
  
  somme_coef = somme_coef[, c("cp_adm", "region", "amm", "unite", "somme")]
  
  dbWriteTable(con_rpsql, c(bdd_target, "somme_coef"), 
               value = somme_coef, append = FALSE, row.names = FALSE, overwrite = T)
  
  dbSendQuery(con_rpsql, paste0("DROP TABLE ", bdd_target, ".amm_cult_dhom_ephy_initial, 
                        ", bdd_target, ".amm_traitementgeneraux_agri, 
                        ", bdd_target, ".dhmed_traitementsgeneraux;"))
  
}

dbDisconnect(con_rpsql)