""" !######################################################################################################################################## !# # !# Script pour calculer les statistiques des entités jonctionnées # !# d'un fichier database (.sql) produit par Therion # !# By Alexandre PONT alexandre.pont@yahoo.fr # !# # !# Utilisation: # !# Exporter le fichier sql avec therion, commande therion.thconfig : export database -o Outputs/database.sql # !# Commande : python pyThStat.py ./chemin/fichier.sql # !# ou : python pyThStat.py pour ouvrir une fenêtre # !# Résultat : fichiers dans le dossier crée du fichier source # !######################################################################################################################################## """ import argparse import os import re import sqlite3 import sys import tkinter as tk from collections import defaultdict from datetime import datetime from tkinter import filedialog from turtle import color # noqa: F401 import matplotlib.pyplot as plt # type: ignore import numpy as np import pandas as pd from alive_progress import alive_bar # https://github.com/rsalmei/alive-progress import Lib.global_data as globalDat from Lib.general_fonctions import Colors, colored_help, safe_relpath, setup_logger ##################################################################################################################################### # Fonction pour importer un fichier SQL dans une base de données SQLite # ##################################################################################################################################### def importation_sql_data(fichier_sql): """ Fonction pour importer un fichier SQL dans une base de données SQLite Args: fichier_sql (_type_): _description_ """ global error_count try: ##################################################################################################################################### # Phase 1 # Si la base de données existe, supprimez-la pour forcer l'écriture ##################################################################################################################################### log.info( f"{Colors.UNDERLINE}Phase 1:{Colors.ENDC}{Colors.INFO} Importation de la base de données Therion {Colors.ENDC}{safe_relpath(input_file_name, 2)}{Colors.INFO} dans: {Colors.ENDC}{safe_relpath(imported_database, 0)}" ) if os.path.exists(imported_database): # print("Suppression de la Bd existante: " + imported_database) os.remove(imported_database) connection = sqlite3.connect(imported_database) cursor = connection.cursor() # Lecture du fichier SQL et exécution des commandes with open(fichier_sql, encoding="utf-8") as sql_file: sql_script = sql_file.read() # Séparation du script en commandes individuelles sql_script = re.sub(r", nan", ", 0", sql_script, flags=re.IGNORECASE) commandes = [cmd.strip() + ";\n" for cmd in sql_script.split(";\n") if cmd.strip()] # Exécution des commandes avec une barre de progression with alive_bar(len(commandes), title=f"{Colors.YELLOW}Progression{Colors.ENDC}", length=20) as bar: for commande in commandes: cursor.execute(commande) bar() connection.commit() connection.close() except sqlite3.Error as e: log.error(f"Erreur lors de l'exécution de la requête importation_sql_data code:{Colors.ENDC} {e}") error_count += 1 sys.exit(1) # Arrête le programme en cas d'erreur ##################################################################################################################################### # Fonction pour construire les tables _JONCTION, _SERIE, _VISEE_FLAG et _RESEAU # ##################################################################################################################################### def construction_tables(): """ Fonction pour construire les tables spécifiques _JONCTION, _SERIE, _VISEE_FLAG et _RESEAU """ global avt_compteur global error_count # Principales requêtes # conn = sqlite3.connect(database) # Connexion à la base de données SQLite # cursor = conn.cursor() # print(f"{Colors.GREEN}{Colors.BOLD}Construction des tables dans {imported_database}{Colors.ENDC}") try: ##################################################################################################################################### # Phase 2 # Création des tables spécifiques ##################################################################################################################################### log.info(f"{Colors.UNDERLINE}Phase 2:{Colors.ENDC}{Colors.INFO} Création des nouvelles tables, indexation") cursor.execute("DROP TABLE IF EXISTS _JONCTION") # Créer et initialiser une nouvelle table de jonctions cursor.execute(""" CREATE TABLE _JONCTION ( ID INTEGER PRIMARY KEY AUTOINCREMENT, STATION_ID INTEGER, SERIE_ID INTEGER, SERIE_RANG INTEGER, SERIE_ENT INTEGER, STATION_ENT INTEGER, SERIE_JONC INTEGER, STATION_JONC INTEGER, STATION_TYPE varchar(4), ENTREE_ID INTEGER, RESEAU_ID INTEGER ) """) cursor.execute("select STATION.ID from STATION") results = cursor.fetchall() Next_Station_ID = cursor.fetchall() # Pour forcer le type cursor.executemany("INSERT INTO _JONCTION (STATION_ID) VALUES (?)", results) conn.commit() cursor.execute("DROP TABLE IF EXISTS _SERIE") # Créer et initialiser une nouvelle table des Series cursor.execute(""" CREATE TABLE _SERIE ( SERIE_ID INTEGER PRIMARY KEY AUTOINCREMENT, SERIE_DEP_ID INTEGER, STATION_DEP_ID INTEGER, SERIE_ARR_ID INTEGER, STATION_ARR_ID INTEGER, SERIE_NBRE_SHOT INTEGER, SERIE_LENGHT REAL, SERIE_LENGHT_SURFACE REAL, SERIE_LENGHT_DUPLICATE REAL, DIRECTION INTEGER, STATION_ENT_ID INTEGER, RESEAU_ID INTEGER) """) Current_Serie_ID = cursor.lastrowid conn.commit() cursor.execute("DROP TABLE IF EXISTS _RESEAU") cursor.execute(""" CREATE TABLE _RESEAU ( ID INTEGER PRIMARY KEY AUTOINCREMENT, RESEAU_ID INTEGER, STATION_JONC INTEGER, ENT_1 INTEGER, ENT_2 INTEGER, RESEAU_NAME) """) conn.commit() SHOT_equates_station() issue_SHOT() duplicate_SHOT() cursor.execute("DROP TABLE IF EXISTS _VISEE_FLAG") # Créer et initialiser une nouvelle table _VISEE_FLAG (suivi des visées lues) cursor.execute(""" CREATE TABLE _VISEE_FLAG ( ID INTEGER PRIMARY KEY AUTOINCREMENT, SHOT_ID INTEGER, SERIE_ID INTEGER, ENTREE_ID INTEGER, RESEAU_ID INTEGER, SERIE_RANG INTEGER ) """) cursor.execute("select SHOT.ID from SHOT") results = cursor.fetchall() cursor.executemany("INSERT INTO _VISEE_FLAG (SHOT_ID) VALUES (?)", results) # type: ignore conn.commit() log.info("Création de l'index des tables principales et optimisation de la mémoire") cursor.execute("CREATE INDEX INDEX_JONCTION_STATION_ID ON _JONCTION(STATION_ID)") cursor.execute("PRAGMA index_list(SHOT)") result = cursor.fetchall() marquage_visee_station_habillage() # print(result) if len(result) == 0: cursor.execute("CREATE INDEX INDEX_SHOT_FROM_ID ON SHOT(FROM_ID)") cursor.execute("CREATE INDEX INDEX_SHOT_TO_ID ON SHOT(TO_ID)") cursor.execute("CREATE INDEX INDEX_SHOT_FLAG_SHOT_ID ON SHOT_FLAG(SHOT_ID)") cursor.execute("CREATE INDEX INDEX_STATION_ID ON STATION(ID)") cursor.execute("CREATE INDEX INDEX_VISEE_FLAG_SHOT_ID ON _VISEE_FLAG(SHOT_ID)") cursor.execute("CREATE INDEX INDEX_STATION_FLAG_STATION_ID ON STATION_FLAG(STATION_ID)") cursor.execute("VACUUM") conn.commit() ##################################################################################################################################### # Phase 3 # A partir des entrées, remplir les tables des jonctions et des séries ##################################################################################################################################### log.info( f"{Colors.UNDERLINE}Phase 3:{Colors.ENDC}{Colors.INFO} Remplissage des tables d'après les {Colors.ENDC}{len(results)}{Colors.INFO} entrée(s){Colors.ENDC}" ) # type: ignore results = sql_liste_entree() for row in results: # type: ignore # if row[0]==28548: # print("debug point") cursor.execute( """ INSERT INTO _SERIE ( SERIE_DEP_ID, STATION_DEP_ID, SERIE_ARR_ID , STATION_ARR_ID, SERIE_NBRE_SHOT, SERIE_LENGHT, SERIE_LENGHT_SURFACE, SERIE_LENGHT_DUPLICATE, DIRECTION, STATION_ENT_ID, RESEAU_ID) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""", (0, row[0], 0, row[0], -1, 0, 0, 0, 0, row[0], 0), ) Current_Serie_ID = cursor.lastrowid cursor.execute( """ UPDATE _JONCTION SET SERIE_ID = ?, SERIE_ENT = ?, STATION_ENT = ?, SERIE_JONC = ?, STATION_JONC = ?, STATION_TYPE = ?, SERIE_RANG = ?, ENTREE_ID = ?, RESEAU_ID = ? WHERE STATION_ID = ? """, (Current_Serie_ID, 0, row[0], 0, 0, "ent", 0, row[0], 0, row[0]), ) cursor.execute(f""" UPDATE _VISEE_FLAG SET SERIE_ID = {Current_Serie_ID}, ENTREE_ID = {row[0]}, RESEAU_ID = {0} WHERE SHOT_ID = {Current_Serie_ID} """) conn.commit() # print(f"Création Série: {Current_Serie_ID} depuis la station d'entrée Station_ID: {row[0]}") ##################################################################################################################################### # Phase 4 # A partir des série vides, itération pour remplir les tables des _JONCTION et des _SERIE ##################################################################################################################################### log.info( f"{Colors.UNDERLINE}Phase 4:{Colors.ENDC}{Colors.INFO} Remplissage des tables d'après les séries vides jonctionnées aux{Colors.ENDC} {Current_Serie_ID}{Colors.INFO} entrée(s){Colors.ENDC}" ) results = sql_serie_vides() Count = 1 New_Serie_ID = cursor.lastrowid Current_Station_ID_Old = 0 Current_Station_ID = 0 cursor.execute("SELECT COUNT(*) AS nbre FROM _JONCTION WHERE STATION_TYPE IS NULL") _compteur = cursor.fetchall() compteur_ttl = int(_compteur[0][0]) avt_compteur = 0 with alive_bar(compteur_ttl, title=f"{Colors.YELLOW}Progression{Colors.ENDC}", length=20) as bar: while len(results) > 0: # type: ignore # print(f"{Colors.GREEN}{Colors.BOLD}Phase 4.{Count}: Remplissage des tables _JONCTION et _SERIE itération: {Count}, séries créée(s): {New_Serie_ID} ajoutée(s): {New_Serie_ID-New_Serie_IDOld} à traiter: {len(results)}{Colors.ENDC}") # type: ignore bar.text(f"{Colors.YELLOW}itération(s): {Colors.ENDC}{Count}{Colors.YELLOW}, série(s) créée(s): {Colors.ENDC}{New_Serie_ID}{Colors.YELLOW}") # type: ignore cursor.execute("SELECT COUNT(*) AS nbre FROM _JONCTION WHERE STATION_TYPE IS NULL") _compteur = cursor.fetchall() compteur = int(_compteur[0][0]) if (compteur_ttl - compteur) > avt_compteur: ajout = compteur_ttl - compteur - avt_compteur bar(ajout) avt_compteur = compteur_ttl - compteur for row in results: # type: ignore # Suivi de la série Current_Serie_ID = int(row[0]) Current_Station_ID_Old = int(Current_Station_ID) # type: ignore Current_Station_ID = int(row[2]) # Current_Nre_Shot = int(row[5]) # Current_Serie_Lenght = 0.0 + float(row[6]) # Current_Serie_Lenght_Surface = 0.0 + float(row[7]) # Current_Serie_Lenght_Duplicate = 0.0 + float(row[8]) Current_Ent = int(row[10]) Direction = int(row[9]) # print(f"Serie courante {Current_Serie_ID} Station_ID: {Current_Station_ID} results: {results}") Fin_Serie = False while Fin_Serie is False: if Direction == 1: Next_Station_ID = sql_station_depart(Current_Station_ID) elif Direction == -1: Current_Station_ID = int(row[4]) Next_Station_ID = sql_station_arrivee(Current_Station_ID) elif Direction == 0: Next_Station_ID_1 = sql_station_depart(Current_Station_ID) Next_Station_ID_2 = sql_station_arrivee(Current_Station_ID) if len(Next_Station_ID_1) == 0 and len(Next_Station_ID_2) == 0: # type: ignore # Entrée sans départ et sans d'arrivée : fin de la série cursor.execute(f"UPDATE _SERIE SET SERIE_NBRE_SHOT = 0 WHERE SERIE_ID = {Current_Serie_ID};") cursor.execute(f"UPDATE _JONCTION SET SERIE_ENT = -1 WHERE STATION_ID = {Current_Station_ID};") conn.commit() Next_Station_ID = Next_Station_ID_1 elif len(Next_Station_ID_1) == 1 and len(Next_Station_ID_2) == 0: # type: ignore # Un départ pas d'arrivée Next_Station_ID = Next_Station_ID_1 Direction = 1 cursor.execute(f"UPDATE _SERIE SET DIRECTION = 1 WHERE SERIE_ID = {Current_Serie_ID};") conn.commit() elif len(Next_Station_ID_1) == 0 and len(Next_Station_ID_2) == 1: # type: ignore # Une arrivée pas de départ Next_Station_ID = Next_Station_ID_2 Direction = -1 cursor.execute(f"UPDATE _SERIE SET DIRECTION = -1 WHERE SERIE_ID = {Current_Serie_ID};") conn.commit() else: # A gérer nouvelles séries nouvelles_series(Current_Station_ID, Current_Station_ID_Old, Current_Serie_ID, 1, Current_Ent) # type: ignore # print (f"\033[34m\tA traiter création nouvelles séries inverses depuis l'entrée {Current_Station_ID} - {Next_Station_ID_2}, {Next_Station_ID_1}{Colors.ENDC}") nouvelles_series(Current_Station_ID, Current_Station_ID_Old, Current_Serie_ID, -1, Current_Ent) Direction = 1 Next_Station_ID = Next_Station_ID_1 if len(Next_Station_ID) == 0: # type: ignore Next_Station_ID_1 = sql_station_depart(Current_Station_ID) # type: ignore Next_Station_ID_2 = sql_station_arrivee(Current_Station_ID) # type: ignore # print(f"\033[34m\tA gérer, fin de la Série: {Current_Serie_ID} à la Station_ID: {Current_Station_ID} nbre: {Current_Nre_Shot} Next station: {Next_Station_ID}, départs directs {len(Next_Station_ID_1)}, départs inverses {len(Next_Station_ID_2)}{Colors.ENDC}") # type: ignore # cursor.execute(f"UPDATE _SERIE SET SERIE_DEP_ID = {Current_Serie_ID} WHERE SERIE_ID = {Current_Serie_ID};") # type: ignore # cursor.execute(f"UPDATE _SERIE SET STATION_DEP_ID = {Current_Station_ID} WHERE SERIE_ID = {Current_Serie_ID};") # type: ignore # cursor.execute(f"UPDATE _SERIE SET SERIE_NBRE_SHOT = 0 WHERE SERIE_ID = {Current_Serie_ID};") # type: ignore cursor.execute(f"DELETE FROM _SERIE WHERE SERIE_ID = {Current_Serie_ID};") conn.commit() # type: ignore Fin_Serie = True elif len(Next_Station_ID) == 1: # type: ignore suivi_serie(Current_Serie_ID, bar) Fin_Serie = True else: # print(f"Station_ID {Current_Station_ID} de la Serie {Current_Serie_ID}, départs à gérer: {len(Next_Station_ID)}, Next station: {Next_Station_ID}") # type: ignore suivi_serie(Current_Serie_ID, bar) # Création de X nouvelles séries et mise à jour de la table des jonctions # nouvelles_series(Current_Station_ID, Current_Station_ID_Old, Current_Serie_ID, 1, Current_Ent) Fin_Serie = True # Exécution de la requête SQL resultsOld = results results = sql_serie_vides() # type: ignore # New_Serie_IDOld = New_Serie_ID New_Serie_ID = cursor.lastrowid # type: ignore if resultsOld == results: # print(f"Erreur sortie itération qté: {len(resultsOld)} - {resultsOld} - {results}") log.error( f"Erreur sortie itération {Colors.ENDC}{Count}{Colors.ERROR}, séries restantes: {Colors.ENDC}{resultsOld}{Colors.ERROR} - {Colors.ENDC}{results}" ) # type: ignore error_count += 1 break Count += 1 cursor.execute("SELECT COUNT(*) AS nbre FROM _JONCTION WHERE STATION_TYPE IS NULL") _compteur = cursor.fetchall() compteur = int(_compteur[0][0]) if (compteur_ttl) > avt_compteur: ajout = compteur_ttl - avt_compteur bar(ajout) avt_compteur = compteur_ttl orphelines_shot() jonction_RESEAU() name_RESEAU() if compteur > 0: log.warning( f"Phase 4: Fin du remplissage des tables,{Colors.WARNING} attention {Colors.ENDC}{compteur}{Colors.WARNING} station(s) non comptabilisé(s)" ) # else : # print(f"{Colors.GREEN}{Colors.BOLD}Phase 4: Fin du remplissage des tables voir {imported_database}{Colors.ENDC}") except sqlite3.Error as e: log.error(f"Erreur lors de l'exécution d'une de la fonction construction_tables, code:{Colors.ENDC} {e}") error_count += 1 ##################################################################################################################################### # Création des séries entres les visées orphelines -> visées d'une visées entre 2 points marqués # ##################################################################################################################################### def orphelines_shot(): global error_count try: cursor.execute(""" -- Visées orphelines SELECT _VISEE_FLAG.SHOT_ID, _VISEE_FLAG.SERIE_ID, _VISEE_FLAG.ENTREE_ID, SHOT_FLAG.FLAG, SHOT.FROM_ID, -- STATION_FROM.NAME, JONCTION_FROM.SERIE_ID, JONCTION_FROM.STATION_TYPE, JONCTION_FROM.ENTREE_ID, SHOT.TO_ID, -- STATION_TO.NAME, JONCTION_TO.SERIE_ID, JONCTION_TO.STATION_TYPE, JONCTION_TO.ENTREE_ID, SHOT.LENGTH --sum (SHOT.LENGTH) FROM _VISEE_FLAG JOIN SHOT ON SHOT.ID = _VISEE_FLAG.SHOT_ID LEFT JOIN SHOT_FLAG ON SHOT.ID = SHOT_FLAG.SHOT_ID JOIN STATION AS STATION_FROM ON SHOT.FROM_ID = STATION_FROM.ID JOIN STATION AS STATION_TO ON SHOT.TO_ID = STATION_TO.ID JOIN _JONCTION AS JONCTION_FROM ON SHOT.FROM_ID = JONCTION_FROM.ID JOIN _JONCTION AS JONCTION_TO ON SHOT.TO_ID = JONCTION_TO.ID WHERE _VISEE_FLAG.SERIE_ID is NULL and JONCTION_TO.SERIE_ID is not null and JONCTION_FROM.SERIE_ID is not null """) conn.commit() orphelines = cursor.fetchall() log.info(f"Intégrations des visées orphelines (entre 2 stations existantes), nbre: {Colors.ENDC}{len(orphelines)}") for row in orphelines: _SERIE_LENGHT = 0 _SERIE_LENGHT_SURFACE = 0 _SERIE_LENGHT_DUPLICATE = 0 if row[3] == "dpl": _SERIE_LENGHT_DUPLICATE = row[12] elif row[3] == "srf": _SERIE_LENGHT_SURFACE = row[12] else: _SERIE_LENGHT = row[12] cursor.execute( """ INSERT INTO _SERIE ( SERIE_DEP_ID, STATION_DEP_ID, SERIE_ARR_ID , STATION_ARR_ID, SERIE_NBRE_SHOT, SERIE_LENGHT, SERIE_LENGHT_SURFACE, SERIE_LENGHT_DUPLICATE, DIRECTION, STATION_ENT_ID) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""", (row[5], row[4], row[9], row[8], 1, _SERIE_LENGHT, _SERIE_LENGHT_SURFACE, _SERIE_LENGHT_DUPLICATE, 1, row[7]), ) _Current_Serie_ID = cursor.lastrowid cursor.execute(f""" UPDATE _VISEE_FLAG SET SERIE_ID = {_Current_Serie_ID}, ENTREE_ID = {row[7]}, SERIE_RANG = {1} WHERE SHOT_ID = {row[0]} """) if row[7] != row[11]: cursor.execute("INSERT INTO _RESEAU (STATION_JONC, ENT_1, ENT_2) VALUES (?, ?, ?)", (row[8], row[7], row[11])) # print (f"{Colors.BLUE}\t Jonction des entrées à la Station_ID: {row[8]} entre: {row[7]} et: {row[11]}{Colors.ENDC}") conn.commit() except sqlite3.Error as e: log.error(f"Erreur lors de l'exécution de la requête orphelines_shot code:{Colors.ENDC} {e}") error_count += 1 ##################################################################################################################################### # Fonction pour joindre les reseaux # ##################################################################################################################################### def jonction_RESEAU(): global error_count try: cursor.execute(""" --Recherche des doublons dans les jonctions réseau SELECT ID --GROUP_CONCAT(_RESEAU.ID) as DUPP_SHOT FROM _RESEAU GROUP BY _RESEAU.ENT_1, _RESEAU.ENT_2, _RESEAU.STATION_JONC HAVING COUNT(_RESEAU.ENT_1)>1 AND COUNT(_RESEAU.ENT_2)>1 AND COUNT(_RESEAU.STATION_JONC)>1 """) conn.commit() doublons = cursor.fetchall() # print(f"Table des RESEAUX doublons nbre: {len(doublons)}") for row in doublons: cursor.execute(f"DELETE FROM _RESEAU WHERE _RESEAU.ID = {row[0]}") conn.commit() index_reseau = 0 while True: index_reseau += 1 cursor.execute(""" -- Liste des entrée dans la table _RESEAU SELECT _RESEAU.ENT_1 AS ENT, _RESEAU.RESEAU_ID, STATION.NAME, STATION.Z FROM _RESEAU JOIN STATION ON _RESEAU.ENT_1 = STATION.ID WHERE _RESEAU.RESEAU_ID IS NULL UNION --ALL SELECT _RESEAU.ENT_2 AS ENT, _RESEAU.RESEAU_ID, STATION.NAME, STATION.Z FROM _RESEAU JOIN STATION ON _RESEAU.ENT_2 = STATION.ID WHERE _RESEAU.RESEAU_ID IS NULL ORDER BY STATION.Z DESC """) conn.commit() entrees = cursor.fetchall() if len(entrees) == 0: break # Sortie boucle while si plus d'entrées à traiter... cursor.execute(f"UPDATE _RESEAU SET RESEAU_ID = {index_reseau} WHERE _RESEAU.ENT_1 = {entrees[0][0]} ") cursor.execute(f"UPDATE _RESEAU SET RESEAU_ID = {index_reseau} WHERE _RESEAU.ENT_2 = {entrees[0][0]} ") conn.commit() liste_entrees_reseau = [] liste_entrees_reseau.append(entrees[0][0]) nbre_entree_reseau_old = 0 nbre_entree_reseau = len(liste_entrees_reseau) while nbre_entree_reseau_old != nbre_entree_reseau: nbre_entree_reseau_old = nbre_entree_reseau for row in liste_entrees_reseau: cursor.execute(f""" -- Recherche entrée jonctionnées SELECT _RESEAU.ENT_1 FROM _RESEAU WHERE _RESEAU.ENT_2 = {row} -- AND _RESEAU.RESEAU_ID IS NULL UNION SELECT _RESEAU.ENT_2 FROM _RESEAU WHERE _RESEAU.ENT_1 = {row} -- AND _RESEAU.RESEAU_ID IS NULL """) jonction = cursor.fetchall() for row2 in jonction: # type: ignore if row2[0] not in liste_entrees_reseau: # print(f"Jonction de l'entrée: {row2[0]} au reseau ID: {index_reseau}") cursor.execute(f"UPDATE _RESEAU SET RESEAU_ID = {index_reseau} WHERE _RESEAU.ENT_1 = {row2[0]} ") cursor.execute(f"UPDATE _RESEAU SET RESEAU_ID = {index_reseau} WHERE _RESEAU.ENT_2 = {row2[0]} ") liste_entrees_reseau.append(row2[0]) conn.commit() nbre_entree_reseau = len(liste_entrees_reseau) for row2 in liste_entrees_reseau: cursor.execute(f"UPDATE _JONCTION SET RESEAU_ID = {index_reseau} WHERE _JONCTION.ENTREE_ID = {row2} ") cursor.execute(f"UPDATE _SERIE SET RESEAU_ID = {index_reseau} WHERE _SERIE.STATION_ENT_ID = {row2} ") cursor.execute(f"UPDATE _VISEE_FLAG SET RESEAU_ID = {index_reseau} WHERE _VISEE_FLAG.ENTREE_ID = {row2} ") conn.commit() log.info( f"Réseau: {Colors.ENDC}{index_reseau}{Colors.INFO}, entrées jonctionnées: {Colors.ENDC}{len(liste_entrees_reseau)}{Colors.INFO}, {Colors.ENDC}{liste_entrees_reseau}" ) except sqlite3.Error as e: log.error(f"Erreur lors de l'exécution de la fonction Jonction_RESEAU, code:{Colors.ENDC} {e}") error_count += 1 ##################################################################################################################################### # Fonction pour nommer les réseaux d'après les survey name # ##################################################################################################################################### def name_RESEAU(): global error_count try: cursor.execute(""" SELECT _RESEAU.ID AS _ID, _RESEAU.RESEAU_ID AS _RESEAU_ID, _RESEAU.ENT_1, _RESEAU.ENT_2, STATION_ENT_1.NAME AS S1_NAME, STATION_ENT_2.NAME AS S2_NAME, SURVEY_ENT_1.NAME AS SURVEY_NAME_ENT_1, SURVEY_ENT_1.FULL_NAME AS SURVEY_FULL_NAME_ENT_1, SURVEY_ENT_1.ID AS SURVEY_ID_ENT_1, SURVEY_ENT_1.TITLE AS SURVEY_TITLE_NAME_ENT_1, SURVEY_ENT_2.NAME AS SURVEY_NAME_ENT_2, SURVEY_ENT_2.FULL_NAME AS SURVEY_FULL_NAME_ENT_2, SURVEY_ENT_2.ID AS SURVEY_ID_ENT_2, SURVEY_ENT_2.TITLE AS SURVEY_TITLE_NAME_ENT_2 FROM _RESEAU AS _RESEAU INNER JOIN STATION AS STATION_ENT_1 ON _RESEAU.ENT_1 = STATION_ENT_1.ID LEFT JOIN STATION AS STATION_ENT_2 ON _RESEAU.ENT_2 = STATION_ENT_2.ID INNER JOIN SURVEY AS SURVEY_ENT_1 ON STATION_ENT_1.SURVEY_ID = SURVEY_ENT_1.ID INNER JOIN SURVEY AS SURVEY_ENT_2 ON STATION_ENT_2.SURVEY_ID = SURVEY_ENT_2.ID ORDER BY _RESEAU_ID; """) conn.commit() name_reseau = cursor.fetchall() for row in name_reseau: log.debug( f"{Colors.BLUE}Réseau ID {Colors.ENDC}{row[0]}{Colors.BLUE}, ENT_1 full name : {Colors.ENDC}{row[7]}{Colors.BLUE}, Survey ID {Colors.ENDC}{row[8]}{Colors.BLUE}, ENT_2 full name : {Colors.ENDC}{row[11]}{Colors.BLUE}, Survey ID {Colors.ENDC}{row[12]}{Colors.BLUE}" ) parent_ent_01 = sql_Parents_Survey(row[8]) parent_ent_02 = sql_Parents_Survey(row[12]) # IDs communs aux deux listes, en parcourant depuis la racine vers l'enfant ids_01 = [row[0] for row in parent_ent_01] # type: ignore ids_02 = [row[0] for row in parent_ent_02] # type: ignore # Ancêtres communs = intersection communs = set(ids_01) & set(ids_02) # Premier parent commun = celui le plus proche des enfants # → dans les listes ordonnées enfant→racine, c'est le commun le plus "à gauche" premier_commun = next(row for row in parent_ent_01 if row[0] in communs) # type: ignore log.debug(f"{Colors.BLUE}Premier commun : {Colors.ENDC}{premier_commun}") cursor.execute("UPDATE _RESEAU SET RESEAU_NAME = ? WHERE RESEAU_ID = ?", (premier_commun[2], row[1])) conn.commit() except sqlite3.Error as e: log.error(f"Erreur lors de l'exécution de la fonction name_RESEAU, code:{Colors.ENDC} {e}") error_count += 1 ##################################################################################################################################### # Fonction pour joindre les equates dans la table des SHOT # # ##################################################################################################################################### def SHOT_equates_station(): global error_count # Requête 8: recherche des equates try: cursor.execute(""" -- Requête 8, recherche des equates -- SELECT -- STATION.ID, -- STATION.NAME, GROUP_CONCAT(STATION.ID) as ID_Group -- GROUP_CONCAT(STATION.X) as X_Group, -- GROUP_CONCAT(STATION.Y) as Y_Group, -- GROUP_CONCAT(STATION.Z) as Z_Group, -- COUNT(STATION.X) AS Qte_X, -- COUNT(STATION.Y) AS Qte_Y, -- COUNT(STATION.Z) AS Qte_Z FROM STATION WHERE STATION.NAME <> '.' AND STATION.NAME <> '-' -- INNER JOIN STATION AS STATION_Bis ON STATION.X = STATION_Bis.X AND STATION.Y = STATION_Bis.Y AND STATION.Z = STATION_Bis.Z --WHERE STATION.X = STATION_BIS.X GROUP BY STATION.X, STATION.Y, STATION.Z HAVING COUNT(STATION.X)>1 AND COUNT(STATION.Y)>1 AND COUNT(STATION.Y)>1 """) equate = cursor.fetchall() log.info(f"Jonction de SHOT equates, nbre: {Colors.ENDC}{len(equate)}") for row in equate: sous_valeurs = row[0].split(",") # print(f": {sous_valeurs[0]} = ", end="") for val in range(1, len(sous_valeurs)): # print(f"{sous_valeurs[val]},", end=" ") cursor.execute(f"SELECT SHOT.ID FROM SHOT WHERE SHOT.FROM_ID = {sous_valeurs[val]}") filtre = cursor.fetchall() for row in filtre: cursor.execute(f"UPDATE SHOT SET FROM_ID = {sous_valeurs[0]} WHERE ID = {row[0]};") cursor.execute(f"SELECT SHOT.ID FROM SHOT WHERE SHOT.TO_ID = {sous_valeurs[val]}") filtre = cursor.fetchall() for row in filtre: cursor.execute(f"UPDATE SHOT SET TO_ID = {sous_valeurs[0]} WHERE ID = {row[0]};") cursor.execute("UPDATE _JONCTION SET STATION_TYPE = ? WHERE id = ?", ("equ", sous_valeurs[val])) cursor.execute("UPDATE _JONCTION SET STATION_JONC = ? WHERE id = ?", (sous_valeurs[0], sous_valeurs[val])) # print(" ", end="") conn.commit() # print("") # if len(equate) == 0 : print(f"Aucun 'equate'") except sqlite3.Error as e: log.error(f"Erreur lors de l'exécution de la requête 8 (sql_8_equates) code:{Colors.ENDC} {e}") error_count += 1 ##################################################################################################################################### # Fonction pour supprimer les visées en double (même départs arrivée lg, az et pente) # ##################################################################################################################################### def duplicate_SHOT(): global error_count # Requête 10, recherche des doublons de visées try: cursor.execute(""" -- Requête 10, recherche des doublons de visées -- SELECT SHOT.FROM_ID, SHOT.TO_ID, SHOT.LENGTH, -- SHOT.BEARING, -- SHOT.GRADIENT, GROUP_CONCAT(SHOT.ID) as DUPP_SHOT FROM SHOT GROUP BY SHOT.FROM_ID, SHOT.TO_ID --, SHOT.BEARING, SHOT.GRADIENT, SHOT.LENGTH HAVING COUNT(SHOT.FROM_ID)>1 AND COUNT(SHOT.TO_ID)>1 --AND COUNT(SHOT.BEARING)>1 AND COUNT(SHOT.GRADIENT)>1 AND COUNT(SHOT.LENGTH)>1 """) duplicate = cursor.fetchall() _total_length_err = 0.0 for row in duplicate: sous_valeurs = row[3].split(",") cursor.execute(f""" SELECT SHOT.ID, SHOT_FLAG.FLAG, round(SHOT.LENGTH, 2) FROM SHOT LEFT JOIN SHOT_FLAG ON SHOT.ID = SHOT_FLAG.SHOT_ID WHERE SHOT.ID = {int(sous_valeurs[0])} """) shot_flag = cursor.fetchall() # print("\t " + str(shot_flag)) cursor.execute(f""" SELECT SHOT.ID, SHOT_FLAG.FLAG, round(SHOT.LENGTH, 2) FROM SHOT LEFT JOIN SHOT_FLAG ON SHOT.ID = SHOT_FLAG.SHOT_ID WHERE SHOT.ID = {int(sous_valeurs[1])} """) shot_flag2 = cursor.fetchall() # print("\t " + str(shot_flag2)) # _total_length += int(row[2]) if shot_flag[0][1] is None and shot_flag2[0][1] == "dpl": cursor.execute("SELECT COUNT(*) AS nombre_enregistrements FROM STATION") Current_Station_ID = cursor.fetchall() _Current_Station_ID = int(Current_Station_ID[0][0]) + 1 cursor.execute(f"INSERT INTO STATION (ID, NAME) VALUES ({_Current_Station_ID}, 'isu')") cursor.execute(f"UPDATE SHOT SET TO_ID = {_Current_Station_ID} WHERE SHOT.ID = {shot_flag2[0][0]}") cursor.execute(f"INSERT INTO _JONCTION (STATION_ID) VALUES ({_Current_Station_ID})") elif shot_flag2[0][1] is None and shot_flag[0][1] == "dpl": cursor.execute("SELECT COUNT(*) AS nombre_enregistrements FROM STATION") Current_Station_ID = cursor.fetchall() _Current_Station_ID = int(Current_Station_ID[0][0]) + 1 cursor.execute(f"INSERT INTO STATION (ID, NAME) VALUES ({_Current_Station_ID}, 'isu')") cursor.execute(f"UPDATE SHOT SET TO_ID = {_Current_Station_ID} WHERE SHOT.ID = {shot_flag[0][0]}") cursor.execute(f"INSERT INTO _JONCTION (STATION_ID) VALUES ({_Current_Station_ID})") else: _total_length_err += float(shot_flag2[0][2]) cursor.execute("SELECT COUNT(*) AS nombre_enregistrements FROM STATION") Current_Station_ID = cursor.fetchall() _Current_Station_ID = int(Current_Station_ID[0][0]) + 1 cursor.execute(f"INSERT INTO STATION (ID, NAME) VALUES ({_Current_Station_ID}, 'isu')") cursor.execute(f"UPDATE SHOT SET TO_ID = {_Current_Station_ID} WHERE SHOT.ID = {shot_flag2[0][0]}") cursor.execute(f"INSERT INTO _JONCTION (STATION_ID) VALUES ({_Current_Station_ID})") log.warning( f"Table des SHOT, visées en double à traiter à la source : {Colors.ENDC}{shot_flag}{Colors.WARNING}, {Colors.ENDC}{shot_flag2}" + f"{Colors.WARNING}, station crée : {Colors.ENDC}{_Current_Station_ID}" + f"{Colors.WARNING}, long. en double : {Colors.ENDC}{'{:.2f}'.format(_total_length_err)}{Colors.WARNING} m" # noqa: UP032 + f"{Colors.WARNING}\nFull name : {Colors.ENDC}{sql_shot_full_name(shot_flag[0][0])}" + f"{Colors.WARNING}, and : {Colors.ENDC}{sql_shot_full_name(shot_flag2[0][0])}" ) conn.commit() # for val in range (1, len(sous_valeurs)) : # cursor.execute(f"DELETE FROM SHOT WHERE SHOT.ID = {sous_valeurs[val]}") # filtre = cursor.fetchall() if len(duplicate) > 0: log.info(f"Table des SHOT, visées dupliquées traités, nbre: {Colors.ENDC}{len(duplicate)}") # print(f"Visées dupliqués supprimés {duplicate}") else: log.info("Table des SHOT, aucune visée dupliquée") except sqlite3.Error as e: log.error(f"Erreur lors de l'exécution de la requête (duplicate_SHOT) code:{Colors.ENDC} {e}") error_count += 1 ##################################################################################################################################### # Fonction pour supprimer les visées en de longueur null sur elle même (même départ et arrivée et longueur nulle # ##################################################################################################################################### def issue_SHOT(): global error_count try: cursor.execute(""" SELECT SHOT.ID --SHOT.FROM_ID, --SHOT.TO_ID, --SHOT.LENGTH FROM SHOT WHERE SHOT.FROM_ID = SHOT.TO_ID AND SHOT.LENGTH = 0 """) issue = cursor.fetchall() for row in issue: cursor.execute(f"DELETE FROM SHOT WHERE ID = {row[0]}") # cursor.execute(f"UPDATE SHOT SET LENGTH = 0.01 WHERE ID = {row[0]}") conn.commit() if len(issue) > 0: log.warning(f"Table des SHOT, visée(s) bloquante(s), même départ et arrivée, longueur nulle supprimée(s), nbre: {Colors.ENDC}{len(issue)}") # print(f"Visée(s) bloquante(s) supprimée(s) {issue}") else: log.info("Table des SHOT, aucune visée bloquante") except sqlite3.Error as e: log.error(f"Erreur lors de l'exécution de la requête (Issue_SHOT) code:{Colors.ENDC} {e}") error_count += 1 ##################################################################################################################################### # Fonction pour marquer les stations d'habillage # ##################################################################################################################################### def marquage_visee_station_habillage(): global error_count try: cursor.execute(""" SELECT STATION.ID AS STATION_ID, SHOT.ID AS SHOT_ID FROM STATION JOIN SHOT ON SHOT.TO_ID = STATION.ID WHERE STATION.NAME = '.' or STATION.NAME = '-' """) filtre = cursor.fetchall() log.info(f"Marquage des visées et des stations d'habillage, nbre: {Colors.ENDC}{len(filtre)}") for row in filtre: cursor.execute(f"UPDATE _JONCTION SET STATION_TYPE = 'hab' WHERE STATION_ID = {row[0]}") cursor.execute(f"UPDATE _VISEE_FLAG SET SERIE_ID = -1 WHERE SHOT_ID = {row[1]}") conn.commit() except sqlite3.Error as e: log.error(f"Erreur lors de l'exécution de la requête (marquage_station_habillage):{Colors.ENDC} {e}") error_count += 1 ##################################################################################################################################### # Fonction pour suivre une série jusqu'au prochain départ ou une jonction # ##################################################################################################################################### def suivi_serie(_Current_Serie_ID, bar): global avt_compteur global error_count try: cursor.execute(f"SELECT * FROM _SERIE WHERE SERIE_ID = {_Current_Serie_ID}") _Serie = cursor.fetchall() # if _Current_Serie_ID == 2 or _Current_Serie_ID == 3: # print("Debug, a suivre") _Current_Next_Station = 0 _Current_Shot = 0 _Current_Nre_Shot = int(_Serie[0][5]) # type: ignore _Current_Serie_Lenght = float(_Serie[0][6]) # type: ignore _Current_Serie_Lenght_Surface = float(_Serie[0][7]) # type: ignore _Current_Serie_Lenght_Duplicate = float(_Serie[0][8]) # type: ignore _Direction = int(_Serie[0][9]) _Current_Ent = int(_Serie[0][10]) if _Direction == 0: # print(f"\033[34mA gérer séries sans direction station série: {_Current_Serie_ID}{Colors.ENDC}") # type: ignore _Current_Station_ID = int(_Serie[0][2]) Next_Station_ID_1 = sql_station_depart(_Current_Station_ID) Next_Station_ID_2 = sql_station_arrivee(_Current_Station_ID) if len(Next_Station_ID_1) == 0 and len(Next_Station_ID_2) == 0: # type: ignore # Pas de départ fin et pas d'arrivée : fin de la série # Next_Station_ID = Next_Station_ID_1 cursor.execute(f"UPDATE _SERIE SET SERIE_NBRE_SHOT = 0 WHERE SERIE_ID = {_Current_Serie_ID};") conn.commit() return elif len(Next_Station_ID_1) == 1 and len(Next_Station_ID_2) == 0: # type: ignore # Un départ pas d'arrivée # Next_Station_ID = Next_Station_ID_1 # Direction = 1 cursor.execute(f"UPDATE _SERIE SET DIRECTION = 1 WHERE SERIE_ID = {_Current_Serie_ID};") conn.commit() elif len(Next_Station_ID_1) == 0 and len(Next_Station_ID_2) == 1: # type: ignore # Une arrivée pas de départ # Next_Station_ID = Next_Station_ID_2 _Serie[0][4] = _Serie[0][2] # Direction = -1 cursor.execute(f"UPDATE _SERIE SET DIRECTION = -1 WHERE SERIE_ID = {_Current_Serie_ID};") conn.commit() else: # A gérer nouvelles séries # nouvelles_series(_Current_Station_ID, _Current_Station_ID_Old, _Current_Serie_ID, 1, _Current_Ent) # type: ignore # print (f"\033[34m\tA vérifier dans suivi_serie nouvelles séries inverses depuis {_Current_Station_ID} - {Next_Station_ID_2}, {Next_Station_ID_1}{Colors.ENDC}") # nouvelles_series(_Current_Station_ID, _Current_Station_ID_Old, _Current_Serie_ID, -1, _Current_Ent) return elif _Direction == -1: _Current_Station_ID = int(_Serie[0][4]) _Next_Station_ID = sql_station_arrivee(_Current_Station_ID) # type: ignore _Current_Nre_Shot = 0 # print(f"Début suivi serie inverse {_Current_Serie_ID} Station_ID: {_Current_Station_ID} Nre: {_Current_Nre_Shot} Next station: {_Next_Station_ID}") # type: ignore _ID_Suite = 0 _Force = False if len(_Next_Station_ID) > 1: # type: ignore while int(_Next_Station_ID[_ID_Suite][0]) != int(_Serie[0][2]): # type: ignore _ID_Suite += 1 if _ID_Suite >= len(_Next_Station_ID): # type: ignore # print(f"\033[34mA vérifier, pas de suite trouvée à la serie inverse: {_Current_Serie_ID} station:{_Current_Station_ID}, shot: {_Current_Shot}{Colors.ENDC}") # error_count += 1 return while (len(_Next_Station_ID) == 1) or (_Force == False): # type: ignore # if _Current_Station_ID == 12074: # print("Debug, a suivre") _Force = True _Current_Nre_Shot += 1 _Current_Serie_Lenght += _Next_Station_ID[_ID_Suite][1] # type: ignore _Current_Serie_Lenght_Surface += _Next_Station_ID[_ID_Suite][2] # type: ignore _Current_Serie_Lenght_Duplicate += _Next_Station_ID[_ID_Suite][3] # type: ignore _Current_Shot = _Next_Station_ID[_ID_Suite][4] # type: ignore _Current_Next_Station = int(_Next_Station_ID[_ID_Suite][0]) # type: ignore _Current_Old_Station = int(_Current_Station_ID) test_jonction(_Current_Next_Station, _Current_Serie_ID, _Current_Ent) # type: ignore cursor.execute(f""" UPDATE _SERIE SET SERIE_DEP_ID = {_Current_Serie_ID}, STATION_DEP_ID = {_Current_Next_Station}, SERIE_NBRE_Shot = {_Current_Nre_Shot}, SERIE_LENGHT = {_Current_Serie_Lenght}, SERIE_LENGHT_SURFACE = {_Current_Serie_Lenght_Surface}, SERIE_LENGHT_DUPLICATE = {_Current_Serie_Lenght_Duplicate} WHERE SERIE_ID = {_Current_Serie_ID}; """) cursor.execute(f""" UPDATE _JONCTION SET STATION_TYPE = 'inv', ENTREE_ID = {_Current_Ent}, SERIE_RANG = {_Current_Nre_Shot}, SERIE_ID = {_Current_Serie_ID} WHERE STATION_ID = {_Current_Station_ID} """) cursor.execute(f""" UPDATE _VISEE_FLAG SET SERIE_ID = {_Current_Serie_ID}, ENTREE_ID = {_Current_Ent}, SERIE_RANG = {_Current_Nre_Shot} WHERE SHOT_ID = {_Current_Shot} """) # print(f"Suivi serie inverse {_Current_Serie_ID} Station_ID: {_Current_Station_ID} Nre: {_Current_Nre_Shot}, long: {_Current_Serie_Lenght:.2f}, Next station: {_Next_Station_ID}") conn.commit() depart = sql_station_depart(_Current_Station_ID) if len(depart) >= 1: # type: ignore # print(f'Départ direct à gérer station: {_Current_Station_ID} série: {_Current_Serie_ID}, nbre shot: {_Current_Nre_Shot}, long: {_Current_Serie_Lenght:.2f}, Arrivée(s) {depart}') nouvelles_series(_Current_Station_ID, _Current_Old_Station, _Current_Serie_ID, 1, _Current_Ent) # type: ignore _Current_Station_ID = int(_Next_Station_ID[_ID_Suite][0]) # type: ignore _Next_Station_ID = sql_station_arrivee(_Current_Next_Station) _ID_Suite = 0 cursor.execute(f""" UPDATE _SERIE SET SERIE_DEP_ID = {_Current_Serie_ID}, STATION_DEP_ID = {_Current_Next_Station}, SERIE_NBRE_Shot = {_Current_Nre_Shot}, SERIE_LENGHT = {_Current_Serie_Lenght}, SERIE_LENGHT_SURFACE = {_Current_Serie_Lenght_Surface}, SERIE_LENGHT_DUPLICATE = {_Current_Serie_Lenght_Duplicate} WHERE SERIE_ID = {_Current_Serie_ID}; """) # if _Current_Station_ID == 5047 : # print("debug point") cursor.execute(f""" UPDATE _JONCTION SET STATION_TYPE = 'arv', ENTREE_ID = {_Current_Ent}, SERIE_RANG = {_Current_Nre_Shot}, SERIE_ID = {_Current_Serie_ID} WHERE STATION_ID = {_Current_Station_ID} """) cursor.execute(f""" UPDATE _VISEE_FLAG SET SERIE_ID = {_Current_Serie_ID}, ENTREE_ID = {_Current_Ent}, SERIE_RANG = {_Current_Nre_Shot} WHERE SHOT_ID = {_Current_Shot} """) conn.commit() if _Current_Nre_Shot > 1: avt_compteur = avt_compteur + _Current_Nre_Shot - 1 bar(_Current_Nre_Shot - 1) # _Current_Next_Station = int(_Next_Station_ID[0][0]) # type: ignore depart = sql_station_depart(_Current_Station_ID) # type: ignore if len(_Next_Station_ID) == 0: # type: ignore # fin de la série # print (f"Fin de la série inverse: {_Current_Serie_ID} (pas de suite) station: {_Current_Station_ID}, nbre de shot: {_Current_Nre_Shot}, long: {_Current_Serie_Lenght:.2f}") nouvelles_series(_Current_Station_ID, _Current_Old_Station, _Current_Serie_ID, 1, _Current_Ent) # type: ignore if len(depart) >= 1: # type: ignore nouvelles_series(_Current_Station_ID, _Current_Old_Station, _Current_Serie_ID, -1, _Current_Ent) # type: ignore else: nouvelles_series(_Current_Station_ID, _Current_Old_Station, _Current_Serie_ID, -1, _Current_Ent) # type: ignore # print (f"Fin de la série inverse: {_Current_Serie_ID} station: {_Current_Station_ID}, nbre de shot: {_Current_Nre_Shot}, long: {_Current_Serie_Lenght:.2f}") if len(depart) >= 1: # type: ignore nouvelles_series(_Current_Station_ID, _Current_Old_Station, _Current_Serie_ID, 1, _Current_Ent) # type: ignore elif _Direction == 1: _Current_Station_ID = int(_Serie[0][2]) _Next_Station_ID = sql_station_depart(_Current_Station_ID) _Current_Nre_Shot = 0 # print(f"Début suivi serie directe {_Current_Serie_ID} Station_ID: {_Current_Station_ID} Nre: {_Current_Nre_Shot} Next station: {_Next_Station_ID}") _ID_Suite = 0 _Force = False if len(_Next_Station_ID) > 1: # type: ignore while int(_Next_Station_ID[_ID_Suite][0]) != int(_Serie[0][4]): # type: ignore _ID_Suite += 1 if _ID_Suite >= len(_Next_Station_ID): # type: ignore # print(f"\033[34mA vérifier, pas de suite trouvée à la serie directe: {_Current_Serie_ID}, Station: {_Current_Station_ID}, shot: {_Current_Shot}{Colors.ENDC}") # error_count += 1 return while (len(_Next_Station_ID) == 1) or (_Force == False): # type: ignore # if _Current_Station_ID == 12074: # print("Debug, a suivre") _Force = True _Current_Nre_Shot += 1 _Current_Serie_Lenght += _Next_Station_ID[0][1] # type: ignore _Current_Serie_Lenght_Surface += _Next_Station_ID[_ID_Suite][2] # type: ignore _Current_Serie_Lenght_Duplicate += _Next_Station_ID[_ID_Suite][3] # type: ignore _Current_Shot = _Next_Station_ID[_ID_Suite][4] # type: ignore _Current_Next_Station = int(_Next_Station_ID[0][0]) # type: ignore _Current_Old_Station = int(_Current_Station_ID) test_jonction(_Current_Next_Station, _Current_Serie_ID, _Current_Ent) # type: ignore cursor.execute(f""" UPDATE _SERIE SET SERIE_DEP_ID = {_Current_Serie_ID}, STATION_DEP_ID = {_Current_Next_Station}, SERIE_NBRE_Shot = {_Current_Nre_Shot}, SERIE_LENGHT = {_Current_Serie_Lenght}, SERIE_LENGHT_SURFACE = {_Current_Serie_Lenght_Surface}, SERIE_LENGHT_DUPLICATE = {_Current_Serie_Lenght_Duplicate} WHERE SERIE_ID = {_Current_Serie_ID}; """) # if _Current_Station_ID == 5035 : # print("debug point") cursor.execute(f""" UPDATE _JONCTION SET STATION_TYPE = 'dir', ENTREE_ID = {_Current_Ent}, SERIE_RANG = {_Current_Nre_Shot}, SERIE_ID = {_Current_Serie_ID} WHERE STATION_ID = {_Current_Station_ID} """) cursor.execute(f""" UPDATE _VISEE_FLAG SET SERIE_ID = {_Current_Serie_ID}, ENTREE_ID = {_Current_Ent}, SERIE_RANG = {_Current_Nre_Shot} WHERE SHOT_ID = {_Current_Shot} """) conn.commit() # print(f"Suivi serie directe {_Current_Serie_ID} Station_ID: {_Current_Station_ID} Nre: {_Current_Nre_Shot} Next station: {_Next_Station_ID}") arrivee = sql_station_arrivee(_Current_Station_ID) if len(arrivee) >= 1: # type: ignore # print(f'Arrivée à gérer station: {_Current_Station_ID} série: {_Current_Serie_ID}, nbre shot: {_Current_Nre_Shot}, long: {_Current_Serie_Lenght:.2f}, Arrivée(s) {arrivee}') nouvelles_series(_Current_Station_ID, _Current_Old_Station, _Current_Serie_ID, -1, _Current_Ent) # type: ignore _Current_Station_ID = int(_Next_Station_ID[0][0]) # type: ignore _Next_Station_ID = sql_station_depart(_Current_Next_Station) _ID_Suite = 0 cursor.execute(f""" UPDATE _SERIE SET SERIE_DEP_ID = {_Current_Serie_ID}, STATION_DEP_ID = {_Current_Next_Station}, SERIE_NBRE_Shot = {_Current_Nre_Shot}, SERIE_LENGHT = {_Current_Serie_Lenght}, SERIE_LENGHT_SURFACE = {_Current_Serie_Lenght_Surface}, SERIE_LENGHT_DUPLICATE = {_Current_Serie_Lenght_Duplicate} WHERE SERIE_ID = {_Current_Serie_ID}; """) # type: ignore cursor.execute(f""" UPDATE _JONCTION SET STATION_TYPE = 'end', ENTREE_ID = {_Current_Ent}, SERIE_RANG = {_Current_Nre_Shot}, SERIE_ID = {_Current_Serie_ID} WHERE STATION_ID = {_Current_Station_ID} """) cursor.execute(f""" UPDATE _VISEE_FLAG SET SERIE_ID = {_Current_Serie_ID}, ENTREE_ID = {_Current_Ent}, SERIE_RANG = {_Current_Nre_Shot} WHERE SHOT_ID = {_Current_Shot} """) conn.commit() if _Current_Nre_Shot > 1: avt_compteur = avt_compteur + _Current_Nre_Shot - 1 bar(_Current_Nre_Shot - 1) arrivee = sql_station_arrivee(_Current_Next_Station) # type: ignore if len(_Next_Station_ID) == 0: # type: ignore # fin de la série # print (f"Fin de la série directe: {_Current_Serie_ID} (pas de suite) à la station: {_Current_Station_ID}, nbre de shot: {_Current_Nre_Shot}, long: {_Current_Serie_Lenght:.2f}") nouvelles_series(_Current_Station_ID, _Current_Old_Station, _Current_Serie_ID, -1, _Current_Ent) # type: ignore if len(arrivee) >= 1: # type: ignore nouvelles_series(_Current_Station_ID, _Current_Old_Station, _Current_Serie_ID, 1, _Current_Ent) # type: ignore else: nouvelles_series(_Current_Station_ID, _Current_Old_Station, _Current_Serie_ID, 1, _Current_Ent) # type: ignore # print (f"Fin de la série directe: {_Current_Serie_ID} station: {_Current_Station_ID}, nbre de shot: {_Current_Nre_Shot}, long: {_Current_Serie_Lenght:.2f}") if len(arrivee) >= 1: # type: ignore nouvelles_series(_Current_Station_ID, _Current_Old_Station, _Current_Serie_ID, -1, _Current_Ent) # type: ignore except sqlite3.Error as e: log.error( f"Erreur lors de l'exécution de la requête de lecture de la série{Colors.ENDC} {_Current_Serie_ID}{Colors.ERROR}, suivi_serie:{Colors.ENDC} {e}" ) error_count += 1 return return ##################################################################################################################################### # Fonction pour créer les nouvelles séries à une station # ##################################################################################################################################### def nouvelles_series(_Current_Station_ID, _Current_Old_Station, _Current_Serie_ID, _DIRECTION, _STATION_ENT_ID): global error_count # if _Current_Serie_ID == 2 or _Current_Serie_ID == 3: # print("Debug, a suivre") try: if _DIRECTION == 1: _Next_Station = sql_station_depart(_Current_Station_ID) # cursor.execute(f""" # SELECT SHOT.TO_ID as TO_ID_RESULT # FROM SHOT # WHERE SHOT.FROM_ID = {_Current_Station_ID} # -- AND ( SELECT SHOT.TO_ID FROM SHOT WHERE SHOT.FROM_ID = TO_ID_RESULT) # """) # _Next_Station = cursor.fetchall() elif _DIRECTION == -1: _Next_Station = sql_station_arrivee(_Current_Station_ID) # cursor.execute(f""" # SELECT SHOT.FROM_ID as FROM_ID_RESULT # FROM SHOT # WHERE SHOT.TO_ID = {_Current_Station_ID} # -- AND ( SELECT SHOT.FROM_ID FROM SHOT WHERE SHOT.TO_ID = FROM_ID_RESULT ) # """) # _Next_Station = cursor.fetchall() if _Next_Station is None: # type: ignore log.warning(f"Pas de série crées à la station: {Colors.ENDC}{_Current_Station_ID}") return # boucle sur liste _Next_Station for Depart in _Next_Station: # type: ignore if _Current_Old_Station != Depart[0]: # type: ignore cursor.execute(f"UPDATE _JONCTION SET SERIE_JONC = {_Current_Serie_ID} WHERE STATION_ID = {_Current_Station_ID};") cursor.execute(f"UPDATE _JONCTION SET ENTREE_ID = {_STATION_ENT_ID} WHERE STATION_ID = {_Current_Station_ID};") cursor.execute(f"UPDATE _JONCTION SET STATION_JONC = {Depart[0]} WHERE STATION_ID = {_Current_Station_ID};") cursor.execute("UPDATE _JONCTION SET STATION_TYPE = ? WHERE id = ?", ("jon", _Current_Station_ID)) if _DIRECTION == 1: cursor.execute( """ INSERT INTO _SERIE ( SERIE_DEP_ID, STATION_DEP_ID, SERIE_ARR_ID , STATION_ARR_ID, SERIE_NBRE_SHOT, SERIE_LENGHT, SERIE_LENGHT_SURFACE, SERIE_LENGHT_DUPLICATE, DIRECTION, STATION_ENT_ID) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""", (_Current_Serie_ID, _Current_Station_ID, -1, Depart[0], -1, 0.0, 0.0, 0.0, 1, _STATION_ENT_ID), ) conn.commit() # print(f"Création Série directe: {cursor.lastrowid} depuis la station: {_Current_Station_ID} vers {Depart[0]} ") elif _DIRECTION == -1: cursor.execute( """ INSERT INTO _SERIE ( SERIE_DEP_ID, STATION_DEP_ID, SERIE_ARR_ID , STATION_ARR_ID, SERIE_NBRE_SHOT, SERIE_LENGHT, SERIE_LENGHT_SURFACE, SERIE_LENGHT_DUPLICATE, DIRECTION, STATION_ENT_ID) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""", (-1, Depart[0], _Current_Serie_ID, _Current_Station_ID, -1, 0.0, 0.0, 0.0, -1, _STATION_ENT_ID), ) conn.commit() # print(f"Création Série inv.: {cursor.lastrowid} depuis {Depart[0]} vers la station: {_Current_Station_ID}") except sqlite3.Error as e: log.error(f"Erreur lors de la requête (nouvelle_serie):{Colors.ENDC} {e}") error_count += 1 return ##################################################################################################################################### # Fonction pour tester si la station a déjà été lue # ##################################################################################################################################### def test_jonction(station, serie, entree): global error_count try: cursor.execute(f""" -- Requête 6: Détection des départs depuis une station (visée directe) SELECT SHOT.TO_ID as TO_ID_RESULT, --_JONCTION.STATION_TYPE, SHOT.LENGTH, CASE WHEN SHOT_FLAG.FLAG = 'srf' THEN SHOT.LENGTH ELSE 0 END AS LENGTH_SRF, CASE WHEN SHOT_FLAG.FLAG = 'dpl' THEN SHOT.LENGTH ELSE 0 END AS LENGTH_DPL, SHOT.ID -- SHOT_FLAG.FLAG as Type_Flag FROM SHOT --JOIN _JONCTION ON SHOT.TO_ID = _JONCTION.STATION_ID LEFT JOIN SHOT_FLAG ON SHOT.ID = SHOT_FLAG.SHOT_ID WHERE SHOT.FROM_ID = {station} -- AND _JONCTION.STATION_TYPE IS NULL -- AND ( SELECT SHOT.TO_ID FROM SHOT WHERE SHOT.FROM_ID = TO_ID_RESULT) """) depart = cursor.fetchall() cursor.execute(f""" -- Requête 7: Détection des arrivées depuis une station (Visée inverse) SELECT SHOT.FROM_ID as FROM_ID_RESULT, --_JONCTION.STATION_TYPE, SHOT.LENGTH, CASE WHEN SHOT_FLAG.FLAG = 'srf' THEN SHOT.LENGTH ELSE 0 END AS LENGTH_SRF, CASE WHEN SHOT_FLAG.FLAG = 'dpl' THEN SHOT.LENGTH ELSE 0 END AS LENGTH_DPL, SHOT.ID -- SHOT_FLAG.FLAG FROM SHOT --JOIN _JONCTION ON SHOT.FROM_ID = _JONCTION.STATION_ID LEFT JOIN SHOT_FLAG ON SHOT.ID = SHOT_FLAG.SHOT_ID WHERE SHOT.TO_ID = {station} --AND _JONCTION.STATION_TYPE IS NULL --AND ( SELECT _JONCTION.STATION_TYPE FROM _JONCTION WHERE SHOT.TO_ID = FROM_ID_RESULT """) arrivee = cursor.fetchall() total = arrivee + depart # type: ignore for row in total: # type: ignore cursor.execute(f"SELECT _JONCTION.STATION_TYPE FROM _JONCTION WHERE _JONCTION.STATION_ID = {row[0]}") # if row[1] == 5017: # print('Debug point') retour = cursor.fetchall() val = str(retour[0]) if val != "(None,)": cursor.execute("UPDATE _JONCTION SET STATION_TYPE = ? WHERE id = ?", ("jon", row[0])) cursor.execute(f"SELECT _JONCTION.ENTREE_ID FROM _JONCTION WHERE _JONCTION.STATION_ID = {row[0]}") retour = cursor.fetchall() cursor.execute(f"SELECT _JONCTION.SERIE_ID FROM _JONCTION WHERE _JONCTION.STATION_ID = {row[0]}") _serie = cursor.fetchall() # print (f"Jonction à proximité de la Station_ID: {row[0]}, retour: {str(val)}, serie {serie} - {_serie[0][0]}, entrée {entree} - {retour[0][0]}") if (retour[0][0] != entree) and (retour[0][0] != None): log.info( f"Jonction à la Station_ID: {Colors.ENDC}{row[0]:>6}{Colors.INFO} entre les entrées {Colors.ENDC}{entree:>6}{Colors.INFO} et {Colors.ENDC}{retour[0][0]:>6}{Colors.YELLOW}" ) cursor.execute("INSERT INTO _RESEAU ( STATION_JONC, ENT_1, ENT_2) VALUES (?, ?, ?)", (row[0], entree, retour[0][0])) conn.commit() # if _serie[0][0] != serie and (_serie[0][0] != None): # print (f"\033[34m\tJonction à la Station_ID: {row[0]} entre les series {serie} et {_serie[0][0]}{Colors.ENDC}") cursor.execute(f"SELECT _JONCTION.STATION_TYPE FROM _JONCTION WHERE _JONCTION.STATION_ID = {station}") retour = cursor.fetchall() val = str(retour[0]) if val == "(None,)": # print (f"Pas de jonction à la Station_ID: {station}, retour: {val}") return False else: cursor.execute("UPDATE _JONCTION SET STATION_TYPE = ? WHERE id = ?", ("jon", station)) cursor.execute(f"SELECT _JONCTION.ENTREE_ID FROM _JONCTION WHERE _JONCTION.STATION_ID = {station}") retour = cursor.fetchall() cursor.execute(f"SELECT _JONCTION.SERIE_ID FROM _JONCTION WHERE _JONCTION.STATION_ID = {station}") _serie = cursor.fetchall() # print (f"Jonction à proximité de la Station_ID: {row[0]}, retour: {str(val)}, serie {serie} - {_serie[0][0]}, entrée {entree} - {retour[0][0]}") if retour[0][0] != entree: log.info( f"Jonction à la Station_ID: {Colors.ENDC}{station:>6}{Colors.INFO} entre les entrées {Colors.ENDC}{entree:>6}{Colors.INFO} et {Colors.ENDC}{retour[0][0]:>6}{Colors.YELLOW}" ) if _serie[0][0] != serie: log.info( f"Jonction à la Station_ID: {Colors.ENDC}{station:>6}{Colors.INFO} entre les séries {Colors.ENDC}{serie:>6}{Colors.INFO} et {Colors.ENDC}{_serie[0][0]:>6}{Colors.YELLOW}" ) return True except sqlite3.Error as e: log.error(f"Erreur lors de l'exécution de la requêtes (test_jonction): {Colors.ENDC}{e}") error_count += 1 return ##################################################################################################################################### # Nombres au format 'french' # ##################################################################################################################################### def format_french_number(value): """Formate un nombre en style français ou retourne la valeur si ce n'est pas un nombre""" try: # Essayer de convertir en float si ce n'est pas déjà un nombre if not isinstance(value, (int, float)): # Si c'est une chaîne qui ressemble à un nombre, on la convertit if isinstance(value, str): # Nettoyer la chaîne (enlever espaces, virgules, etc.) cleaned = value.replace(" ", "").replace(",", ".") if cleaned.replace("-", "").replace(".", "").isdigit(): value = float(cleaned) else: return value else: return value # Formatage du nombre if isinstance(value, float) and (value != value or abs(value) == float("inf")): # noqa: PLR0124 return value # NaN ou infini sign = "-" if value < 0 else "" val_abs = abs(value) formatted = f"{val_abs:,.2f}".replace(",", " ").replace(".", ",") return f"{sign}{formatted}" except (ValueError, TypeError, AttributeError): # Retourner la valeur originale en cas d'erreur return value ##################################################################################################################################### # Fonction pour exécuter une requête et sauvegarder les résultats dans un fichier texte # ##################################################################################################################################### def calcul_stats(output_file_csv, output_file_md, filename="None"): global error_count output_file_ligne_md = [] output_file_ligne_md.append("-------------\n") output_file_ligne_csv = [] try: ##################################################################################################################################### # Phase 5 # Enregistrement des résultats dans un fichier ##################################################################################################################################### log.info( f"{Colors.UNDERLINE}Phase 5:{Colors.ENDC}{Colors.INFO} Écriture des statistiques dans le fichier: {Colors.ENDC}{safe_relpath(output_file_md, 2)}.md" ) ############################################################################################################### # Général ############################################################################################################### results = sql_Centerline_length() cursor.execute("SELECT COUNT(*) AS nbre FROM _JONCTION WHERE STATION_TYPE IS NULL") _compteur = cursor.fetchall() compteur = int(_compteur[0][0]) results2 = sql_bilan_reseaux() results3 = sql_bilan_annee() Rose(output_file_name_rose) Shot_lengths_histogram(output_file_name_histo) base_name = sql_base_name() findetraitement = datetime.now() # noqa: DTZ005 duree = findetraitement - maintenant jours, secondes = divmod(duree.seconds, 86400) # 86400 secondes dans une journée # noqa: RUF059 heures, secondes = divmod(secondes, 3600) # 3600 secondes dans une heure minutes, secondes = divmod(secondes, 60) # 60 secondes dans une minute if duree.seconds > 3600: duree_formatee = f"{heures:02} (h) {minutes:02} (m) {secondes:02} (s)" elif duree.seconds > 60: duree_formatee = f"{minutes:02} (m) {secondes:02} (s)" else: duree_formatee = f"{secondes:02} (s)" ############################################################################################################### # Fichiers type markdown ############################################################################################################### output_file_ligne_md.append(f"# Statistiques de `{base_name}`\n") output_file_ligne_md.append("--------------\n\n") output_file_ligne_md.append( f"### Développement total\n\n" f"Développement topographié: \t`{format_french_number(results[0][0])} (m)`\n" # type: ignore f"Développement topographie dupliqués: \t`{format_french_number(results[0][1])} (m)`\n" # type: ignore f"Développement topographie de surface:\t`{format_french_number(results[0][2])} (m)`\n" # type: ignore f"Soit un grand total de : \t`{format_french_number(results[0][0] + results[0][1] + results[0][2])} (m)`\n" # type: ignore ) if compteur > 0: # type: ignore output_file_ligne_md.append(f"> [!WARNING] `{compteur}` station(s) non comptabilisée(s) et raccordée(s)\n\n") else: output_file_ligne_md.append("Toutes les stations sont comptabilisées et raccordées\n\n") output_file_ligne_md.append("\n--------------\n") if results2[0][0] != None: # type: ignore output_file_ligne_md.append("### Développement total par réseau\n") headers = [ " Réseau ", " Entrée(s) ", " Nbre ", " Dev. (m) ", " Prof. (m) ", " Dupl. (m) ", " Surf. (m)", " Visées ", " ID Stat. ", " Alt. min (m) ", " ID Stat. ", " Alt. max (m) ", ] output_file_ligne_md.append("| " + " | ".join(headers) + " |\n") output_file_ligne_md.append("|" + "|".join(["------------"] * len(headers)) + "|\n") vals = results2[1] def fmt(v, idx): if v is None: return "" return format_french_number(v) if idx in (3, 4, 5, 6, 9, 11) else str(v).replace(" ", "") first = fmt(vals[0], 0) if vals[0] is not None else " " reste = " | ".join(f"**{fmt(v, i + 1)}**" for i, v in enumerate(vals[1:])) output_file_ligne_md.append(f"| {first}" + (f" | {reste}" if reste else "") + " |\n") for row in results2[2:]: # type: ignore # clean_row = (v.strip() for v in row) # _row = [format_french_number(v) if idx in (3, 4, 5, 6, 9, 11) else str(v) for idx, v in enumerate(clean_row)] clean_row = (str(v).strip() if v is not None else "" for v in row) _row = [format_french_number(v) if idx in (3, 4, 5, 6, 9, 11) else v for idx, v in enumerate(clean_row)] formatted_row = [str(v) for v in _row] output_file_ligne_md.append("| " + " | ".join(formatted_row) + " |\n") if results3[0][0] != None: # type: ignore output_file_ligne_md.append("\n\n--------------\n") output_file_ligne_md.append("\n### Développement total topographié par année(s)\n") headers = [" Année ", "Dev. (m)", "Cumul (m)", "Dupl. (m)", "Cumul (m)", "Surf. (m)", "Cumul (m)"] output_file_ligne_md.append("| " + " | ".join(headers) + " |\n") output_file_ligne_md.append("|" + "|".join(["---"] * len(headers)) + "|\n") for row in results3[1:]: # type: ignore if row[1].strip() != "0.00" or row[3].strip() != "0.00" or row[5].strip() != "0.00": _row = [format_french_number(v) if idx in (1, 2, 3, 4, 5, 6) else str(v) for idx, v in enumerate(row)] formatted_row = [str(v) for v in _row] output_file_ligne_md.append("| " + " | ".join(formatted_row) + " |\n") output_file_ligne_md.append("\n\n--------------\n") output_file_ligne_md.append( "### Graphiques\n\n" f"""