diff --git a/Scripts/pyCreateTh/.vscode/settings.json b/Scripts/pyCreateTh/.vscode/settings.json index ba24b63..8e4afec 100644 --- a/Scripts/pyCreateTh/.vscode/settings.json +++ b/Scripts/pyCreateTh/.vscode/settings.json @@ -1,5 +1,6 @@ { "cSpell.words": [ + "altc", "annee", "ansi", "ARSIP", @@ -10,21 +11,37 @@ "Backsights", "beijing", "buildparam", + "buildthconfig", + "Carth", + "carthesian", "cavename", "centerlines", + "centi", + "checkfiles", "clarke", "clino", "CLINO", "colwidth", + "Commecial", "containging", "coordsyst", "cumcount", + "Cylp", + "cylpolar", + "datal", "dataold", "datat", "datathwritetools", + "Deca", + "décommenter", + "Degd", + "deniv", + "Deniv", "depmatch", "depthchange", "depthre", + "dictcave", + "dictl", "downcasting", "drawnexemptextendedre", "drawnexemptplanre", @@ -32,9 +49,11 @@ "drawnre", "ecart", "ecarts", + "elems", "ENDC", "endcenterline", "endlayout", + "endmap", "endscrap", "endsurvey", "equats", @@ -45,53 +64,105 @@ "explo", "fnme", "formated", + "fromcount", + "FURB", "geocentricdatumofaustralia", "geocentricofaustralia", "Geophysicaya", + "github", + "hskip", "icomments", "icoupe", + "iline", "isin", "istructure", + "ithc", + "ithconfig", "Koef", "Larra", + "latc", "lengthre", "lenmatch", + "lensurv", "levelname", "levelno", "linex", + "longc", "LRUD", + "lruddir", "migovec", + "mkfle", "NODRAW", "Noeuds", "northamerican", "northamericandatum", + "nostring", + "nosurvey", "nouvelletriangulationfrançaise", + "pdfs", "pulkovo", "pytro", "resultats", "roth", "rsuffix", + "scompass", "sinfo", "sirgas", + "slopesurv", + "smeters", + "sourcefiles", "southamerican", "southamericandatum", "syscoord", "tendcenterline", + "tendcode", "thanksto", + "Thbook", + "thcfnme", "thconfig", + "thconfigfnme", + "thcoords", + "thcpath", "therion", + "thjunk", "thlang", + "thlocation", + "thmaps", + "thsizel", + "thsizem", + "thsizexl", + "thtot", + "tocount", + "Topof", "topofil", "totdata", "totfile", "triees", "trox", + "typelem", + "typelen", + "typem", + "unitclino", + "unitcounter", "Urruty", "UUUUDDDDSSSB", "UUUUDDDDSSSBL", "UUUUDDDDSSSSSBL", + "versionfle", "Visualtopo", + "vtopo", + "vtopotools", + "Vulc", "wpage", - "XTHERION" + "writecenterlineheader", + "writedata", + "writethc", + "writethconfig", + "xavier", + "xcoord", + "XTHERION", + "xvigrid", + "xviscale", + "ycoord" ] -} +} \ No newline at end of file diff --git a/Scripts/pyCreateTh/Lib/general_fonctions.py b/Scripts/pyCreateTh/Lib/general_fonctions.py index 54e1a88..42f499f 100644 --- a/Scripts/pyCreateTh/Lib/general_fonctions.py +++ b/Scripts/pyCreateTh/Lib/general_fonctions.py @@ -2,12 +2,13 @@ !############################################################################################# # # # general_fonctions.py for pyCreateTh.py # -# # +# # !############################################################################################# Alex 2025 06 09 """ -import os, logging, sys, re, configparser, unicodedata, shutil + +import os, logging, sys, re, configparser, unicodedata, shutil # noqa: I001 from pathlib import Path import Lib.global_data as global_Data from datetime import datetime @@ -21,36 +22,38 @@ log = logging.getLogger("Logger") # Couleurs ANSI par niveau de log ################################################################################################# COLOR_CODES = { - logging.DEBUG: "\033[94m", # Bleu - logging.INFO: "\033[92m", # Vert - logging.WARNING: "\033[95m", # MAGENTA - logging.ERROR: "\033[91m", # Rouge + logging.DEBUG: "\033[94m", # Bleu + logging.INFO: "\033[92m", # Vert + logging.WARNING: "\033[95m", # MAGENTA + logging.ERROR: "\033[91m", # Rouge logging.CRITICAL: "\033[1;91m", # Rouge vif } RESET = "\033[0m" + ################################################################################################# # Codes de couleur ANSI class Colors: - BLACK = '\033[90m' - RED = '\033[91m' - GREEN = '\033[92m' - YELLOW = '\033[93m' - BLUE = '\033[94m' - MAGENTA = '\033[95m' - CYAN = '\033[96m' - WHITE = '\033[97m' - - ERROR = '\033[91m' - WARNING = '\033[95m' - HEADER = '\033[96m' - DEBUG = '\033[94m' # Bleu - INFO = '\033[92m' # Vert - CRITICAL = '\033[1;91m', # Rouge vif - - ENDC = '\033[0m' - BOLD = '\033[1m' - UNDERLINE = '\033[4m' + BLACK = "\033[90m" + RED = "\033[91m" + GREEN = "\033[92m" + YELLOW = "\033[93m" + BLUE = "\033[94m" + MAGENTA = "\033[95m" + CYAN = "\033[96m" + WHITE = "\033[97m" + + ERROR = "\033[91m" + WARNING = "\033[95m" + HEADER = "\033[96m" + DEBUG = "\033[94m" # Bleu + INFO = "\033[92m" # Vert + CRITICAL = ("\033[1;91m",) # Rouge vif + + ENDC = "\033[0m" + BOLD = "\033[1m" + UNDERLINE = "\033[4m" + ################################################################################################# # fonction pour réduire l'affichage des chemins long # @@ -68,12 +71,12 @@ def safe_relpath(path, base_dir=None, max_depth=4, max_name_len=50, prefix="~"): # ── 1. Résolution du chemin ────────────────────────────────────────────── try: path = Path(path).expanduser().resolve() - except Exception: + except Exception: # noqa: BLE001 return str(path) try: base = Path(base_dir).expanduser().resolve() if base_dir else Path.cwd().resolve() - except Exception: + except Exception: # noqa: BLE001 base = None # ── 2. Nom du fichier / dossier (tronqué) ───────────────────────────────── @@ -89,7 +92,7 @@ def safe_relpath(path, base_dir=None, max_depth=4, max_name_len=50, prefix="~"): parts = list(rel.parts) else: raise ValueError - except Exception: + except Exception: # noqa: BLE001 parts = list(path.parts) # ── 4. Cas path == base → "." ──────────────────────────────────────────── @@ -108,11 +111,10 @@ def safe_relpath(path, base_dir=None, max_depth=4, max_name_len=50, prefix="~"): # ── 7. Construction finale sûre ────────────────────────────────────────── try: return os.path.join(*parts) - except Exception: + except Exception: # noqa: BLE001 return name - ################################################################################################# # Coloration des messages d'aide d'arg # ################################################################################################# @@ -124,27 +126,27 @@ def colored_help(parser): parser (argparse.ArgumentParser): Le parseur d'arguments. Returns: None - + """ # Captures the help output help_text = parser.format_help() - + # Coloration des différentes parties - colored_help_text = help_text.replace( - 'usage:', f'{Colors.ERROR}usage:{Colors.ENDC}' - ).replace( - 'options:', f'{Colors.GREEN}options:{Colors.ENDC}' - ).replace('positional arguments:', f'{Colors.BLUE}positional arguments:{Colors.ENDC}' - ).replace(', --help', f'{Colors.BLUE}, --help:{Colors.ENDC}' - ).replace('elp:', f'{Colors.BLUE}elp{Colors.ENDC}') + colored_help_text = ( + help_text.replace("usage:", f"{Colors.ERROR}usage:{Colors.ENDC}") + .replace("options:", f"{Colors.GREEN}options:{Colors.ENDC}") + .replace("positional arguments:", f"{Colors.BLUE}positional arguments:{Colors.ENDC}") + .replace(", --help", f"{Colors.BLUE}, --help:{Colors.ENDC}") + .replace("elp:", f"{Colors.BLUE}elp{Colors.ENDC}") + ) # Surligner les arguments for action in parser._actions: if action.option_strings: # Colorer les options (--xyz) for opt in action.option_strings: - colored_help_text = colored_help_text.replace(opt, f'{Colors.BLUE}{opt}{Colors.ENDC}').replace('--help', f'{Colors.BLUE}--help:{Colors.ENDC}') - + colored_help_text = colored_help_text.replace(opt, f"{Colors.BLUE}{opt}{Colors.ENDC}").replace("--help", f"{Colors.BLUE}--help:{Colors.ENDC}") + # Imprimer le texte coloré print(colored_help_text) sys.exit(1) @@ -164,25 +166,25 @@ def sanitize_filename(thName): Returns: str: The cleaned and compatible string. - + """ # Unicode normalization to replace accented characters with their non-accented equivalents - thName = unicodedata.normalize('NFKD', thName).encode('ASCII', 'ignore').decode('ASCII') + thName = unicodedata.normalize("NFKD", thName).encode("ASCII", "ignore").decode("ASCII") # Replace parentheses with underscores - thName = thName.replace('(', '_').replace(')', '_') + thName = thName.replace("(", "_").replace(")", "_") # Replace illegal characters with an underscore - thName = re.sub(r'[<>:"/\\|?*\']', '_', thName) # Illegal on Windows - thName = re.sub(r'\s+', '_', thName) # Spaces to underscores - thName = re.sub(r'[^a-zA-Z0-9._-]', '_', thName) # Keep only allowed chars + thName = re.sub(r'[<>:"/\\|?*\']', "_", thName) # Illegal on Windows + thName = re.sub(r"\s+", "_", thName) # Spaces to underscores + thName = re.sub(r"[^a-zA-Z0-9._-]", "_", thName) # Keep only allowed chars # Convert to lowercase, then capitalize the first letter # thName = thName.lower().capitalize() # thName = thName.capitalize() - + # Suppression des underscores en début et fin - thName = thName.strip('_') + thName = thName.strip("_") return thName or "default_filename" # Avoid empty result @@ -197,24 +199,24 @@ def select_file_tk_window(): """ # Créer une instance de la fenêtre tkinter root = tk.Tk() - + # Cacher la fenêtre principale root.withdraw() - + # Afficher la boite de dialogue de sélection de fichier file_path = filedialog.askopenfilename( title="Select your file", - filetypes=[ - ("Compatibles files", "*.th *.mak *.dat *.tro *.trox"), - ("MAK files", "*.mak"), - ("TH files", "*.th"), - ("DAT files", "*.dat"), - ("TRO files", "*.tro"), - ("TROX files", "*.trox"), - ("All files", "*.*")] - ) - - + filetypes=[ + ("Compatibles files", "*.th *.mak *.dat *.tro *.trox"), + ("MAK files", "*.mak"), + ("TH files", "*.th"), + ("DAT files", "*.dat"), + ("TRO files", "*.tro"), + ("TROX files", "*.trox"), + ("All files", "*.*"), + ], + ) + return file_path # Retourner le chemin complet du fichier sélectionné @@ -237,58 +239,53 @@ def load_config_old(args, configIni="config.ini"): config.read(config_file, encoding="utf-8") survey_keys = { - 'Author': 'Author', - 'Copyright1': 'Copyright', - 'Copyright2': 'Copyright', - 'Copyright3': 'Copyright', - 'Copyright_Short': None, - 'map_comment': 'mapComment', - 'club': 'club', - 'thanksto': 'thanksto', - 'datat': 'datat', - 'wpage': 'wpage', - 'cs': 'cs' + "Author": "Author", + "Copyright1": "Copyright", + "Copyright2": "Copyright", + "Copyright3": "Copyright", + "Copyright_Short": None, + "map_comment": "mapComment", + "club": "club", + "thanksto": "thanksto", + "datat": "datat", + "wpage": "wpage", + "cs": "cs", } for key, attr in survey_keys.items(): - if 'Survey_Data' in config and key in config['Survey_Data']: - if key.startswith('Copyright') and all( - k in config['Survey_Data'] for k in ['Copyright1', 'Copyright2', 'Copyright3'] - ): - global_Data.Copyright = "\n".join([ - config['Survey_Data']['Copyright1'], - config['Survey_Data']['Copyright2'], - config['Survey_Data']['Copyright3'] - ]) - global_Data.CopyrightShort = config['Survey_Data']['Copyright_Short'] + if "Survey_Data" in config and key in config["Survey_Data"]: + if key.startswith("Copyright") and all(k in config["Survey_Data"] for k in ["Copyright1", "Copyright2", "Copyright3"]): + global_Data.Copyright = "\n".join([config["Survey_Data"]["Copyright1"], config["Survey_Data"]["Copyright2"], config["Survey_Data"]["Copyright3"]]) + global_Data.CopyrightShort = config["Survey_Data"]["Copyright_Short"] elif attr: - setattr(global_Data, attr, config['Survey_Data'][key]) + setattr(global_Data, attr, config["Survey_Data"][key]) app_keys = { - 'template_path': 'templatePath', - 'station_by_scrap': ('stationByScrap', int), - 'final_therion_exe': ('finalTherionExe', lambda x: x.lower() == 'true'), - 'parse_tro_files_by_explo': ('parse_tro_files_by_explo', lambda x: x.lower() == 'true'), - 'therion_path': 'therionPath', - 'survey_prefix_name': 'SurveyPrefixName', - 'shot_lines_in_th2_files': ('linesInTh2', lambda x: x.lower() == 'true'), - 'station_name_in_th2_files': ('stationNamesInTh2', lambda x: x.lower() == 'true'), - 'wall_lines_in_th2_files': ('wallLinesInTh2', lambda x: x.lower() == 'true'), - 'kSmooth': ('kSmooth', float) + "template_path": "templatePath", + "station_by_scrap": ("stationByScrap", int), + "final_therion_exe": ("finalTherionExe", lambda x: x.lower() == "true"), + "parse_tro_files_by_explo": ("parse_tro_files_by_explo", lambda x: x.lower() == "true"), + "therion_path": "therionPath", + "survey_prefix_name": "SurveyPrefixName", + "shot_lines_in_th2_files": ("linesInTh2", lambda x: x.lower() == "true"), + "station_name_in_th2_files": ("stationNamesInTh2", lambda x: x.lower() == "true"), + "wall_lines_in_th2_files": ("wallLinesInTh2", lambda x: x.lower() == "true"), + "kSmooth": ("kSmooth", float), } for key, value in app_keys.items(): - if 'Application_Data' in config and key in config['Application_Data']: + if "Application_Data" in config and key in config["Application_Data"]: attr, caster = (value, str) if isinstance(value, str) else value - setattr(global_Data, attr, caster(config['Application_Data'][key])) - + setattr(global_Data, attr, caster(config["Application_Data"][key])) + return config_file - except Exception as e: + except Exception as e: # noqa: BLE001 log.critical(f"Reading {configIni} file error: {Colors.ENDC}{e}") - exit(0) + sys.exit(0) +################################################################################################# def load_config(args, configIni="config.ini", profile="Default"): """ Charge un fichier de configuration .ini et initialise les variables globales. @@ -300,7 +297,6 @@ def load_config(args, configIni="config.ini", profile="Default"): Exemple : Survey_Data:PSM """ try: - # Chemin potentiel du fichier config config_file = os.path.join(os.path.dirname(args.file), configIni) if not os.path.isfile(config_file): @@ -333,51 +329,39 @@ def load_config(args, configIni="config.ini", profile="Default"): # ---------------------------------------------------------- survey_keys = { - 'Author': 'Author', - 'Copyright1': 'Copyright', - 'Copyright2': 'Copyright', - 'Copyright3': 'Copyright', - 'Copyright_Short': None, - 'map_comment': 'mapComment', - 'club': 'club', - 'thanksto': 'thanksto', - 'datat': 'datat', - 'wpage': 'wpage', - 'cs': 'cs' + "Author": "Author", + "Copyright1": "Copyright", + "Copyright2": "Copyright", + "Copyright3": "Copyright", + "Copyright_Short": None, + "map_comment": "mapComment", + "club": "club", + "thanksto": "thanksto", + "datat": "datat", + "wpage": "wpage", + "cs": "cs", } # ========================================================== # Variables de substitution # ========================================================== - variables = { - "YEAR": str(datetime.now().year) - } + variables = {"YEAR": str(datetime.now().year)} # noqa: DTZ005 def expand(value): try: return value.format(**variables) - except Exception: + except Exception: # noqa: BLE001 return value # ========================================================== # Lecture Survey_Data # ========================================================== - survey_keys = { - 'Author': 'Author', - 'map_comment': 'mapComment', - 'club': 'club', - 'thanksto': 'thanksto', - 'datat': 'datat', - 'wpage': 'wpage', - 'cs': 'cs' - } + survey_keys = {"Author": "Author", "map_comment": "mapComment", "club": "club", "thanksto": "thanksto", "datat": "datat", "wpage": "wpage", "cs": "cs"} for key, attr in survey_keys.items(): - if key in survey_cfg: - value = expand(survey_cfg[key]) setattr(global_Data, attr, value) @@ -389,75 +373,56 @@ def load_config(args, configIni="config.ini", profile="Default"): copyright_lines = [] for key in ("Copyright1", "Copyright2", "Copyright3"): - if key in survey_cfg: - - copyright_lines.append( - expand(survey_cfg[key]) - ) + copyright_lines.append(expand(survey_cfg[key])) if copyright_lines: - - global_Data.Copyright = "\n".join( - copyright_lines - ) + global_Data.Copyright = "\n".join(copyright_lines) if "Copyright_Short" in survey_cfg: - - global_Data.CopyrightShort = expand( - survey_cfg["Copyright_Short"] - ) - + global_Data.CopyrightShort = expand(survey_cfg["Copyright_Short"]) # ---------------------------------------------------------- # Lecture Application_Data # ---------------------------------------------------------- app_keys = { - 'template_path': 'templatePath', - 'station_by_scrap': ('stationByScrap', int), - 'final_therion_exe': ('finalTherionExe', lambda x: x.lower() == 'true'), - 'parse_tro_files_by_explo': ('parse_tro_files_by_explo', lambda x: x.lower() == 'true'), - 'therion_path': 'therionPath', - 'survey_prefix_name': 'SurveyPrefixName', - 'shot_lines_in_th2_files': ('linesInTh2', lambda x: x.lower() == 'true'), - 'station_name_in_th2_files': ('stationNamesInTh2', lambda x: x.lower() == 'true'), - 'wall_lines_in_th2_files': ('wallLinesInTh2', lambda x: x.lower() == 'true'), - 'kSmooth': ('kSmooth', float) + "template_path": "templatePath", + "station_by_scrap": ("stationByScrap", int), + "final_therion_exe": ("finalTherionExe", lambda x: x.lower() == "true"), + "parse_tro_files_by_explo": ("parse_tro_files_by_explo", lambda x: x.lower() == "true"), + "therion_path": "therionPath", + "survey_prefix_name": "SurveyPrefixName", + "shot_lines_in_th2_files": ("linesInTh2", lambda x: x.lower() == "true"), + "station_name_in_th2_files": ("stationNamesInTh2", lambda x: x.lower() == "true"), + "wall_lines_in_th2_files": ("wallLinesInTh2", lambda x: x.lower() == "true"), + "kSmooth": ("kSmooth", float), } - if 'Application_Data' in config: - + if "Application_Data" in config: for key, value in app_keys.items(): - if key not in config['Application_Data']: + if key not in config["Application_Data"]: continue - attr, caster = ( - (value, str) - if isinstance(value, str) - else value - ) + attr, caster = (value, str) if isinstance(value, str) else value - setattr( - global_Data, - attr, - caster(config['Application_Data'][key]) - ) + setattr(global_Data, attr, caster(config["Application_Data"][key])) # log.info(f"Configuration profile : {profile}") return config_file, profile - except Exception as e: - log.critical(f"Reading config file : {Colors.ENDC}{configIni}{Colors.ERROR} error : {Colors.ENDC}{e}" ) - exit(0) + except Exception as e: # noqa: BLE001 + log.critical(f"Reading config file : {Colors.ENDC}{configIni}{Colors.ERROR} error : {Colors.ENDC}{e}") + sys.exit(0) + ################################################################################################# # Supprime les codes ANSI (pour l'écriture dans les fichiers) ################################################################################################# def strip_ansi_codes(text): - ansi_escape = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])') - return ansi_escape.sub('', text) + ansi_escape = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])") + return ansi_escape.sub("", text) ################################################################################################# @@ -486,11 +451,11 @@ class FileFormatter(logging.Formatter): args=(), exc_info=record.exc_info, func=record.funcName, - sinfo=record.stack_info + sinfo=record.stack_info, ) return super().format(record_copy) - - + + ################################################################################################# # Fonction de configuration du logger ################################################################################################# @@ -498,9 +463,9 @@ def setup_logger(logfile="app.log", debug_log=False): logger = logging.getLogger("Logger") logger.setLevel(logging.DEBUG) logger.handlers.clear() - + min_level = logging.DEBUG if debug_log else logging.INFO - + # Console stderr handler — affichage à l'écran avec couleurs stderr_handler = logging.StreamHandler(sys.stderr) stderr_handler.setLevel(min_level) @@ -514,7 +479,7 @@ def setup_logger(logfile="app.log", debug_log=False): file_formatter = FileFormatter("%(asctime)s - %(levelname)s - %(message)s") # <-- Ta classe personnalisée file_handler.setFormatter(file_formatter) logger.addHandler(file_handler) - + return logger @@ -533,103 +498,105 @@ def copy_template_if_not_exists(template_path, destination_path): try: if not os.path.exists(destination_path): # If the destination folder does not exist, copy the template - shutil.copytree(template_path, destination_path) + shutil.copytree(template_path, destination_path) log.info(f"The folder {Colors.ENDC}{template_path}{Colors.GREEN} has been copied to {Colors.ENDC}{safe_relpath(destination_path)}{Colors.GREEN}") else: log.warning(f"The folder '{Colors.ENDC}{safe_relpath(destination_path)}{Colors.WARNING}' already exists. No files were copied.") - except Exception as e: + except Exception as e: # noqa: BLE001 log.critical(f"Copy template error: {Colors.ENDC}{e}") - exit(0) - - -################################################################################################# + sys.exit(0) + + +################################################################################################# def add_copyright_header(file_path, copyright_text): # Lire le contenu du fichier - with open(file_path, 'r', encoding="utf-8") as file: + with open(file_path, "r", encoding="utf-8") as file: content = file.readlines() - + # Vérifier si le copyright est déjà présent if not any("copyright" in line.lower() for line in content): # Ajouter le copyright en en-tête content.insert(0, f"{copyright_text}\n") - - # Réécrire le fichier avec le copyright ajouté - with open(file_path, 'w', encoding="utf-8") as file: - file.writelines(content) - + # Réécrire le fichier avec le copyright ajouté + with open(file_path, "w", encoding="utf-8") as file: + file.writelines(content) + + ################################################################################################# def copy_file_with_copyright(th_file, destination_path, copyright_text): # Vérifier si le fichier existe if os.path.exists(th_file): # Créer le dossier de destination s'il n'existe pas os.makedirs(destination_path, exist_ok=True) - + _destFile = sanitize_filename(os.path.basename(th_file)[:-3]) + ".th" # Copier le fichier vers le dossier de destination dest_file = os.path.join(destination_path, _destFile) shutil.copy(th_file, dest_file) - + # Ajouter le copyright dans l'en-tête si nécessaire add_copyright_header(dest_file, copyright_text) - - log.debug(f"File {Colors.ENDC}{safe_relpath(th_file)}{Colors.GREEN} has been copied to {Colors.ENDC}{safe_relpath(destination_path)}{Colors.GREEN} with the copyright header added.{Colors.ENDC}") + + log.debug( + f"File {Colors.ENDC}{safe_relpath(th_file)}{Colors.GREEN} has been copied to {Colors.ENDC}{safe_relpath(destination_path)}{Colors.GREEN} with the copyright header added.{Colors.ENDC}" + ) else: log.error(f"The file .th does not exist {Colors.ENDC}{safe_relpath(th_file)}") global_Data.error_count += 1 - - + + ################################################################################################# -# Remplir les template avec les variables vers output_path # # +# Remplir les template avec les variables vers output_path # # ################################################################################################# def update_template_files(template_path, variables, output_path): """ Process a Therion template file by replacing variables. - + Args: template_path (str): Path to the original template file variables (dict): Dictionary of variables to replace output_path (str): Path for the new configuration file - + Returns: None - + """ - + try: # Read the content of the template file - with open(template_path, 'r', encoding='utf-8') as file: + with open(template_path, "r", encoding="utf-8") as file: content = file.read() - + # Replace variables for var, value in variables.items(): # Use regex to replace {variable} with its value - pattern = r'\{' + re.escape(var) + r'\}' + pattern = r"\{" + re.escape(var) + r"\}" content = re.sub(pattern, str(value), content) - + # Write the new file - with open(output_path, 'w', encoding='utf-8') as file: + with open(output_path, "w", encoding="utf-8") as file: file.write(content) log.info(f"Update template successfully: {Colors.ENDC}{safe_relpath(output_path)}") # Delete the original template file os.remove(template_path) - + except FileNotFoundError: log.error(f"Template file {Colors.ENDC}{template_path}{Colors.ERROR} not found") global_Data.error_count += 1 - + except PermissionError: - log.error(f"Insufficient permissions to write the file") + log.error("Insufficient permissions to write the file") global_Data.error_count += 1 - - except Exception as e: + + except Exception as e: # noqa: BLE001 log.error(f"An error occurred (update_template_files : {Colors.ENDC}{os.path.basename(template_path)}{Colors.ERROR}) : {Colors.ENDC}{e}") global_Data.error_count += 1 -################################################################################################# +################################################################################################# def load_text_file_utf8(filepath, short_filename): """Loads a text file with various encodings and converts it to UTF-8. @@ -642,41 +609,62 @@ def load_text_file_utf8(filepath, short_filename): """ encodings_to_try = [ - 'utf-8-sig', # UTF-8 avec BOM - 'utf-8', # UTF-8 standard - 'windows-1252', # ANSI Windows Europe de l’Ouest - 'iso-8859-15', # ISO-8859-15 (latin9), remplace iso-8859-1 (latin1) - 'iso-8859-1', + "utf-8-sig", # UTF-8 avec BOM + "utf-8", # UTF-8 standard + "windows-1252", # ANSI Windows Europe de l’Ouest + "iso-8859-15", # ISO-8859-15 (latin9), remplace iso-8859-1 (latin1) + "iso-8859-1", ] for enc in encodings_to_try: try: - with open(filepath, 'r', encoding=enc) as f: + with open(filepath, "r", encoding=enc) as f: content = f.read() - log.info(f"Open source file: {Colors.ENDC}{short_filename}{Colors.GREEN}, with encoding: {Colors.ENDC}{enc}{Colors.GREEN} and conversion to {Colors.ENDC}utf-8") + log.info( + f"Open source file: {Colors.ENDC}{short_filename}{Colors.GREEN}, with encoding: {Colors.ENDC}{enc}{Colors.GREEN} and conversion to {Colors.ENDC}utf-8" + ) message_log = f"* Source file: {short_filename}, encoding: {enc}, conversion to utf-8\n" return content, message_log, enc - + except UnicodeDecodeError as e: log.debug(f"Failed {Colors.ENDC}{enc}{Colors.DEBUG} for {Colors.ENDC}{short_filename}{Colors.DEBUG}: {Colors.ENDC}{e}") continue - - except Exception as e: + + except Exception as e: # noqa: BLE001 log.critical(f"Unexpected error while reading {Colors.ENDC}{short_filename}{Colors.CRITICAL}: {e}") - exit(0) + sys.exit(0) return None, "", None # Dernier recours : lecture binaire + forçage try: - with open(filepath, 'rb') as f: + with open(filepath, "rb") as f: raw = f.read() - content = raw.decode('windows-1252', errors='replace') + content = raw.decode("windows-1252", errors="replace") log.warning(f"Force-reading {Colors.ENDC}{short_filename}{Colors.WARNING} with character replacement (windows-1252)") - message = f"* Force-reading source file: {short_filename} with character replacement (windows-1252)\n" - return content, message, 'windows-1252' - - except Exception as e: - log.critical(f"Failed to read file {Colors.ENDC}{short_filename}{Colors.CRITICAL}: {Colors.ENDC}{e}") - exit(0) + message = f"* Force-reading source file: {short_filename} with character replacement (windows-1252)\n" + return content, message, "windows-1252" + + except Exception as e: # noqa: BLE001 + log.critical(f"Failed to read file {Colors.ENDC}{short_filename}{Colors.CRITICAL}: {Colors.ENDC}{e}") + sys.exit(0) return None, "", None + +################################################################################################# +def read_text_file(filename): + """Lecture avec prise en charge de plusieurs encodages.""" + + for encoding in ("utf-8-sig", "cp1252", "latin-1"): + try: + with open(filename, "r", encoding=encoding) as f: + content = f.read() + + if encoding != "utf-8-sig": + log.info(f"Fichier : {Colors.ENDC}{safe_relpath(filename)}{Colors.INFO} lu en {Colors.ENDC}{encoding}") + + return content + + except UnicodeDecodeError: + continue + + raise UnicodeError(f"{Colors.ERROR}Impossible de décoder {Colors.ENDC}{filename}") diff --git a/Scripts/pyCreateTh/Lib/global_data.py b/Scripts/pyCreateTh/Lib/global_data.py index b575ab7..018b016 100644 --- a/Scripts/pyCreateTh/Lib/global_data.py +++ b/Scripts/pyCreateTh/Lib/global_data.py @@ -1,16 +1,16 @@ """ !#############################################################################################! -global_data.py for pyCreateTh.py +global_data.py for pyCreateTh.py !#############################################################################################! """ -Version = "2026.01.08" +Version = "2026.11.19" ################################################################################################# - -error_count = 0 # Compteur d'erreurs +debug_log = False # Mode debug des messages +error_count = 0 # Compteur d'erreurs ## [Survey_Data] default values Author = "Created by pyCreateTh.py" @@ -28,7 +28,7 @@ templatePath = "./Template" stationByScrap = 20 finalTherion_exe = True therionPath = "C:/Therion/therion.exe" -SurveyPrefixName = f"Survey_" +SurveyPrefixName = "Survey_" linesInTh2 = True stationNamesInTh2 = True wallLinesInTh2 = True @@ -39,33 +39,35 @@ parse_tro_files_by_explo = True ################################################################################################# THERION_KEYWORDS = { - "centerline", + "centerline", "endcenterline", - "date", - "units", - "flags", + "date", + "units", + "flags", "team", - "calibrate", - "data", + "calibrate", + "data", "declination", - "fix", - "station", + "fix", + "station", "equate", - "cs", - "extend", - "infer", + "cs", + "extend", + "infer", "explo-team", - "instrument", - "grade", - "clino", - "compass", - "length", - "reverse", - "topofil", - "duplicate", + "instrument", + "grade", + "clino", + "compass", + "length", + "reverse", + "topofil", + "duplicate", "not", } +################################################################################################# +# tot file template # ################################################################################################# totfile = """\t## Survey file: \tinput Data/{TH_NAME}.th @@ -81,6 +83,8 @@ totfile = """\t## Survey file: """ +################################################################################################# +# Th file template # ################################################################################################# thFileDat = """ encoding utf-8 @@ -93,6 +97,7 @@ survey {SURVEY_NAME} -title "{SURVEY_TITLE}" \t\t# team "{SURVEY_TEAM}" {FIX_POINTS} + \t\texplo-date {EXPLO_DATE} \t\t# explo-team "{EXPLO_TEAM}" {CORRECTIONS}{DECLINATION} @@ -109,7 +114,8 @@ endsurvey {SOURCE} """ - +################################################################################################# +# thconfig template (minimal) # ################################################################################################# thconfigTemplate = """ source "{th_file}" @@ -152,9 +158,9 @@ endscrap """ th2Point = """\tpoint {x} {y} station -name {station}""" -th2Name = """\tpoint {x} {y} station-name -align tr -scale xs -text {station}""" +th2Name = """\tpoint {x} {y} station-name -align tr -scale xs -text {station}""" -th2Line = """ +th2Line = """ line u:Shot_Survey \t{x1} {y1} \t{x2} {y2} @@ -173,49 +179,41 @@ endscrap ################################################################################################# datumToEPSG = { - # Datums globaux - "wgs84": "326", # UTM Nord (WGS84) - EPSG:326XX - "wgs1984": "326", # UTM Nord (WGS84) - EPSG:326XX - "etrs89": "258", # UTM Nord (ETRS89) - Europe - - # Datums européens - "european1950": "230", # ED50 / UTM Nord - Europe - "ed50": "230", - - # Datums nord-américains - "nad27": "267", # UTM Nord (NAD27) - Amérique du Nord - "northamericandatum1927": "267", - "northamerican1927": "267", - "nad83": "269", # UTM Nord (NAD83) - Amérique du Nord - "northamericandatum1983": "269", - "northamerican1983" : "269", - - # Datums français - "ntf": "275", # UTM Nord (NTF) - France (Paris) - "nouvelletriangulationfrançaise": "275", - - # Datums africains - "clarke1880": "297", # UTM Nord (Clarke 1880) - Afrique - - # Datums australiens - "agd66": "202", # UTM Nord (AGD66) - Australie - "australiangeodeticdatum1966": "202", - "australiangeodetic1966": "202", - "agd84": "203", # UTM Nord (AGD84) - Australie - "australiangeodeticdatum1984": "203", - "australiangeodetic1984": "203", - "gda94": "283", # UTM Nord (GDA94) - Australie - "geocentricdatumofaustralia1994": "283", - "geocentricofaustralia1994": "283", - - # Datums asiatiques - "pulkovo1942": "284", # UTM Nord (Pulkovo 1942) - Russie/CEI - "beijing1954": "214", # UTM Nord (Beijing 1954) - Chine - - # Datums sud-américains - "sad69": "291", # UTM Nord (SAD69) - Amérique du Sud - "southamericandatum1969": "291", - "southamerican1969": "291", - "sirgas2000": "319", # UTM Nord (SIRGAS 2000) - Amérique Latine + # Datums globaux + "wgs84": "326", # UTM Nord (WGS84) - EPSG:326XX + "wgs1984": "326", # UTM Nord (WGS84) - EPSG:326XX + "etrs89": "258", # UTM Nord (ETRS89) - Europe + # Datums européens + "european1950": "230", # ED50 / UTM Nord - Europe + "ed50": "230", + # Datums nord-américains + "nad27": "267", # UTM Nord (NAD27) - Amérique du Nord + "northamericandatum1927": "267", + "northamerican1927": "267", + "nad83": "269", # UTM Nord (NAD83) - Amérique du Nord + "northamericandatum1983": "269", + "northamerican1983": "269", + # Datums français + "ntf": "275", # UTM Nord (NTF) - France (Paris) + "nouvelletriangulationfrançaise": "275", + # Datums africains + "clarke1880": "297", # UTM Nord (Clarke 1880) - Afrique + # Datums australiens + "agd66": "202", # UTM Nord (AGD66) - Australie + "australiangeodeticdatum1966": "202", + "australiangeodetic1966": "202", + "agd84": "203", # UTM Nord (AGD84) - Australie + "australiangeodeticdatum1984": "203", + "australiangeodetic1984": "203", + "gda94": "283", # UTM Nord (GDA94) - Australie + "geocentricdatumofaustralia1994": "283", + "geocentricofaustralia1994": "283", + # Datums asiatiques + "pulkovo1942": "284", # UTM Nord (Pulkovo 1942) - Russie/CEI + "beijing1954": "214", # UTM Nord (Beijing 1954) - Chine + # Datums sud-américains + "sad69": "291", # UTM Nord (SAD69) - Amérique du Sud + "southamericandatum1969": "291", + "southamerican1969": "291", + "sirgas2000": "319", # UTM Nord (SIRGAS 2000) - Amérique Latine } - \ No newline at end of file diff --git a/Scripts/pyCreateTh/Lib/pytro2th/datathwritetools.py b/Scripts/pyCreateTh/Lib/pytro2th/datathwritetools.py index 76a1d1c..e2095f2 100644 --- a/Scripts/pyCreateTh/Lib/pytro2th/datathwritetools.py +++ b/Scripts/pyCreateTh/Lib/pytro2th/datathwritetools.py @@ -1,5 +1,5 @@ ######!/usr/bin/env python -# -*- coding: utf-8 -*- +# -*- coding: utf-8 -*- # noqa: UP009 # coding: utf8 # Copyright (c) 2020 Xavier Robert @@ -16,569 +16,571 @@ USAGE : INPUTS: -The inputs are in the script file, in the "# Define data to analysis" section. +The inputs are in the script file, in the "# Define data to analysis" section. The different arguments are described. """ ###### To DO : ####### # - Test the MTL pdfs (I have not tested it, even if it should be OK) -# - Add error bars on data graphs ? -# For that we should read the input data file given in topo_parameters.txt +# - Add error bars on data graphs ? +# For that we should read the input data file given in topo_parameters.txt # (paragraphe N°12 of topo_parameters.txt) -# +# ###### End To DO ####### -from __future__ import division +from __future__ import division # noqa: I001, UP010 # This to be sure that the result of the division of integers is a real, not an integer -#from __future__ import unicode_literals +# from __future__ import unicode_literals # Import modules from Lib.general_fonctions import sanitize_filename -import sys, os, copy, datetime +import sys, os, copy, datetime # noqa: F401 from pyproj import Proj, transform + ################################################################################################# def writeheader_th(file, cavename, entrance): - """ - Function to write the header of the file.th - - INPUTS: - file : variable that sets the file.th - cavename : name of the cave - entrance : name of the entrance station - - OUTPUTS: - None - - USAGE: - writeheader_th(file, cavename, entrance) - - Author: Xavier Robert, Lima 2016/06/27 - - """ - - file.write(u'encoding utf-8 \n\nsurvey %s -title "%s" -entrance "%s" \n' - %(sanitize_filename(cavename), cavename, entrance)) - - return + """ + Function to write the header of the file.th + + INPUTS: + file : variable that sets the file.th + cavename : name of the cave + entrance : name of the entrance station + + OUTPUTS: + None + + USAGE: + writeheader_th(file, cavename, entrance) + + Author: Xavier Robert, Lima 2016/06/27 + + """ + + file.write('encoding utf-8 \n\nsurvey %s -title "%s" -entrance "%s" \n' % (sanitize_filename(cavename), cavename, entrance)) # noqa: UP031 + + return # noqa: PLR1711 ################################################################################################# -def writecenterlineheader(file, entrance, settings, comments, data, coordsyst, coordinates, club, - icomments, thlang): - """ - Function to write the centerline header - - - INPUTS: - file : variable that sets the file.th - entrance : name of the entrance station - settings : List of the settings of this survey section - comments : String that correspond to the end of the string "Line" - that do not correspond to the settings - data : data from this survey section - coordsyst : Coordinates system to set the entrance coordinates - coordinates : Entrance coordinates - club : Name of the group that explored the cave - icomments : True if comments in the file - False if not - thlang : 'fr' for french - 'en' for english - ... other languages not implemented - - OUTPUTS: - None - - USAGE: - writeheader_th(file, cavename, entrance) - - Author: Xavier Robert, Lima 2016/06/27 - - """ - # First, define dictionaries to help the coding - # angleU: define the angle unit - angleU = {u'Deg' : u'degrees', - u'Degd' :u'degrees', - u'Gra' : u'grad'} - # compassdir: - dir = {u'Dir' : u'', - u'Inv' : u'back'} - # lruddir: Set the LRUD - lruddir = {u'Dir' : u'left right up down', - u'Inv' : u'right left up down', - u'Nod' : u''} - # unitcounter: set the unit of the counter (for the length) - unitcounter = {u'Vulc' : u'centi', - u'Prof' : u'', - u'Deniv': u''} - # unitclino: used to correct the clino if topoVulcain - unitclino = {u'Deg' : u'90', - u'Degd' : u'90', - u'Gra' : u'100'} - # typelen: type of length measures - #typelem = {u'Deca' : u'normal', - # u'Topof' : u'topofil', - # u'Vulc' : u'topofil', - # u'Prof' : u'diving', - # u'Deniv' : u'deniv'} - # style: data style - style = {u'Deca' : u'normal', - u'Topof' : u'topofil', - u'Diving' : u'diving', - u'Prof' : u'diving', - u'Carth' : u'carthesian', - u'Cylp' : u'cylpolar', - u'Dim' : u'dimensions', - u'Nosy' : u'nosurvey'} - # station: type of stations - station = {u'station' : u'station', - u'from' : u'from', - u'to' : u'to', - u'vtopo' : u'from to'} - # lensurv: how are set the length measurements - lensurv = {u'Deca' : u'length', - u'Topof' : u'fromcount tocount', - u'Diving' : u'length', - u'Prof' : u'length'} - # slopesurv: how are set the slope measurements - slopesurv = {u'Clino' : u'clino', - u'Vulc' : u'clino', - u'Deniv' : u'depthchange', - u'Prof' : u'depth'} - - # Begin the centerline - file.write(u'\n\tcenterline \n') - - # if entrance in the data, write the entrance coordinates - if [datal for datal in data if entrance in datal] != []: - if icomments: - if thlang == u'fr': - file.write(u'\t\t# Si le systeme de coordonnées n\'est pas le système' - u' Lambert français, voir le Thbook et le fichier' - u' extern/proj4/nad/epsg dans le dossier source de Therion \n') - file.write(u'\t\t# Si les coordonnées de l\'entrée sont connues,' - u' copier dans la centerline correspondante et décommenter' - u' les 2 lignes suivantes : \n') - elif thlang == u'en': - file.write(u'\t\t# If your are not in the french Lambert system, ' - u' To find number of your system, see' - u' extern/proj4/nad/epsg file in the Therion' - u' source distribution \n') - file.write(u'\t\t# If the entrance coordinates are known, uncomment and' - u' copy in the corresponding centerline the next 2 lines: \n') - if coordsyst != None: - file.write(u'\t\tcs %s \n' - u'\t\tfix %s %s %s %s \n\n' % (coordsyst, entrance, coordinates[0], coordinates[1], coordinates[2])) # [Correction Alex 2025 11 10] - else: - file.write(u'\t\t#cs %s \n' - u'\t\t#fix %s %s %s %s \n\n' % (coordsyst, entrance, coordinates[0], coordinates[1], coordinates[2])) # [Correction Alex 2025 11 10] - typem = u'Deca' - if u'Topof' not in settings: - settings [1:1]= u' ' - typem = u'Topof' - if u'Prof' in settings or u'Deniv' in settings: - settings[4:4] = u' ' - # next line used to debug - #file.write(u'\t' + str(settings) + u'\n') - # write the survey caracteristics - file.write(u'\t\tdate %s\n'% str(settings[9])) - if icomments: - if thlang == u'fr': - file.write(u'\t\t# Si date est utilisé, commenter la ligne "declination", ' - u'la date sera utilisée pour la calculer\n') - elif thlang == u'en': - file.write(u'\t\t# If date is used, comment the ligne "declination", ' - u'the date will be use to compute it\n') - if str(settings[9]) == "": - file.write(u'\t\tdeclination %s %s \n'% (str(settings[5]), angleU[settings[2]])) - else : - file.write(u'\t\t# declination %s %s \n'% (str(settings[5]), angleU[settings[2]])) +def writecenterlineheader(file, entrance, settings, comments, data, coordsyst, coordinates, club, icomments, thlang, cavename): + """ + Function to write the centerline header - # file.write(u'\t\t\tteam "G.S. Vulcain" \n') - file.write(u'\t\t# team "%s" \n' % club) - file.write(u'\t\t# explo-date %s\n'% str(settings[9])) - # file.write(u'\t\t\texplo-team "G.S. Vulcain" \n') - if club.count(' ') >= 2: - _club = club.replace(' ', '/', 1) - else : - _club = club - file.write(u'\t\texplo-team "%s" \n' % _club) - - if icomments: - if thlang == u'en': file.write(u'\t\t# (to be completed, add many lines as you need) \n') - elif thlang == u'fr': file.write(u'\t\t# (peut être complété en ajoutant le nombre de lignes nécessaires) \n') - - dirs = settings[6].rstrip(u'\n\r').split(u',') - - file.write(u'\n\t\tunits length meters \n') - if u'Topof' in settings: - file.write(u'\t\tunits counter %smeters \n' % unitcounter[settings[3]]) - file.write(u'\t\tcalibrate counter 0 %s \n' % settings[1]) - # To set the slope - if u'Vulc' in settings: - file.write(u'\t\tcalibrate clino 1 %s -1\n' % unitclino[settings[4]]) - if u'Prof' in settings: - file.write(u'\t\tunits depth meters \n') - typem = u'Prof' - elif u'Deniv' in settings: - file.write(u'\t\tunits depth meters \n') - typem = u'Diving' - - file.write(u'\t\tunits compass %s \n' % (angleU[settings[2]])) - if u'Vulc' in settings or 'Clino' in settings: - file.write(u'\t\tunits clino %s \n' % (angleU[settings[4]])) - - file.write(u'\n\t\tdata %s %s %s %scompass %s%s %s\n' - % (style[typem], station[u'vtopo'], lensurv[settings[0]], - dir[dirs[0]], dir[dirs[1]], slopesurv[settings[3]], - lruddir[dirs[2]])) - if comments != u'': - file.write(u'\t\t\t#' + comments + u'\n') - - return + + INPUTS: + file : variable that sets the file.th + entrance : name of the entrance station + settings : List of the settings of this survey section + comments : String that correspond to the end of the string "Line" + that do not correspond to the settings + data : data from this survey section + coordsyst : Coordinates system to set the entrance coordinates + coordinates : Entrance coordinates + club : Name of the group that explored the cave + icomments : True if comments in the file + False if not + thlang : 'fr' for french + 'en' for english + ... other languages not implemented + + OUTPUTS: + None + + USAGE: + writeheader_th(file, cavename, entrance) + + Author: Xavier Robert, Lima 2016/06/27 + + """ + # First, define dictionaries to help the coding + # angleU: define the angle unit + angleU = {"Deg": "degrees", "Degd": "degrees", "Gra": "grad"} + # compass dir: + dir = {"Dir": "", "Inv": "back"} + # lruddir: Set the LRUD + lruddir = {"Dir": "left right up down", "Inv": "right left up down", "Nod": ""} + # unitcounter: set the unit of the counter (for the length) + unitcounter = {"Vulc": "centi", "Prof": "", "Deniv": ""} + # unitclino: used to correct the clino if topoVulcain + unitclino = {"Deg": "90", "Degd": "90", "Gra": "100"} + # typelen: type of length measures + # typelem = {u'Deca' : u'normal', + # u'Topof' : u'topofil', + # u'Vulc' : u'topofil', + # u'Prof' : u'diving', + # u'Deniv' : u'deniv'} + # style: data style + style = { + "Deca": "normal", + "Topof": "topofil", + "Diving": "diving", + "Prof": "diving", + "Carth": "carthesian", + "Cylp": "cylpolar", + "Dim": "dimensions", + "Nosy": "nosurvey", + } + # station: type of stations + station = {"station": "station", "from": "from", "to": "to", "vtopo": "from to"} + # lensurv: how are set the length measurements + lensurv = {"Deca": "length", "Topof": "fromcount tocount", "Diving": "length", "Prof": "length"} + # slopesurv: how are set the slope measurements + slopesurv = {"Clino": "clino", "Vulc": "clino", "Deniv": "depthchange", "Prof": "depth"} + + # Begin the centerline + file.write("\n\tcenterline \n") + + # if entrance in the data, write the entrance coordinates + if [datal for datal in data if entrance in datal] != []: + if icomments: + if thlang == "fr": + file.write( + "\t\t# Si le système de coordonnées n'est pas le système" + " Lambert français, voir le Thbook et le fichier" + " extern/proj4/nad/epsg dans le dossier source de Therion \n" + ) + file.write("\t\t# Si les coordonnées de l'entrée sont connues, copier dans la centerline correspondante et décommenter les 2 lignes suivantes : \n") + elif thlang == "en": + file.write( + "\t\t# If your are not in the french Lambert system, " + " To find number of your system, see" + " extern/proj4/nad/epsg file in the Therion" + " source distribution \n" + ) + file.write("\t\t# If the entrance coordinates are known, uncomment and copy in the corresponding centerline the next 2 lines: \n") + if coordsyst != None: + file.write( + '\t\tcs %s\n\t\tfix %s %s %s %s\n\t\tstation %s "%s" entrance\n\n' # noqa: UP031 + % (coordsyst, entrance, coordinates[0], coordinates[1], coordinates[2], entrance, cavename) + ) # [Correction Alex 2026 11 19] # noqa: RUF100, UP031 + else: + file.write( + '\t\t#cs %s\n\t\t#fix %s %s %s %s\n\t\t#station %s "%s" entrance\n\n' # noqa: UP031 + % (coordsyst, entrance, coordinates[0], coordinates[1], coordinates[2], entrance, cavename) + ) # [Correction Alex 2026 11 19] # noqa: RUF100, UP031 + + typem = "Deca" + if "Topof" not in settings: + settings[1:1] = " " + typem = "Topof" + if "Prof" in settings or "Deniv" in settings: + settings[4:4] = " " + # next line used to debug + # file.write(u'\t' + str(settings) + u'\n') + # write the survey characteristics + file.write("\t\tdate %s\n" % str(settings[9])) # noqa: UP031 + if icomments: + if thlang == "fr": + file.write('\t\t# Si date est utilisé, commenter la ligne "declination", la date sera utilisée pour la calculer\n') + elif thlang == "en": + file.write('\t\t# If date is used, comment the ligne "declination", the date will be use to compute it\n') + if str(settings[9]) == "": + file.write("\t\tdeclination %s %s \n" % (str(settings[5]), angleU[settings[2]])) # noqa: UP031 + else: + file.write("\t\t# declination %s %s \n" % (str(settings[5]), angleU[settings[2]])) # noqa: UP031 + + # file.write(u'\t\t\tteam "G.S. Vulcain" \n') + file.write('\t\t# team "%s" \n' % club) # noqa: UP031 + file.write("\t\t# explo-date %s\n" % str(settings[9])) # noqa: UP031 + # file.write(u'\t\t\texplo-team "G.S. Vulcain" \n') + if club.count(" ") >= 2: + _club = club.replace(" ", "/", 1) + else: + _club = club + file.write('\t\texplo-team "%s" \n' % _club) # noqa: UP031 + + if icomments: + if thlang == "en": + file.write("\t\t# (to be completed, add many lines as you need) \n") + elif thlang == "fr": + file.write("\t\t# (peut être complété en ajoutant le nombre de lignes nécessaires) \n") + + dirs = settings[6].rstrip("\n\r").split(",") + + file.write("\n\t\tunits length meters \n") + if "Topof" in settings: + file.write("\t\tunits counter %smeters \n" % unitcounter[settings[3]]) # noqa: UP031 + file.write("\t\tcalibrate counter 0 %s \n" % settings[1]) # noqa: UP031 + # To set the slope + if "Vulc" in settings: + file.write("\t\tcalibrate clino 1 %s -1\n" % unitclino[settings[4]]) # noqa: UP031 + if "Prof" in settings: + file.write("\t\tunits depth meters \n") + typem = "Prof" + elif "Deniv" in settings: + file.write("\t\tunits depth meters \n") + typem = "Diving" + + file.write("\t\tunits compass %s \n" % (angleU[settings[2]])) # noqa: UP031 + if "Vulc" in settings or "Clino" in settings: + file.write("\t\tunits clino %s \n" % (angleU[settings[4]])) # noqa: UP031 + + file.write( + "\n\t\tdata %s %s %s %scompass %s%s %s\n" # noqa: UP031 + % (style[typem], station["vtopo"], lensurv[settings[0]], dir[dirs[0]], dir[dirs[1]], slopesurv[settings[3]], lruddir[dirs[2]]) + ) + if comments != "": + file.write("\t\t\t#" + comments + "\n") + + return # noqa: PLR1711 ################################################################################################# def writedata(file, settings, data, dataold): - """ - function to write the data in the .th file - - INPUTS: - file : variable that sets the file.th - settings : List of the settings of this survey section - data : data from this survey section - dataold : data from the previous survey section - - OUTPUTS: - None - - USAGE: - writeheader_th(file, cavename, entrance) - - Author: Xavier Robert, Lima 2016/06/27 - - """ - - # dictl = length of the data line - dictl = {u'Deca' : 9, - u'Topof' : 10} - - i=0 - for elems in data: - for k in [0,2]: - if elems[k] == u'*': - # remove the '*', and replace them with the right data ! - if i == 0: elems[k] = dataold[len(dataold)-1][k+1] - else: elems[k] = data[i-1][k+1] - - if elems[0] == elems[1]: elems[1] = elems[1] + u'd' - - for k in range (dictl[settings[0]]-4, dictl[settings[0]]): - # Check that LRUD != '*'; If yes, change them to 0 - if elems[k] == u'*': elems[k] = u'0' - - # Si le premier caractère est '-', on le remplace par '+' [Ajout Alex 2025 11 10] - elif elems[k].startswith(u'-'): - elems[k] = u'+' + elems[k][1:] - - # Check if option 'E' - if u'E' in elems: - file.write(u'\t\t\tflags duplicate \n') - # We write the data - # if elems[0:1] == "*": - # elems[0:1] = "-" - file.write(u'\t\t\t' + u'\t'.join( - "-" if i == 1 and x == "*" else x - for i, x in enumerate(elems[0:dictl[settings[0]]]) - )) + """ + function to write the data in the .th file - # file.write(u'\t\t\t' + u'\t'.join(x for x in elems[0:dictl[settings[0]]])) - - if len(elems) > (dictl[settings[0]] + 2): - if elems[dictl[settings[0]] + 1] != u'N' and elems[dictl[settings[0]] + 1] != u'I': - # we add the comment if there is one - file.write(u'\t# ' + ' '.join(x for x in elems[(dictl[settings[0]]+1) : len(elems)])[1:-1] + u'\n') - elif len(elems) > (dictl[settings[0]] + 3): - file.write(u'\t# ' + ' '.join(x for x in elems[(dictl[settings[0]]+2) : len(elems)])[1:-1] + u'\n') - else: - file.write(u'\n') - else: - file.write(u'\n') - if elems[(dictl[settings[0]])] == u'I': - file.write(u'\t\t\textend reverse \n') - if u'E' in elems: - file.write(u'\t\t\tflags not duplicate \n') - i+=1 - - return + INPUTS: + file : variable that sets the file.th + settings : List of the settings of this survey section + data : data from this survey section + dataold : data from the previous survey section + + OUTPUTS: + None + + USAGE: + writeheader_th(file, cavename, entrance) + + Author: Xavier Robert, Lima 2016/06/27 + + """ + + # dictl = length of the data line + dictl = {"Deca": 9, "Topof": 10} + + i = 0 + for elems in data: + for k in [0, 2]: + if elems[k] == "*": + # remove the '*', and replace them with the right data ! + if i == 0: + elems[k] = dataold[len(dataold) - 1][k + 1] + else: + elems[k] = data[i - 1][k + 1] + + if elems[0] == elems[1]: + elems[1] = elems[1] + "d" + + for k in range(dictl[settings[0]] - 4, dictl[settings[0]]): + # Check that LRUD != '*'; If yes, change them to 0 + if elems[k] == "*": + elems[k] = "0" + + # Si le premier caractère est '-', on le remplace par '+' [Ajout Alex 2025 11 10] + elif elems[k].startswith("-"): + elems[k] = "+" + elems[k][1:] + + # Check if option 'E' + if "E" in elems: + file.write("\t\t\tflags duplicate\n") + # We write the data + # if elems[0:1] == "*": + # elems[0:1] = "-" + file.write("\t\t\t" + "\t".join("-" if i == 1 and x == "*" else x for i, x in enumerate(elems[0 : dictl[settings[0]]]))) + + # file.write(u'\t\t\t' + u'\t'.join(x for x in elems[0:dictl[settings[0]]])) + + if len(elems) > (dictl[settings[0]] + 2): + if elems[dictl[settings[0]] + 1] != "N" and elems[dictl[settings[0]] + 1] != "I": + # we add the comment if there is one + file.write("\t# " + " ".join(x for x in elems[(dictl[settings[0]] + 1) : len(elems)])[1:-1] + "\n") + elif len(elems) > (dictl[settings[0]] + 3): + file.write("\t# " + " ".join(x for x in elems[(dictl[settings[0]] + 2) : len(elems)])[1:-1] + "\n") + else: + file.write("\n") + else: + file.write("\n") + if elems[(dictl[settings[0]])] == "I": + file.write("\t\t\textend reverse \n") + if "E" in elems: + file.write("\t\t\tflags not duplicate\n") + i += 1 # noqa: SIM113 + + return # noqa: PLR1711 ################################################################################################# -def write_thtot(file, cavename = u'cave', icomments = True, thlang = 'en'): - """ - Function to write the file cavename-tot.th - - INPUTS: - file : variable that sets the file.th - cavename : name of the cave - icomments : True if comments in the file - False if not - thlang : 'fr' for french - 'en' for english - ... other languages not implemented - - OUTPUTS: - None - - USAGE: - write_thtot(file, cavename, icomments, thlang) - - Author: Xavier Robert, Grenoble 2021/01/03 - - """ - - file.write(u'encoding utf-8 \n\n') +def write_thtot(file, cavename="cave", icomments=True, thlang="en"): + """ + Function to write the file cavename-tot.th - #file.write(u'encoding utf-8' \n\nsurvey %s -title "%s" -entrance "%s" \n' - # %(cavename.replace(u' ', u'_'), cavename, entrance)) + INPUTS: + file : variable that sets the file.th + cavename : name of the cave + icomments : True if comments in the file + False if not + thlang : 'fr' for french + 'en' for english + ... other languages not implemented - if icomments: - if thlang == u'fr': - file.write(u'# Copyright (C) %s Xavier Robert \n' %(str(datetime.datetime.now().year))) - file.write(u'# Ce travaille est sous la License Creative Commons Attribution-ShareAlike-NonCommecial :\n') - file.write(u'# \n\n') - elif thlang == u'en': - file.write(u'# Copyright (C) %s Xavier Robert \n' %(str(datetime.datetime.now().year))) - file.write(u'# This work is under the Creative Commons Attribution-ShareAlike-NonCommecial License:\n') - file.write(u'# \n\n') - - file.write(u'survey %s -title "%s"\n\n' %(sanitize_filename(cavename), cavename.replace(u' ', u'_'))) - #file.write(u'survey %s -title "%s"\n\n' %(cavename.replace(u' ', u'_'), cavename.replace(u' ', u'_'))) + OUTPUTS: + None - if icomments: - if thlang == u'fr': - file.write(u'\t# Pour importer les différentes données de différents fichiers topos :\n') - if thlang == u'en': - file.write(u'\t# To import data from different data files:\n') - file.write(u'\tinput Data/%s.th\n\n' %(cavename.replace(u' ', u'_'))) - - file.write(u'#\tcenterline\n') - if icomments: - if thlang == u'fr': file.write(u'\t\t##Rajout des longueurs explorées, non topo, ou topos perdues\n') - elif thlang == u'en': file.write(u'\t\t##Add length explored, but not surveyed, or with lost surveys\n') + USAGE: + write_thtot(file, cavename, icomments, thlang) - file.write(u'#\t\tstation Ca.31@%s "+78 m explorés " continuation explored 78m\n' %(cavename.replace(u' ', u'_'))) - if icomments: - if thlang == u'fr': file.write(u'\t\t## Pour assembler plusieurs fichiers topos\n') - elif thlang == u'en': file.write(u'\t\t## To join different surveys\n') + Author: Xavier Robert, Grenoble 2021/01/03 - file.write(u'#\t\tequate 6@%s 0@%s\n\n'%(cavename.replace(u' ', u'_'), cavename.replace(u' ', u'_') + u'2')) - - file.write(u'#\tendcenterline)\n\n') - - if icomments: - file.write(u'#\t##########################################################################################\n') - if thlang == u'fr': - file.write(u'#\t## Pour importer les différents fichiers de dessins en plan\n') - file.write(u'#\t## Et Pour assembler plusieurs scraps entre eux, il faut utiliser la commande\n') - file.write(u"#\t## join scrap1 scrap2 -count n (où n = nombre de galerie à connecter, par défaut n = 1). C'est tout simple !\n") - elif thlang == u'en': - file.write(u'#\t## To import different th2 files\n') - file.write(u'#\t## And to join different scraps together, you need to use the command\n') - file.write(u"#\t## join scrap1 scrap2 -count n (wher n = number of connections, by default n = 1). This is simple!\n") + """ - file.write(u'#\tjoin scrap1 scrap2 #-count n\n\n') + file.write("encoding utf-8 \n\n") - if icomments: - if thlang == u'fr': file.write(u'## Pour le plan\n') - elif thlang == u'en': file.write(u'## For plan view\n') - - file.write(u'input Data/%s.th2\n\n' %(cavename.replace(u' ', u'_'))) + # file.write(u'encoding utf-8' \n\nsurvey %s -title "%s" -entrance "%s" \n' + # %(cavename.replace(u' ', u'_'), cavename, entrance)) - if icomments: - if thlang == u'fr': file.write(u'## Pour la coupe développée\n') - elif thlang == u'en': file.write(u'## For extended elevation\n') + if icomments: + if thlang == "fr": + file.write("# Copyright (C) %s Xavier Robert \n" % (str(datetime.datetime.now().year))) # noqa: DTZ005, UP031 + file.write("# Ce travaille est sous la License Creative Commons Attribution-ShareAlike-NonCommecial :\n") + file.write("# \n\n") + elif thlang == "en": + file.write("# Copyright (C) %s Xavier Robert \n" % (str(datetime.datetime.now().year))) # noqa: DTZ005, UP031 + file.write("# This work is under the Creative Commons Attribution-ShareAlike-NonCommecial License:\n") + file.write("# \n\n") - file.write(u'input Data/%s-coupe.th2\n\n' %(cavename.replace(u' ', u'_'))) + file.write('survey %s -title "%s"\n\n' % (sanitize_filename(cavename), cavename.replace(" ", "_"))) # noqa: UP031 + # file.write(u'survey %s -title "%s"\n\n' %(cavename.replace(u' ', u'_'), cavename.replace(u' ', u'_'))) - if icomments: - if thlang == u'fr': file.write(u'## Appel des maps\n') - elif thlang == u'en': file.write(u'## Call the maps file\n') + if icomments: + if thlang == "fr": + file.write("\t# Pour importer les différentes données de différents fichiers topos :\n") + if thlang == "en": + file.write("\t# To import data from different data files:\n") + file.write("\tinput Data/%s.th\n\n" % (cavename.replace(" ", "_"))) # noqa: UP031 - file.write(u'input %s-maps.th\n\n' %(cavename.replace(u' ', u'_'))) - file.write(u'endsurvey\n') + file.write("#\tcenterline\n") + if icomments: + if thlang == "fr": + file.write("\t\t##Rajout des longueurs explorées, non topo, ou topos perdues\n") + elif thlang == "en": + file.write("\t\t##Add length explored, but not surveyed, or with lost surveys\n") - return + file.write('#\t\tstation Ca.31@%s "+78 m explorés " continuation explored 78m\n' % (cavename.replace(" ", "_"))) # noqa: UP031 + if icomments: + if thlang == "fr": + file.write("\t\t## Pour assembler plusieurs fichiers topos\n") + elif thlang == "en": + file.write("\t\t## To join different surveys\n") + + file.write("#\t\tequate 6@%s 0@%s\n\n" % (cavename.replace(" ", "_"), cavename.replace(" ", "_") + "2")) # noqa: UP031 + + file.write("#\tendcenterline)\n\n") + + if icomments: + file.write("#\t##########################################################################################\n") + if thlang == "fr": + file.write("#\t## Pour importer les différents fichiers de dessins en plan\n") + file.write("#\t## Et Pour assembler plusieurs scraps entre eux, il faut utiliser la commande\n") + file.write("#\t## join scrap1 scrap2 -count n (où n = nombre de galerie à connecter, par défaut n = 1). C'est tout simple !\n") + elif thlang == "en": + file.write("#\t## To import different th2 files\n") + file.write("#\t## And to join different scraps together, you need to use the command\n") + file.write("#\t## join scrap1 scrap2 -count n (where n = number of connections, by default n = 1). This is simple!\n") + + file.write("#\tjoin scrap1 scrap2 #-count n\n\n") + + if icomments: + if thlang == "fr": + file.write("## Pour le plan\n") + elif thlang == "en": + file.write("## For plan view\n") + + file.write("input Data/%s.th2\n\n" % (cavename.replace(" ", "_"))) # noqa: UP031 + + if icomments: + if thlang == "fr": + file.write("## Pour la coupe développée\n") + elif thlang == "en": + file.write("## For extended elevation\n") + + file.write("input Data/%s-coupe.th2\n\n" % (cavename.replace(" ", "_"))) # noqa: UP031 + + if icomments: + if thlang == "fr": + file.write("## Appel des maps\n") + elif thlang == "en": + file.write("## Call the maps file\n") + + file.write("input %s-maps.th\n\n" % (cavename.replace(" ", "_"))) # noqa: UP031 + file.write("endsurvey\n") + + return # noqa: PLR1711 ################################################################################################# -def write_thmaps(file, cavename = u'cave', icomments = True, thlang = 'en'): - """ - Function to write the file cavename-maps.th - - INPUTS: - file : variable that sets the file.th - cavename : name of the cave - icomments : True if comments in the file - False if not - thlang : 'fr' for french - 'en' for english - ... other languages not implemented - - OUTPUTS: - None - - USAGE: - write_thmaps(file, cavename, icomments, thlang) - - Author: Xavier Robert, Grenoble 2021/01/03 - - """ - - file.write(u'encoding utf-8 \n\n') +def write_thmaps(file, cavename="cave", icomments=True, thlang="en"): + """ + Function to write the file cavename-maps.th - #file.write(u'encoding utf-8' \n\nsurvey %s -title "%s" -entrance "%s" \n' - # %(cavename.replace(u' ', u'_'), cavename, entrance)) + INPUTS: + file : variable that sets the file.th + cavename : name of the cave + icomments : True if comments in the file + False if not + thlang : 'fr' for french + 'en' for english + ... other languages not implemented - if icomments: - if thlang == u'fr': - file.write(u'# Copyright (C) %s Xavier Robert \n' %(str(datetime.datetime.now().year))) - file.write(u'# Ce travail est sous la License Creative Commons Attribution-ShareAlike-NonCommecial :\n') - file.write(u'# \n\n') - elif thlang == u'en': - file.write(u'# Copyright (C) %s Xavier Robert \n' %(str(datetime.datetime.now().year))) - file.write(u'# This work is under the Creative Commons Attribution-ShareAlike-NonCommecial License:\n') - file.write(u'# \n\n') + OUTPUTS: + None - file.write(u'map MP-%s-plan-tot -title "%s"\n' %(cavename.replace(u' ', u'_'), cavename.replace(u' ', u'_'))) - file.write(u'\tSP-%s-1\n' %(cavename.replace(u' ', u'_'))) - file.write(u'\t#break\n') - file.write(u'\t#SP-%s-2\n' %(cavename.replace(u' ', u'_'))) - file.write(u'endmap\n') + USAGE: + write_thmaps(file, cavename, icomments, thlang) - file.write(u'map MC-%s-coupe-tot -title "%s"\n' %(cavename.replace(u' ', u'_'), cavename.replace(u' ', u'_'))) - file.write(u'\tSC-%s-1\n' %(cavename.replace(u' ', u'_'))) - file.write(u'\t#break\n') - file.write(u'\t#SC-%s-2\n' %(cavename.replace(u' ', u'_'))) - file.write(u'endmap\n') + Author: Xavier Robert, Grenoble 2021/01/03 - return + """ + + file.write("encoding utf-8 \n\n") + + # file.write(u'encoding utf-8' \n\nsurvey %s -title "%s" -entrance "%s" \n' + # %(cavename.replace(u' ', u'_'), cavename, entrance)) + + if icomments: + if thlang == "fr": + file.write("# Copyright (C) %s Xavier Robert \n" % (str(datetime.datetime.now().year))) # noqa: DTZ005, UP031 + file.write("# Ce travail est sous la License Creative Commons Attribution-ShareAlike-NonCommecial :\n") + file.write("# \n\n") + elif thlang == "en": + file.write("# Copyright (C) %s Xavier Robert \n" % (str(datetime.datetime.now().year))) # noqa: DTZ005, UP031 + file.write("# This work is under the Creative Commons Attribution-ShareAlike-NonCommecial License:\n") + file.write("# \n\n") + + file.write('map MP-%s-plan-tot -title "%s"\n' % (cavename.replace(" ", "_"), cavename.replace(" ", "_"))) # noqa: UP031 + file.write("\tSP-%s-1\n" % (cavename.replace(" ", "_"))) # noqa: UP031 + file.write("\t#break\n") + file.write("\t#SP-%s-2\n" % (cavename.replace(" ", "_"))) # noqa: UP031 + file.write("endmap\n") + + file.write('map MC-%s-coupe-tot -title "%s"\n' % (cavename.replace(" ", "_"), cavename.replace(" ", "_"))) # noqa: UP031 + file.write("\tSC-%s-1\n" % (cavename.replace(" ", "_"))) # noqa: UP031 + file.write("\t#break\n") + file.write("\t#SC-%s-2\n" % (cavename.replace(" ", "_"))) # noqa: UP031 + file.write("endmap\n") + + return # noqa: PLR1711 ################################################################################################# -def write_thcoords(file, cavename = u'cave', coordinates = None, coordsyst = None, icomments = True, thlang = u'en'): - """ - Function to write the file Legends/entrances_coordinates.th - - INPUTS: - file : variable that sets the file.th - cavename : name of the cave - cordinates : Coordinates of the Cave - coordsyst : Coordinates system and projection - icomments : True if comments in the file - False if not - thlang : 'fr' for french - 'en' for english - ... other languages not implemented - - OUTPUTS: - None - - USAGE: - write_thcoords(file, cavename, coordinates, coordsyst, icomments, thlang) - - Author: Xavier Robert, Grenoble 2021/01/03 - - """ - - # Coordinates definition - if coordinates: - if coordsyst: - # Transform Lambert coordinates into Lat Long coordinates - inProj = Proj(coordsyst) - outProj = Proj('epsg:4326') - latc, longc = transform(inProj, outProj, float(coordinates[0]), float(coordinates[1])) - else: - latc = coordinates[1] + u'(Check coord. syst.)' - longc = coordinates[0] + u'(Check coord. syst.)' - altc = coordinates[2] - else: - latc = u'None' - longc = u'None' - altc = u'None' - - file.write(u'encoding utf-8 \n\n') +def write_thcoords(file, cavename="cave", coordinates=None, coordsyst=None, icomments=True, thlang="en"): + """ + Function to write the file Legends/entrances_coordinates.th - if icomments: - if thlang == u'fr': - file.write(u'# Copyright (C) %s Xavier Robert \n' %(str(datetime.datetime.now().year))) - file.write(u'# Ce travail est sous la License Creative Commons Attribution-ShareAlike-NonCommecial :\n') - file.write(u'# \n\n') - elif thlang == u'en': - file.write(u'# Copyright (C) %s Xavier Robert \n' %(str(datetime.datetime.now().year))) - file.write(u'# This work is under the Creative Commons Attribution-ShareAlike-NonCommecial License:\n') - file.write(u'# \n\n') + INPUTS: + file : variable that sets the file.th + cavename : name of the cave + coordinates : Coordinates of the Cave + coordsyst : Coordinates system and projection + icomments : True if comments in the file + False if not + thlang : 'fr' for french + 'en' for english + ... other languages not implemented - file.write(u'layout Entrances_coords_%s\n\n' %(cavename.replace(u' ', u'_'))) - - if icomments: - if thlang == u'fr': - file.write(u'\t# Layout qui définit les différentes variables contenant du texte avec \n') - file.write(u"\t# les coordonnées de l'entrée que nous voulons ajouter au header.\n") - file.write(u"\t# Nous avons besoin d'une variable par entrée.\n") - file.write(u'\t# Ce layout est appelé par le layout Coords_Header ci-dessous\n\n') - elif thlang == u'en': - file.write(u'\t# Layout where we define the different variables that contain the text with \n') - file.write(u'\t# the entrance coordinates we want to print in the header.\n') - file.write(u'\t# We need one variable per entrance.\n') - file.write(u'\t# This layout is called by the layout Coords_Header below\n\n') + OUTPUTS: + None - file.write(u'\tcode tex-map\n') - file.write(u'\t\t\\def\\thjunk{ }\n') - file.write(u'\t\t\\def\\thlocation%s{%s -- Lat. : %s N ; Long. : %s E ; Alt. : %s m}\n' %(cavename.replace(u' ', u'_'), cavename.replace(u' ', u'_'), str(latc), str(longc), str(altc))) - # We probably need in the future to iterate on the number of entrances... - # I do not knwo for the moment if Visual Top take in account different entrences coordinates - file.write(u'\tendcode\n\n') - - file.write(u'\tendlayout\n\n') + USAGE: + write_thcoords(file, cavename, coordinates, coordsyst, icomments, thlang) + Author: Xavier Robert, Grenoble 2021/01/03 - file.write(u'layout Coords_Header_%s\n\n' %(cavename.replace(u' ', u'_'))) - if icomments: - if thlang == u'fr': file.write(u'\t# Layout that set the presentation for the entrance coordinates.\n\n') - - file.write(u'\tcopy Entrances_coords_%s\n\n' %(cavename.replace(u' ', u'_'))) - if icomments: - if thlang == u'fr': - file.write(u'\t# Appelle le layout ci-dessus Entrances_coords où nous avons défini les différentes \n') - file.write(u'\t# variables qui contiennent le texte avec \n') - file.write(u'\t# les coordonnées des entrées à écrire dans le header.\n\n') - elif thlang == u'en': - file.write(u'\t# it calls the layout above Entrances_coords where we defined the different \n') - file.write(u'\t# variables that contain the text with \n') - file.write(u'\t# the entrance coordinates we want to print in the header.\n\n') - - file.write(u'\tcode tex-map\n') - file.write(u'\t\t\\def\\nostring{}\n') - file.write(u'\t\t\\def\\thsizexl{}\n') - file.write(u'\t\t\\def\\thsizel{}\n') - file.write(u'\t\t\\def\\thsizem{}\n') - file.write(u'\t\t\\ifx\\thsizexl\\nostring\\def\\thsizexl{30}\\else\\fi\n') - file.write(u'\t\t\\ifx\\thsizel\\nostring\\def\\thsizel{24}\\else\\fi\n') - file.write(u'\t\t\\ifx\\thsizem\\nostring\\def\\thsizem{12}\\else\\fi\n\n') - - file.write(u'\t\t\\ECoordinates={\n') - file.write(u'\t\t\t\\edef\\tmp{\\thjunk} \\ifx\\tmp\\empty \\else\n') - file.write(u'\t\t\t\t{\\size[\\thsizem] \\ss\\thjunk\\vss}\n') - file.write(u'\t\t\t\\fi\n') - file.write(u'\t\t\t\\edef\\tmp{\\thlocation%s} \\ifx\\tmp\\empty \\else\n' %(cavename.replace(u' ', u'_'))) - file.write(u'\t\t\t\t# The first one should be without hskip\n') - file.write(u'\t\t\t\t{\\size[\\thsizem]\\hskip2cm \\ss\\thlocation%s\\vss}\n' %(cavename.replace(u' ', u'_'))) - file.write(u'\t\t\t\\fi\n') - file.write(u'\t\t\t}\n') - file.write(u'\tendcode\n\n') + """ - file.write(u'\tendlayout\n\n') + # Coordinates definition + if coordinates: + if coordsyst: + # Transform Lambert coordinates into Lat Long coordinates + inProj = Proj(coordsyst) + outProj = Proj("epsg:4326") + latc, longc = transform(inProj, outProj, float(coordinates[0]), float(coordinates[1])) + else: + latc = coordinates[1] + "(Check coord. syst.)" + longc = coordinates[0] + "(Check coord. syst.)" + altc = coordinates[2] + else: + latc = "None" + longc = "None" + altc = "None" - return \ No newline at end of file + file.write("encoding utf-8 \n\n") + + if icomments: + if thlang == "fr": + file.write("# Copyright (C) %s Xavier Robert \n" % (str(datetime.datetime.now().year))) # noqa: DTZ005, UP031 + file.write("# Ce travail est sous la License Creative Commons Attribution-ShareAlike-NonCommecial :\n") + file.write("# \n\n") + elif thlang == "en": + file.write("# Copyright (C) %s Xavier Robert \n" % (str(datetime.datetime.now().year))) # noqa: DTZ005, UP031 + file.write("# This work is under the Creative Commons Attribution-ShareAlike-NonCommecial License:\n") + file.write("# \n\n") + + file.write("layout Entrances_coords_%s\n\n" % (cavename.replace(" ", "_"))) # noqa: UP031 + + if icomments: + if thlang == "fr": + file.write("\t# Layout qui définit les différentes variables contenant du texte avec \n") + file.write("\t# les coordonnées de l'entrée que nous voulons ajouter au header.\n") + file.write("\t# Nous avons besoin d'une variable par entrée.\n") + file.write("\t# Ce layout est appelé par le layout Coords_Header ci-dessous\n\n") + elif thlang == "en": + file.write("\t# Layout where we define the different variables that contain the text with \n") + file.write("\t# the entrance coordinates we want to print in the header.\n") + file.write("\t# We need one variable per entrance.\n") + file.write("\t# This layout is called by the layout Coords_Header below\n\n") + + file.write("\tcode tex-map\n") + file.write("\t\t\\def\\thjunk{ }\n") + file.write( + "\t\t\\def\\thlocation%s{%s -- Lat. : %s N ; Long. : %s E ; Alt. : %s m}\n" # noqa: UP031 + % (cavename.replace(" ", "_"), cavename.replace(" ", "_"), str(latc), str(longc), str(altc)) + ) + # We probably need in the future to iterate on the number of entrances... + # I do not know for the moment if Visual Top take in account different entrances coordinates + file.write("\tendcode\n\n") + + file.write("\tendlayout\n\n") + + file.write("layout Coords_Header_%s\n\n" % (cavename.replace(" ", "_"))) # noqa: UP031 + if icomments: # noqa: SIM102 + if thlang == "fr": + file.write("\t# Layout that set the presentation for the entrance coordinates.\n\n") + + file.write("\tcopy Entrances_coords_%s\n\n" % (cavename.replace(" ", "_"))) # noqa: UP031 + if icomments: + if thlang == "fr": + file.write("\t# Appelle le layout ci-dessus Entrances_coords où nous avons défini les différentes \n") + file.write("\t# variables qui contiennent le texte avec \n") + file.write("\t# les coordonnées des entrées à écrire dans le header.\n\n") + elif thlang == "en": + file.write("\t# it calls the layout above Entrances_coords where we defined the different \n") + file.write("\t# variables that contain the text with \n") + file.write("\t# the entrance coordinates we want to print in the header.\n\n") + + file.write("\tcode tex-map\n") + file.write("\t\t\\def\\nostring{}\n") + file.write("\t\t\\def\\thsizexl{}\n") + file.write("\t\t\\def\\thsizel{}\n") + file.write("\t\t\\def\\thsizem{}\n") + file.write("\t\t\\ifx\\thsizexl\\nostring\\def\\thsizexl{30}\\else\\fi\n") + file.write("\t\t\\ifx\\thsizel\\nostring\\def\\thsizel{24}\\else\\fi\n") + file.write("\t\t\\ifx\\thsizem\\nostring\\def\\thsizem{12}\\else\\fi\n\n") + + file.write("\t\t\\ECoordinates={\n") + file.write("\t\t\t\\edef\\tmp{\\thjunk} \\ifx\\tmp\\empty \\else\n") + file.write("\t\t\t\t{\\size[\\thsizem] \\ss\\thjunk\\vss}\n") + file.write("\t\t\t\\fi\n") + file.write("\t\t\t\\edef\\tmp{\\thlocation%s} \\ifx\\tmp\\empty \\else\n" % (cavename.replace(" ", "_"))) # noqa: UP031 + file.write("\t\t\t\t# The first one should be without hskip\n") + file.write("\t\t\t\t{\\size[\\thsizem]\\hskip2cm \\ss\\thlocation%s\\vss}\n" % (cavename.replace(" ", "_"))) # noqa: UP031 + file.write("\t\t\t\\fi\n") + file.write("\t\t\t}\n") + file.write("\tendcode\n\n") + + file.write("\tendlayout\n\n") + + return # noqa: PLR1711 diff --git a/Scripts/pyCreateTh/Lib/pytro2th/tro2th.py b/Scripts/pyCreateTh/Lib/pytro2th/tro2th.py index 77ba595..6163cb8 100644 --- a/Scripts/pyCreateTh/Lib/pytro2th/tro2th.py +++ b/Scripts/pyCreateTh/Lib/pytro2th/tro2th.py @@ -1,5 +1,5 @@ ######!/usr/bin/env python -# -*- coding: utf8 -*- +# -*- coding: utf8 -*- # noqa: UP009 # coding: utf8 # Copyright (c) 2020 Xavier Robert @@ -8,498 +8,523 @@ # Modifié Alex 2026 01 04 -> print remplacés par log.xxx """ - !---------------------------------------------------------! - ! ! - ! Tro to Therion ! - ! ! - ! Code to transform the .tro files ! - ! Visual Topo into files that can ! - ! be used by Therion ! - ! ! - ! Written by Xavier Robert ! - ! ! - !---------------------------------------------------------! +!---------------------------------------------------------! +! ! +! Tro to Therion ! +! ! +! Code to transform the .tro files ! +! Visual Topo into files that can ! +! be used by Therion ! +! ! +! Written by Xavier Robert ! +! ! +!---------------------------------------------------------! - ENGLISH : - This code is to transform the .tro file from Visualtopo (http://vtopo.free.fr/) - into files that can be read by Therion (http://therion.speleo.sk/). - It reads .tro file and produce one .th file (file with survey data), - and one thconfig file (file that is used to compile and build the survey with Therion). - - TODOS : - Correct the errors in encodings... This is the most important.... - - Check all the situations possibles... - - Add title to the centerline ! + ENGLISH : + This code is to transform the .tro file from Visualtopo (http://vtopo.free.fr/) + into files that can be read by Therion (http://therion.speleo.sk/). + It reads .tro file and produce one .th file (file with survey data), + and one thconfig file (file that is used to compile and build the survey with Therion). + + TODOS : - Correct the errors in encodings... This is the most important.... + - Check all the situations possibles... + - Add title to the centerline ! """ + # Do divisions with Reals, not with integers # Must be at the beginning of the file -from __future__ import division -#from __future__ import unicode_literals +from __future__ import division # noqa: I001, UP010 + +# from __future__ import unicode_literals import sys, os, wget, logging from urllib.error import HTTPError # Import Python modules -#modulesNames = ['sys', 'warnings'] -#for module in modulesNames: -# try: -# # because we want to import using a variable, do it this way -# module_obj = __import__(module) -# # create a global object containging our module -# globals()[module] = module_obj -# except ImportError: -# sys.exit("ERROR : Module " + module + " not present. \n\n Please, install it \ -# \n\n Edit the source code for more information") +# modulesNames = ['sys', 'warnings'] +# for module in modulesNames: +# try: +# # because we want to import using a variable, do it this way +# module_obj = __import__(module) +# # create a global object containging our module +# globals()[module] = module_obj +# except ImportError: +# sys.exit("ERROR : Module " + module + " not present. \n\n Please, install it \ +# \n\n Edit the source code for more information") from .buildparam import * from .vtopotools import * from .datathwritetools import * from .buildthconfig import * -import os, logging, sys +import os, logging, sys # noqa: F401, F811 from Lib.general_fonctions import Colors, safe_relpath -import Lib.global_data as global_data +import Lib.global_data as global_data # noqa: PLR0402 log = logging.getLogger("Logger") + ################################################################################################# -def tro2th(fle_tro_fnme = None, fle_th_fnme = None, - fle_tro_encoding=None, - thlang = u'fr', - cavename = None, - icomments = True, icoupe = True, - ithconfig = True, istructure = True, thconfigfnme = None, - ithc = True, thcpath = None, thcfnme = u'config.thc', - sourcefile = None, xviscale = 1000, xvigrid = 10, scale = 500, - Errorfiles = True): - - """ - Main function to convert tro to th files. - This is this function that should be called from python. - - INPUTS: - fle_tro_fnme : (string) Path and name of the .tro file to convert. - if None (value by default), the function does not convert anything - but build .thconfig and config.thc files - If the path is not given, the function will look in the folder from where it is launched - fle_th_fnme : (string) Path and name of the .th file to create from the .tro file. - If None (value by default), this file is created from the .tro file name - and in the same folder than that .tro file - thlang : (string) String that set the language. 'fr' by default. - If you need english, change 'fr' to 'en' in the function definition - set 'fr' for french - set 'en' for english - ... other languages are not implemented - cavename : (string) Name of the cave. - If set to None (default value), it is get from the .tro file. - icomments : (Boolean) To add (True, by default) or not (False) comments in the produced files - icoupe : (Boolean) To set (True, by default) or not (False) an extended-elevation layout in the .thconfig file - ithconfig : (Boolean) To set if the thconfig file is created (True, by default) or not - istructure : (Boolean) To set if the structure and the addditional files are created (True, by default) or not - thconfigfnme : (string) Path and name of the thconfig file. - If None (by default), path and name build from the .tro file - ithc : (Boolean) To build (True, by default) or not (False) a config file config.thc - thcpath : (string) Path to the directry that contains the config file called in the cave.thconfig file. - If used with ithc = False, this path is only used for the declaration - in the cave.thconfig - If used with ithc = True, the config file will be written in that directory. - Set to None by default - thcfnme : (string) Name of the config.thc (value by default if set to None or if ommitted) - sourcefile : (list of strings) Define the source files declared in the cave.thconfig - ex :['example.th', 'example.th2', 'example-coupe.th2'] - If None or ommitted, it is build from the .tro file or the cavename - xviscale : (Real) Scale of the xvi file. - Set to 1000 by default that corresponds to 1/1000 - xvigrid : (Real) Spacing of the grid for the xvi, in meters. - Set 10 by default - scale : (Real) scale of the map - Set to 500 by default that corresponds to 1/500 - Errorfiles : (Boolean) If True (by default), an error will be raised if output files exists in the folder - If False, only a warning is raised, and the previous files are erased by the new ones. - Use with caution - - OUTPUTS: - Depending of the parameters inputed, several files can be produced - cavename.th : survey data for Therion - cavename.thconfig : file to build the pdf's maps and others - confgi.thc : config file for the .thconfig file. - - USAGE: - To build everything - tro2th(fle_tro_fnme = 'Test', fle_th_fnme = 'Test', - thlang = 'fr', - cavename = 'Test', - icomments = True, icoupe = True, - ithconfig = True, thconfigfnme = None, - ithc = True, thcpath = None, thcfnme = 'config.thc', - sourcefiles = None, xviscale = 1000, xvigrid = 10, scale = 500, - Errorfiles = True) - - To build only a .th file - tro2th(fle_tro_fnme = 'Test', fle_th_fnme = 'Test', - thlang = 'fr', - cavename = 'Test', - icomments = True, icoupe = True, - ithconfig = False - ithc = False - Errorfiles = True) - - To build only a thonfig file, in english, without any comments and without extended elevation layout - tro2th(thlang = 'en', - cavename = 'Test', - icomments = False, icoupe = False, - ithconfig = False, thconfigfnme = None, - ithc = False, thcpath = my/path/to/my/confg/file, thcfnme = 'config.thc', - sourcefiles = ['Test.th', 'Test.th2'], xviscale = 1000, xvigrid = 10, scale = 500, - Errorfiles = True) - - Author: Xavier Robert, Lima 2016/06/27 - - License: CCby-nc - """ - - if thlang in [u'fr', u'FR', u'Fr', u'fR']: thlang = u'fr' - elif thlang in [u'en',u'EN', u'En', u'eN']: thlang = u'en' - else: raise NameError(u'ERROR: Language %s not implemented\n' - u' Use "en" instead' % thlang ) - log.info(u'____________________________________________________________\n\n\t\tTRO 2 THERION\n____________________________________________________________\n') - if thlang == u'fr': - log.info(u'\nÉcrit par Xavier Robert, Groupe spéléo Vulcain - Lyon, France\n') - elif thlang == u'en': - log.info(u'\nWritten by Xavier Robert, Groupe spéléo Vulcain - Lyon, France\n') - log.info(u'____________________________________________________________\n\n') - - coordsyst = None - coordinates = None - if fle_tro_fnme is not None: - if fle_tro_fnme[-4:] != u'.tro': - fle_tro_fnme = fle_tro_fnme + u'.tro' - # check if file exists - if os.path.isfile(fle_tro_fnme) == False : - if thlang == u'fr': raise NameError(u'ERROR : Le fichier {FileNa} n\'existe pas'.format(FileNa=str(fle_tro_fnme))) - elif thlang == u'en': raise NameError(u'ERROR : File {FileNa} does not exist'.format(FileNa=str(fle_tro_fnme))) - - if fle_th_fnme is None: - # convert tro file to th file - log.info('1') - entrance, cavename, coordinates, coordsyst, fle_th_fnme = convert_tro(fle_tro_fnme, fle_tro_encoding=fle_tro_encoding, - icomments = icomments, icoupe = icoupe, istructure = istructure, - thlang = thlang, Errorfiles = Errorfiles) - else: - log.info(2) - entrance, cavename, coordinates, coordsyst, fle_th_fnme = convert_tro(fle_tro_fnme, fle_th_fnme, cavename, - icomments = icomments, icoupe = icoupe, istructure = istructure, - thlang = thlang, Errorfiles = Errorfiles) - if thlang == u'fr': log.info(u'\tFichier Therion %s construit à partir des données %s' %(fle_th_fnme, fle_tro_fnme)) - elif thlang == u'en': log.info(u'\tFile %s built from %s' %(fle_th_fnme, fle_tro_fnme)) - else: - if thlang == u'fr': log.info(u'\tPas de fichier .tro en entrée, pas de fichier de données .th créé...') - elif thlang == u'en': log.info(u'\tNo .tro File input, no .th data file created...') - # Build here the new structure: - if istructure: build_structure(u'cave', Errorfiles = True) +def tro2th( + fle_tro_fnme=None, + fle_th_fnme=None, + fle_tro_encoding=None, + thlang="fr", + cavename=None, + icomments=True, + icoupe=True, + ithconfig=True, + istructure=True, + thconfigfnme=None, + ithc=True, + thcpath=None, + thcfnme="config.thc", + sourcefile=None, + xviscale=1000, + xvigrid=10, + scale=500, + Errorfiles=True, +): + """ + Main function to convert tro to th files. + This is this function that should be called from python. - if sourcefile is None: - if fle_th_fnme is None: - if cavename is None: cavename = u'cave' - sourcefile = [cavename.replace(u' ', u'_') + u'.th', - u'#' + cavename.replace(u' ', u'_') + u'.th2', - u'#' + cavename.replace(u' ', u'_') + u'-coupe.th2'] - else: - sourcefile = [fle_th_fnme, u'#' + fle_th_fnme[0:-4] + u'th2', u'#' + fle_th_fnme[0:-4] + u'-coupe.th2' ] - # Build the dictionnary for the thconfig file - dictcave = [sourcefile, xviscale, xvigrid, cavename, coordsyst, scale] + INPUTS: + fle_tro_fnme : (string) Path and name of the .tro file to convert. + if None (value by default), the function does not convert anything + but build .thconfig and config.thc files + If the path is not given, the function will look in the folder from where it is launched + fle_th_fnme : (string) Path and name of the .th file to create from the .tro file. + If None (value by default), this file is created from the .tro file name + and in the same folder than that .tro file + thlang : (string) String that set the language. 'fr' by default. + If you need english, change 'fr' to 'en' in the function definition + set 'fr' for french + set 'en' for english + ... other languages are not implemented + cavename : (string) Name of the cave. + If set to None (default value), it is get from the .tro file. + icomments : (Boolean) To add (True, by default) or not (False) comments in the produced files + icoupe : (Boolean) To set (True, by default) or not (False) an extended-elevation layout in the .thconfig file + ithconfig : (Boolean) To set if the thconfig file is created (True, by default) or not + istructure : (Boolean) To set if the structure and the additional files are created (True, by default) or not + thconfigfnme : (string) Path and name of the thconfig file. + If None (by default), path and name build from the .tro file + ithc : (Boolean) To build (True, by default) or not (False) a config file config.thc + thcpath : (string) Path to the directory that contains the config file called in the cave.thconfig file. + If used with ithc = False, this path is only used for the declaration + in the cave.thconfig + If used with ithc = True, the config file will be written in that directory. + Set to None by default + thcfnme : (string) Name of the config.thc (value by default if set to None or if omitted) + sourcefile : (list of strings) Define the source files declared in the cave.thconfig + ex :['example.th', 'example.th2', 'example-coupe.th2'] + If None or omitted, it is build from the .tro file or the cavename + xviscale : (Real) Scale of the xvi file. + Set to 1000 by default that corresponds to 1/1000 + xvigrid : (Real) Spacing of the grid for the xvi, in meters. + Set 10 by default + scale : (Real) scale of the map + Set to 500 by default that corresponds to 1/500 + Errorfiles : (Boolean) If True (by default), an error will be raised if output files exists in the folder + If False, only a warning is raised, and the previous files are erased by the new ones. + Use with caution - # build thc file - if ithc : - if thcpath is not None : - # Download the config file from my github page - try: - wget.download('https://raw.githubusercontent.com/robertxa/Th-Config-Xav/master/config.thc', - thcpath) - #thcpath + thcfnme) - except HTTPError: - if thcpath[-1] not in ['/', '\\']: thcpath = thcpath + '/' - writethc(thcpath + thcfnme, istructure) - except FileNotFoundError: - if thcpath[-1] not in ['/', '\\']: thcpath = thcpath + '/' - writethc(thcpath + thcfnme, istructure) - else: - # Download the config file from my github page - try: - if istructure: wget.download('https://raw.githubusercontent.com/robertxa/Th-Config-Xav/master/config.thc', - cavename.replace(u' ', u'_') + '/') - else: wget.download('https://raw.githubusercontent.com/robertxa/Th-Config-Xav/master/config.thc') - except HTTPError: - writethc(thcfnme, cavename, istructure) - except FileNotFoundError: - writethc(thcfnme, cavename, istructure) - - # build thconfig file - # Needs to be change to take in account istructure - if ithconfig : - # write the file - if thconfigfnme is None or thconfigfnme == u'' or thconfigfnme == u' ': - if fle_th_fnme is None: thconfigfnme = cavename.replace(u' ', u'_') + u'.thconfig' - else: thconfigfnme = fle_th_fnme[0:-3] + u'.thconfig' - - if thcpath is not None: - thcfnme = thcpath + thcfnme - writethconfig(cavename.replace(u' ', u'_') + thconfigfnme, icomments, icoupe, thlang, - dictcave, - ithc, thcfnme) - else: - thcfnme = thcfnme - writethconfig(cavename.replace(u' ', u'_') + thconfigfnme, icomments, icoupe, thlang, - dictcave, - ithc, cavename.replace(u' ', u'_') + u'/config.thc') + OUTPUTS: + Depending of the parameters inputted, several files can be produced + cavename.th : survey data for Therion + cavename.thconfig : file to build the pdf's maps and others + config.thc : config file for the .thconfig file. - if istructure: - # build cavename-tot.th file - f3w = open(cavename.replace(u' ', u'_') + '/' + cavename.replace(u' ', u'_') + '-tot.th', 'w') - write_thtot(f3w, cavename, icomments, thlang) - f3w.closed - log.info(u'\tFile ' + cavename.replace(u' ', u'_') + u'/' + cavename.replace(u' ', u'_') + u'-tot.th written...\n') + USAGE: + To build everything + tro2th(fle_tro_fnme = 'Test', fle_th_fnme = 'Test', + thlang = 'fr', + cavename = 'Test', + icomments = True, icoupe = True, + ithconfig = True, thconfigfnme = None, + ithc = True, thcpath = None, thcfnme = 'config.thc', + sourcefiles = None, xviscale = 1000, xvigrid = 10, scale = 500, + Errorfiles = True) - # build cavename-maps.th file - f4w = open(cavename.replace(u' ', u'_') + u'/' + cavename.replace(u' ', u'_') + '-maps.th', 'w') - write_thmaps(f4w, cavename, icomments, thlang) - f4w.closed - log.info(u'\tFile ' + cavename.replace(u' ', u'_') + u'/' + cavename.replace(u' ', u'_') + u'-maps.th written...\n\n') + To build only a .th file + tro2th(fle_tro_fnme = 'Test', fle_th_fnme = 'Test', + thlang = 'fr', + cavename = 'Test', + icomments = True, icoupe = True, + ithconfig = False + ithc = False + Errorfiles = True) - # build Legends/entrances-coordinates.th file - f5w = open(cavename.replace(u' ', u'_') + '/Legends/entrances_coordinates.th', 'w') - write_thcoords(f5w, cavename, coordinates, coordsyst, icomments, thlang) - f5w.closed - log.info(u'\tFile ' + cavename.replace(u' ', u'_') + u'/Legends/entrances_coordinates.th written...\n\n') + To build only a thconfig file, in english, without any comments and without extended elevation layout + tro2th(thlang = 'en', + cavename = 'Test', + icomments = False, icoupe = False, + ithconfig = False, thconfigfnme = None, + ithc = False, thcpath = my/path/to/my/config/file, thcfnme = 'config.thc', + sourcefiles = ['Test.th', 'Test.th2'], xviscale = 1000, xvigrid = 10, scale = 500, + Errorfiles = True) - log.info(u'____________________________________________________________') - log.info(u'') - - return + Author: Xavier Robert, Lima 2016/06/27 + + License: CCby-nc + """ + + if thlang in ["fr", "FR", "Fr", "fR"]: + thlang = "fr" + elif thlang in ["en", "EN", "En", "eN"]: + thlang = "en" + else: + raise NameError( + "ERROR: Language %s not implemented\n" # noqa: UP031 + ' Use "en" instead' % thlang + ) + log.info("____________________________________________________________\n\n\t\tTRO 2 THERION\n____________________________________________________________\n") + if thlang == "fr": + log.info("\nÉcrit par Xavier Robert, Groupe spéléo Vulcain - Lyon, France\n") + elif thlang == "en": + log.info("\nWritten by Xavier Robert, Groupe spéléo Vulcain - Lyon, France\n") + log.info("____________________________________________________________\n\n") + + coordsyst = None + coordinates = None + if fle_tro_fnme is not None: + if fle_tro_fnme[-4:] != ".tro": + fle_tro_fnme = fle_tro_fnme + ".tro" + # check if file exists + if os.path.isfile(fle_tro_fnme) == False: + if thlang == "fr": + raise NameError("ERROR : Le fichier {FileNa} n'existe pas".format(FileNa=str(fle_tro_fnme))) # noqa: UP032 + elif thlang == "en": + raise NameError("ERROR : File {FileNa} does not exist".format(FileNa=str(fle_tro_fnme))) # noqa: UP032 + + if fle_th_fnme is None: + # convert tro file to th file + log.info("1") + entrance, cavename, coordinates, coordsyst, fle_th_fnme = convert_tro( + fle_tro_fnme, fle_tro_encoding=fle_tro_encoding, icomments=icomments, icoupe=icoupe, istructure=istructure, thlang=thlang, Errorfiles=Errorfiles + ) + else: + log.info(2) + entrance, cavename, coordinates, coordsyst, fle_th_fnme = convert_tro( # noqa: RUF059 + fle_tro_fnme, fle_th_fnme, cavename, icomments=icomments, icoupe=icoupe, istructure=istructure, thlang=thlang, Errorfiles=Errorfiles + ) + if thlang == "fr": + log.info("\tFichier Therion %s construit à partir des données %s" % (fle_th_fnme, fle_tro_fnme)) # noqa: UP031 + elif thlang == "en": + log.info("\tFile %s built from %s" % (fle_th_fnme, fle_tro_fnme)) # noqa: UP031 + else: + if thlang == "fr": + log.info("\tPas de fichier .tro en entrée, pas de fichier de données .th créé...") + elif thlang == "en": + log.info("\tNo .tro File input, no .th data file created...") + # Build here the new structure: + if istructure: + build_structure("cave", Errorfiles=True) + + if sourcefile is None: + if fle_th_fnme is None: + if cavename is None: + cavename = "cave" + sourcefile = [cavename.replace(" ", "_") + ".th", "#" + cavename.replace(" ", "_") + ".th2", "#" + cavename.replace(" ", "_") + "-coupe.th2"] + else: + sourcefile = [fle_th_fnme, "#" + fle_th_fnme[0:-4] + "th2", "#" + fle_th_fnme[0:-4] + "-coupe.th2"] + # Build the dictionary for the thconfig file + dictcave = [sourcefile, xviscale, xvigrid, cavename, coordsyst, scale] + + # build thc file + if ithc: + if thcpath is not None: + # Download the config file from my github page + try: + wget.download("https://raw.githubusercontent.com/robertxa/Th-Config-Xav/master/config.thc", thcpath) + # thcpath + thcfnme) + except HTTPError: + if thcpath[-1] not in ["/", "\\"]: + thcpath = thcpath + "/" + writethc(thcpath + thcfnme, istructure) + except FileNotFoundError: + if thcpath[-1] not in ["/", "\\"]: + thcpath = thcpath + "/" + writethc(thcpath + thcfnme, istructure) + else: + # Download the config file from my github page + try: + if istructure: + wget.download("https://raw.githubusercontent.com/robertxa/Th-Config-Xav/master/config.thc", cavename.replace(" ", "_") + "/") + else: + wget.download("https://raw.githubusercontent.com/robertxa/Th-Config-Xav/master/config.thc") + except HTTPError: + writethc(thcfnme, cavename, istructure) + except FileNotFoundError: + writethc(thcfnme, cavename, istructure) + + # build thconfig file + # Needs to be change to take in account istructure + if ithconfig: + # write the file + if thconfigfnme is None or thconfigfnme == "" or thconfigfnme == " ": + if fle_th_fnme is None: + thconfigfnme = cavename.replace(" ", "_") + ".thconfig" + else: + thconfigfnme = fle_th_fnme[0:-3] + ".thconfig" + + if thcpath is not None: + thcfnme = thcpath + thcfnme + writethconfig(cavename.replace(" ", "_") + thconfigfnme, icomments, icoupe, thlang, dictcave, ithc, thcfnme) + else: + thcfnme = thcfnme # noqa: PLW0127 + writethconfig(cavename.replace(" ", "_") + thconfigfnme, icomments, icoupe, thlang, dictcave, ithc, cavename.replace(" ", "_") + "/config.thc") + + if istructure: + # build cavename-tot.th file + f3w = open(cavename.replace(" ", "_") + "/" + cavename.replace(" ", "_") + "-tot.th", "w") # noqa: SIM115 + write_thtot(f3w, cavename, icomments, thlang) + f3w.closed # noqa: B018 + log.info("\tFile " + cavename.replace(" ", "_") + "/" + cavename.replace(" ", "_") + "-tot.th written...\n") + + # build cavename-maps.th file + f4w = open(cavename.replace(" ", "_") + "/" + cavename.replace(" ", "_") + "-maps.th", "w") # noqa: SIM115 + write_thmaps(f4w, cavename, icomments, thlang) + f4w.closed # noqa: B018 + log.info("\tFile " + cavename.replace(" ", "_") + "/" + cavename.replace(" ", "_") + "-maps.th written...\n\n") + + # build Legends/entrances-coordinates.th file + f5w = open(cavename.replace(" ", "_") + "/Legends/entrances_coordinates.th", "w") # noqa: SIM115 + write_thcoords(f5w, cavename, coordinates, coordsyst, icomments, thlang) + f5w.closed # noqa: B018 + log.info("\tFile " + cavename.replace(" ", "_") + "/Legends/entrances_coordinates.th written...\n\n") + + log.info("____________________________________________________________") + log.info("") + + return # noqa: PLR1711 ################################################################################################# -def build_structure(cavename, Errorfiles = True): - """ - Check and build if needed the new structure: - -Cave/ - -Data/ - -cavename.th - (-cavename.th2) - -Legends/ - -entrances_coordinates.th - -Outputs/ - -outputs.txt - -Cavename.thconfig - -cavename-tot.th - -cavename-maps.th - -config.thc - - INPUTS: - cavename = name of the cave that is used to build all the folders and file structure - Errorfiles = Boolean; If True (Default), the program stops if the structure already exists - If False or none, if the structure exists, it is erased +def build_structure(cavename, Errorfiles=True): + """ + Check and build if needed the new structure: + -Cave/ + -Data/ + -cavename.th + (-cavename.th2) + -Legends/ + -entrances_coordinates.th + -Outputs/ + -outputs.txt + -Cavename.thconfig + -cavename-tot.th + -cavename-maps.th + -config.thc - OUTPUTS: - None, except a new structure + INPUTS: + cavename = name of the cave that is used to build all the folders and file structure + Errorfiles = Boolean; If True (Default), the program stops if the structure already exists + If False or none, if the structure exists, it is erased - USAGE: - build_structure(cavename, Errorfiles) + OUTPUTS: + None, except a new structure - """ - - # check if the folder cavename/ exists - if os.path.exists(cavename.replace(u' ', u'_')): - if Errorfiles: - # Stop - raise NameError(u'ERROR : Folder {FileNa} does exist'.format(FileNa=str(cavename.replace(u' ', u'_')))) - else: - log.warning(f"I have erased the folder {Colors.ENDC}{cavename.replace(u' ', u'_')}") - if not os.path.exists(cavename.replace(u' ', u'_') + u'/Data'): os.mkdir(cavename.replace(u' ', u'_') + u'/Data') - if not os.path.exists(cavename.replace(u' ', u'_') + u'/Legends'): os.mkdir(cavename.replace(u' ', u'_') + u'/Legends') - if not os.path.exists(cavename.replace(u' ', u'_') + u'/Outputs'): - os.mkdir(cavename.replace(u' ', u'_') + u'/Outputs') - # Add outputs.txt file - mkfle_output_txt(cavename.replace(u' ', u'_')) - # - if no, create it and create the other files - else: - # Create the subfolders - os.mkdir(cavename.replace(u' ', u'_')) - os.mkdir(cavename.replace(u' ', u'_') + u'/Data') - os.mkdir(cavename.replace(u' ', u'_') + u'/Outputs') - # Add outputs.txt file - mkfle_output_txt(cavename.replace(u' ', u'_')) - os.mkdir(cavename.replace(u' ', u'_') + u'/Legends') - - return + USAGE: + build_structure(cavename, Errorfiles) + + """ + + # check if the folder cavename/ exists + if os.path.exists(cavename.replace(" ", "_")): + if Errorfiles: + # Stop + raise NameError("ERROR : Folder {FileNa} does exist".format(FileNa=str(cavename.replace(" ", "_")))) + else: + log.warning(f"I have erased the folder {Colors.ENDC}{cavename.replace(' ', '_')}") + if not os.path.exists(cavename.replace(" ", "_") + "/Data"): + os.mkdir(cavename.replace(" ", "_") + "/Data") + if not os.path.exists(cavename.replace(" ", "_") + "/Legends"): + os.mkdir(cavename.replace(" ", "_") + "/Legends") + if not os.path.exists(cavename.replace(" ", "_") + "/Outputs"): + os.mkdir(cavename.replace(" ", "_") + "/Outputs") + # Add outputs.txt file + mkfle_output_txt(cavename.replace(" ", "_")) + # - if no, create it and create the other files + else: + # Create the subfolder + os.mkdir(cavename.replace(" ", "_")) + os.mkdir(cavename.replace(" ", "_") + "/Data") + os.mkdir(cavename.replace(" ", "_") + "/Outputs") + # Add outputs.txt file + mkfle_output_txt(cavename.replace(" ", "_")) + os.mkdir(cavename.replace(" ", "_") + "/Legends") + + return # noqa: PLR1711 ################################################################################################# def mkfle_output_txt(cavename): - """ - Build the file Output.txt in the folder cavename/Outputs/ + """ + Build the file Output.txt in the folder cavename/Outputs/ - INPUTS: - cavename = name of the cave + INPUTS: + cavename = name of the cave - OUTPUTS: - None + OUTPUTS: + None - USAGE: - create_output_txt(cavename) - """ - # Open the cavename/Outputs/outputs.txt file - f1w = open(cavename.replace(u' ', u'_') + u'/Outputs/outputs.txt','w') - f1w.write(u'Folder where Therion outputs are exported \n\n') - # close the cavename/Outputs/outputs.txt file - f1w.closed - log.info(u'\tFile ' + cavename.replace(u' ', u'_') + u'/Outputs/outputs.txt written...') - - return + USAGE: + create_output_txt(cavename) + """ + # Open the cavename/Outputs/outputs.txt file + f1w = open(cavename.replace(" ", "_") + "/Outputs/outputs.txt", "w") # noqa: SIM115 + f1w.write("Folder where Therion outputs are exported \n\n") + # close the cavename/Outputs/outputs.txt file + f1w.closed # noqa: B018 + log.info("\tFile " + cavename.replace(" ", "_") + "/Outputs/outputs.txt written...") + + return # noqa: PLR1711 ################################################################################################# -def convert_tro(fle_tro_fnme, fle_tro_encoding=None, fle_th_fnme = None, cavename = None, - icomments = True, icoupe = True, istructure = True, thlang = u'fr', Errorfiles = True): - """ - Function that manages the tro 2 th conversion - - INPUTS: - fle_tro_fnme : path and file name of the .tro file to convert - fle_th_fnme : path and file name of the .th file to create. - If ommitted, set to None, and this varaible will be set in function of the fle_tro_fnme or cavename - cavename : Name of the cave. If ommitted, it is set to None, and it is get from the .tro file - icomments : (Boolean) To add (True, by default) or not (False) comments in the produced files - icoupe : (Boolean) To set (True, by default) or not (False) an extended-elevation layout in the .thconfig file - istructure : (Boolean) To set if the structure and the addditional files are created (True, by default) or not - thlang : (string) String that set the language. 'fr' by default. - If you need english, change 'fr' to 'en' in the function definition - set 'fr' for french - set 'en' for english - - Errorfiles : True (by default if ommitted) to get an error if the .th file already exists. - False if only a warning... - OUTPUTS: - new .th file with surveyed data for Therion - cavename : Name of the cave from the .tro file - coordinates : Coordinates of the entrance (in m) - coordsyst : Coordinates system used by the .tro file - entrance : Entrance station - - USAGE: - cavename, coordsyst = convert_tro(fle_tro_fnme, [fle_th_fnme = fle_th_fnme, cavename = cavename, Errorfiles = Errorfiles]) - fle_th_fnme, cavename and Errorfiles can be ommitted. - - Author: Xavier Robert, Lima 2016/06/27 - - License: CCby-nc - """ - - #from codecs import open - - # Initialization of some variables... - #xcoord=0. - #ycoord=0. - #alt=0. - - # open the .tro survey - log.info(f"Processing VisualTopo file: {Colors.ENDC}{safe_relpath(fle_tro_fnme)}") - - # print(' ') - fle_tro = open(fle_tro_fnme, 'r', encoding=fle_tro_encoding) - # read the .tro file - try: - lines = fle_tro.readlines() - # change the encoding - lines = convert_text(lines) - except UnicodeDecodeError: - # find the line where there is the error - # initiate the line number - lineNumber = 1 - try: - # read the first line - line = fle_tro.redline() - while line: - # update the line number - lineNumber += 1 - # read the next line - line = fle_tro.readline() - except UnicodeDecodeError: - log.error(f"Special or accentuated character not supporter line {Colors.ENDC}{lineNumber}{Colors.ERROR}, correct the input file") - global_data.error_count += 1 - - - - # read the header - coordinates = None - cavename, coordinates, coordsyst, club, entrance, versionfle = read_vtopo_header(lines) - - if cavename is None or cavename == '' or cavename == ' ': - cavename = u'cave' - - if fle_th_fnme is None: - fle_th_fnme = cavename.replace(u' ', u'_') + u'.th' - log.info (fle_th_fnme) - if fle_th_fnme[-3:] != u'.th': - fle_th_fnme = fle_th_fnme + u'.th' - - - # Build here the new structure: - if istructure: build_structure(cavename, Errorfiles) +def convert_tro(fle_tro_fnme, fle_tro_encoding=None, fle_th_fnme=None, cavename=None, icomments=True, icoupe=True, istructure=True, thlang="fr", Errorfiles=True): + """ + Function that manages the tro 2 th conversion - # check if file exists... - checkfiles(fle_th_fnme, Errorfiles) - - # open the .th file - if istructure: fle_th = open (cavename.replace(u' ', u'_') + '/Data/' + fle_th_fnme, 'w') - else: fle_th = open (fle_th_fnme, 'w') - - # write the .th header - writeheader_th(fle_th, cavename, entrance) - - # initiate variables - i = 0 - iline = [] - dataold = [] - - # get line numbers of the lines beginning with 'Param' - for line in lines: - if u'Param' in line: iline.append(i) - i+=1 - - for j in iline: - # read the settings of the survey - settings, comments = read_settings(lines[j].replace(u'\n', u'')) - - # read the data from the tro file - data = read_data(lines, settings, j, iline) - - # write centerline header - writecenterlineheader(fle_th, entrance, settings, comments, data, coordsyst, coordinates, club, - icomments, thlang) + INPUTS: + fle_tro_fnme : path and file name of the .tro file to convert + fle_th_fnme : path and file name of the .th file to create. + If omitted, set to None, and this variable will be set in function of the fle_tro_fnme or cavename + cavename : Name of the cave. If omitted, it is set to None, and it is get from the .tro file + icomments : (Boolean) To add (True, by default) or not (False) comments in the produced files + icoupe : (Boolean) To set (True, by default) or not (False) an extended-elevation layout in the .thconfig file + istructure : (Boolean) To set if the structure and the additional files are created (True, by default) or not + thlang : (string) String that set the language. 'fr' by default. + If you need english, change 'fr' to 'en' in the function definition + set 'fr' for french + set 'en' for english - # write the data to the .th file - writedata(fle_th, settings, data, dataold) - - # write the end of the centerline in the .th file - fle_th.write(u'\n\tendcenterline\n\n') - dataold = data - # write the end of the survey in the .th file - fle_th.write(u'\nendsurvey\n') - fle_th.close - - #print (fle_th_fnme) - - if thlang == u'fr': log.info(f"Fichier Therion {Colors.ENDC}{fle_th_fnme}{Colors.INFO} écrit !") - elif thlang == u'en': log.info(f"Therion file {Colors.ENDC}{fle_th_fnme}{Colors.INFO} written!") - - return entrance, cavename, coordinates, coordsyst, fle_th_fnme + Errorfiles : True (by default if omitted) to get an error if the .th file already exists. + False if only a warning... + OUTPUTS: + new .th file with surveyed data for Therion + cavename : Name of the cave from the .tro file + coordinates : Coordinates of the entrance (in m) + coordsyst : Coordinates system used by the .tro file + entrance : Entrance station + + USAGE: + cavename, coordsyst = convert_tro(fle_tro_fnme, [fle_th_fnme = fle_th_fnme, cavename = cavename, Errorfiles = Errorfiles]) + fle_th_fnme, cavename and Errorfiles can be omitted. + + Author: Xavier Robert, Lima 2016/06/27 + + License: CCby-nc + """ + + # from codecs import open + + # Initialization of some variables... + # xcoord=0. + # ycoord=0. + # alt=0. + + # open the .tro survey + log.info(f"Processing VisualTopo file: {Colors.ENDC}{safe_relpath(fle_tro_fnme)}") + + # print(' ') + fle_tro = open(fle_tro_fnme, "r", encoding=fle_tro_encoding) # noqa: SIM115 + # read the .tro file + try: + lines = fle_tro.readlines() + # change the encoding + lines = convert_text(lines) + except UnicodeDecodeError: + # find the line where there is the error + # initiate the line number + lineNumber = 1 + try: + # read the first line + line = fle_tro.redline() + while line: + # update the line number + lineNumber += 1 + # read the next line + line = fle_tro.readline() + except UnicodeDecodeError: + log.error(f"Special or accentuated character not supporter line {Colors.ENDC}{lineNumber}{Colors.ERROR}, correct the input file") + global_data.error_count += 1 + + # read the header + coordinates = None + cavename, coordinates, coordsyst, club, entrance, versionfle = read_vtopo_header(lines) # noqa: RUF059 + + if cavename is None or cavename == "" or cavename == " ": + cavename = "cave" + + if fle_th_fnme is None: + fle_th_fnme = cavename.replace(" ", "_") + ".th" + log.info(fle_th_fnme) + if fle_th_fnme[-3:] != ".th": + fle_th_fnme = fle_th_fnme + ".th" + + # Build here the new structure: + if istructure: + build_structure(cavename, Errorfiles) + + # check if file exists... + checkfiles(fle_th_fnme, Errorfiles) + + # open the .th file + if istructure: + fle_th = open(cavename.replace(" ", "_") + "/Data/" + fle_th_fnme, "w") # noqa: SIM115 + else: + fle_th = open(fle_th_fnme, "w") # noqa: SIM115 + + # write the .th header + writeheader_th(fle_th, cavename, entrance) + + # initiate variables + i = 0 + iline = [] + dataold = [] + + # get line numbers of the lines beginning with 'Param' + for line in lines: + if "Param" in line: + iline.append(i) + i += 1 # noqa: SIM113 + + for j in iline: + # read the settings of the survey + settings, comments = read_settings(lines[j].replace("\n", "")) + + # read the data from the tro file + data = read_data(lines, settings, j, iline) + + # write centerline header + writecenterlineheader(fle_th, entrance, settings, comments, data, coordsyst, coordinates, club, icomments, thlang, cavename) + + # write the data to the .th file + writedata(fle_th, settings, data, dataold) + + # write the end of the centerline in the .th file + fle_th.write("\n\tendcenterline\n\n") + dataold = data + # write the end of the survey in the .th file + fle_th.write("\nendsurvey\n") + fle_th.close # noqa: B018 + + # print (fle_th_fnme) + + if thlang == "fr": + log.info(f"Fichier Therion {Colors.ENDC}{fle_th_fnme}{Colors.INFO} écrit !") + elif thlang == "en": + log.info(f"Therion file {Colors.ENDC}{fle_th_fnme}{Colors.INFO} written!") + + return entrance, cavename, coordinates, coordsyst, fle_th_fnme ################################################################################################# -if __name__ == u'__main__': - - - # initiate variables - - # run the transformation - tro2th() +if __name__ == "__main__": + # initiate variables + + # run the transformation + tro2th() diff --git a/Scripts/pyCreateTh/Lib/th2th.py b/Scripts/pyCreateTh/Lib/th2th.py index d64d65e..1849928 100644 --- a/Scripts/pyCreateTh/Lib/th2th.py +++ b/Scripts/pyCreateTh/Lib/th2th.py @@ -1,36 +1,37 @@ """ - !---------------------------------------------------------! - ! ! - ! th to Therion ! - ! ! - ! Code to transform the .th files ! - ! ! - ! be used by Therion ! - ! ! - ! Written by Alexandre Pont ! - ! ! - !---------------------------------------------------------! +!---------------------------------------------------------! +! ! +! th to Therion ! +! ! +! Code to transform the .th files ! +! ! +! be used by Therion ! +! ! +! Written by Alexandre Pont ! +! ! +!---------------------------------------------------------! - ENGLISH : - Création Alex 2026 01 09 + ENGLISH : + Création Alex 2026 01 09 + + +TODOS : -.... - - TODOS : -.... - """ ################################################################################################# ################################################################################################# -import os, re, argparse, shutil, sys, time, math, logging -from os.path import isfile, join, abspath, splitext +import os, re, shutil, math, logging, sys # noqa: I001 +from os.path import isfile, join from pathlib import Path import numpy as np import networkx as nx import pandas as pd -pd.set_option('future.no_silent_downcasting', True) -from datetime import datetime -from collections import defaultdict -from contextlib import redirect_stdout + +pd.set_option("future.no_silent_downcasting", True) +from datetime import datetime # noqa: I001 +from collections import defaultdict # noqa: F401 +from contextlib import redirect_stdout # noqa: F401 from Lib.survey import SurveyLoader, NoSurveysFoundException from Lib.therion import compile_template, compile_file, get_stats_from_log @@ -120,18 +121,15 @@ def add_start_end_splays(df_splays_complet, df_equates): if not splay_example.empty: splay_example["group_id"] = group_id splay_example["rank_in_group"] = row["max_rank"] + 1 - ref_row = df_splays_complet[ - (df_splays_complet["group_id"] == group_id) & - (df_splays_complet["rank_in_group"] == row["max_rank"] - 1) - ] + ref_row = df_splays_complet[(df_splays_complet["group_id"] == group_id) & (df_splays_complet["rank_in_group"] == row["max_rank"] - 1)] if not ref_row.empty: splay_example["longueur_ref"] = ref_row.iloc[0]["longueur_ref"] splay_example["bissectrice"] = ref_row.iloc[0]["bissectrice"] - splay_example = splay_example.drop_duplicates() + splay_example = splay_example.drop_duplicates() df_splays_new = pd.concat([df_splays_new, splay_example], ignore_index=True) - # print(f"\n splay_example end add: {len(splay_example)}") + # print(f"\n splay_example end add: {len(splay_example)}") # print(splay_example) - + # Vérifie si le end_point est déjà dans les splays mask = (df_splays_complet["name1"] == start_point) & (df_splays_complet["group_id"] == start_group) if not mask.any(): @@ -140,22 +138,19 @@ def add_start_end_splays(df_splays_complet, df_equates): if not splay_example.empty: splay_example["group_id"] = group_id splay_example["rank_in_group"] = 0 - ref_row = df_splays_complet[ - (df_splays_complet["group_id"] == start_group) & - (df_splays_complet["rank_in_group"] == 0) - ] + ref_row = df_splays_complet[(df_splays_complet["group_id"] == start_group) & (df_splays_complet["rank_in_group"] == 0)] if not ref_row.empty: splay_example["longueur_ref"] = ref_row.iloc[0]["longueur_ref"] splay_example["bissectrice"] = ref_row.iloc[0]["bissectrice"] - splay_example = splay_example.drop_duplicates() + splay_example = splay_example.drop_duplicates() df_splays_new = pd.concat([df_splays_new, splay_example], ignore_index=True) - # print(f"\n splay_example start add : {len(splay_example)}") + # print(f"\n splay_example start add : {len(splay_example)}") # print(splay_example) - + # else: - # Aucun splay existant pour ce group_id : on ignore ou on crée un modèle vide - # print(f"Aucun modèle de splay pour group_id {group_id} — point {end_point} ignoré.") - + # Aucun splay existant pour ce group_id : on ignore ou on crée un modèle vide + # print(f"Aucun modèle de splay pour group_id {group_id} — point {end_point} ignoré.") + return df_splays_new @@ -170,7 +165,7 @@ def convert_to_line_polaire_df(df_lines): Returns: pd.DataFrame: Un DataFrame avec les colonnes polaires. """ - + try: # Forcer la conversion des colonnes numériques df_lines = df_lines.copy() # évite de modifier l'original @@ -180,43 +175,46 @@ def convert_to_line_polaire_df(df_lines): # Supprimer les lignes invalides (NaN après conversion) df_lines = df_lines.dropna(subset=cols_to_float) - - + dx = df_lines["x2"] - df_lines["x1"] dy = df_lines["y2"] - df_lines["y1"] - + # Calcul de la longueur et de l'azimut length = np.hypot(dx, dy) azimut = (np.degrees(np.arctan2(dx, dy))) % 360 if "group_id" in df_lines.columns: - df_polaire = pd.DataFrame({ - "x1": df_lines["x1"], - "y1": df_lines["y1"], - "x2": df_lines["x2"], - "y2": df_lines["y2"], - "azimut_deg": azimut, - "longueur": length, - "name1": df_lines["name1"], - "name2": df_lines["name2"], - "group_id": df_lines["group_id"], - "rank_in_group": df_lines["rank_in_group"], - }) - else : - df_polaire = pd.DataFrame({ - "x1": df_lines["x1"], - "y1": df_lines["y1"], - "x2": df_lines["x2"], - "y2": df_lines["y2"], - "azimut_deg": azimut, - "longueur": length, - "name1": df_lines["name1"], - "name2": df_lines["name2"], - }) + df_polaire = pd.DataFrame( + { + "x1": df_lines["x1"], + "y1": df_lines["y1"], + "x2": df_lines["x2"], + "y2": df_lines["y2"], + "azimut_deg": azimut, + "longueur": length, + "name1": df_lines["name1"], + "name2": df_lines["name2"], + "group_id": df_lines["group_id"], + "rank_in_group": df_lines["rank_in_group"], + } + ) + else: + df_polaire = pd.DataFrame( + { + "x1": df_lines["x1"], + "y1": df_lines["y1"], + "x2": df_lines["x2"], + "y2": df_lines["y2"], + "azimut_deg": azimut, + "longueur": length, + "name1": df_lines["name1"], + "name2": df_lines["name2"], + } + ) return df_polaire - except Exception as e: + except Exception as e: # noqa: BLE001 log.error(f"Issue in polar conversion: {Colors.ENDC}{e}") globalData.error_count += 1 return pd.DataFrame() @@ -264,7 +262,7 @@ def assign_groups_and_ranks(df_lines): # Si tous les nœuds ont un degré 2 : cycle fermé if not start_nodes: - start_nodes = [list(G.nodes)[0]] + start_nodes = [list(G.nodes)[0]] # noqa: RUF015 for node in start_nodes: for neighbor in G.neighbors(node): @@ -333,49 +331,47 @@ def wall_construction_smoothed(df_lines, df_splays, x_min, x_max, y_min, y_max): Returns: list: Une liste de murs construits. - """ + """ - th2_walls=[] + th2_walls = [] _list = "" - + # pd.set_option('display.max_rows', None) # pd.set_option('display.max_columns', None) # pd.set_option('display.width', None) # pd.set_option('display.max_colwidth', None) - # print(f"\n df_lines: {len(df_lines)} :\n{df_lines}") - # print(f"\n df_splays: {len(df_splays)} :\n{df_splays}") + # print(f"\n df_lines: {len(df_lines)} :\n{df_lines}") + # print(f"\n df_splays: {len(df_splays)} :\n{df_splays}") - if len(df_lines) <= 2 or len(df_splays) <= 2: return th2_walls, 0, 0, 0, 0 df_lines, df_equates = assign_groups_and_ranks(df_lines) - + # Conversion en polaire df_lines_polaire = convert_to_line_polaire_df(df_lines) df_splays_polaire = convert_to_line_polaire_df(df_splays) - + df_temp = df_lines_polaire.copy() - df_temp['rank_in_group_prev'] = df_temp['rank_in_group'] + 1 + df_temp["rank_in_group_prev"] = df_temp["rank_in_group"] + 1 # Fusionner pour récupérer l'azimut précédent df_lines_polaire = df_lines_polaire.merge( - df_temp[['group_id', 'rank_in_group_prev', 'azimut_deg']], - left_on=['group_id', 'rank_in_group'], - right_on=['group_id', 'rank_in_group_prev'], - how='left', - suffixes=('', '_prev') + df_temp[["group_id", "rank_in_group_prev", "azimut_deg"]], + left_on=["group_id", "rank_in_group"], + right_on=["group_id", "rank_in_group_prev"], + how="left", + suffixes=("", "_prev"), ) # Renommer et nettoyer - df_lines_polaire['azimut_prev_deg'] = df_lines_polaire['azimut_deg_prev'] - df_lines_polaire = df_lines_polaire.drop(['rank_in_group_prev', 'azimut_deg_prev'], axis=1) - df_lines_polaire['azimut_prev_deg'] = df_lines_polaire['azimut_prev_deg'].fillna(df_lines_polaire['azimut_deg']) - df_lines_polaire['bissectrice'] = (df_lines_polaire['azimut_deg'] + df_lines_polaire['azimut_prev_deg']) / 2 - - - # print(f"\n df_lines_polaire: {len(df_lines_polaire)} :\n{df_lines_polaire}") - # print(f"\n df_equates: {len(df_equates)} :\n{df_equates}") + df_lines_polaire["azimut_prev_deg"] = df_lines_polaire["azimut_deg_prev"] + df_lines_polaire = df_lines_polaire.drop(["rank_in_group_prev", "azimut_deg_prev"], axis=1) + df_lines_polaire["azimut_prev_deg"] = df_lines_polaire["azimut_prev_deg"].fillna(df_lines_polaire["azimut_deg"]) + df_lines_polaire["bissectrice"] = (df_lines_polaire["azimut_deg"] + df_lines_polaire["azimut_prev_deg"]) / 2 + + # print(f"\n df_lines_polaire: {len(df_lines_polaire)} :\n{df_lines_polaire}") + # print(f"\n df_equates: {len(df_equates)} :\n{df_equates}") # Index des lignes polaires par station name1 index_by_station = df_lines_polaire.set_index("name1")[["bissectrice", "longueur"]] @@ -383,239 +379,196 @@ def wall_construction_smoothed(df_lines, df_splays, x_min, x_max, y_min, y_max): # Jointure pour récupérer azimut_ref et longueur_ref _df_splays_complet = df_splays_polaire.copy() _df_splays_complet = _df_splays_complet.join(index_by_station, on="name1", rsuffix="_ref") - + # Remplacer les valeurs manquantes par défaut : azimut_ref = 0, longueur_ref = 0 _df_splays_complet["bissectrice"] = _df_splays_complet["bissectrice"].fillna(0) _df_splays_complet["longueur_ref"] = _df_splays_complet["longueur_ref"].fillna(0) - - df_splays_complet = _df_splays_complet.merge( - df_lines[["name1", "group_id", "rank_in_group"]], - on="name1", - how="left" - ) - + + df_splays_complet = _df_splays_complet.merge(df_lines[["name1", "group_id", "rank_in_group"]], on="name1", how="left") + missing_mask = df_splays_complet["group_id"].isna() - + for idx, row in df_splays_complet[missing_mask].iterrows(): name1 = row["name1"] match = df_lines_polaire[df_lines_polaire["name2"] == name1] - if not match.empty: + if not match.empty: group_id = match["group_id"].values[0] max_rank = df_lines_polaire[df_lines_polaire["group_id"] == group_id]["rank_in_group"].max() - + df_splays_complet.loc[idx, "bissectrice"] = match["azimut_deg"].values[0] df_splays_complet.loc[idx, "longueur_ref"] = match["longueur"].values[0] df_splays_complet.loc[idx, "group_id"] = group_id df_splays_complet.loc[idx, "rank_in_group"] = max_rank + 1 df_splays_complet = add_start_end_splays(df_splays_complet, df_equates) - + df_splays_complet = df_splays_complet.sort_values(by=["group_id", "rank_in_group"]).reset_index(drop=True) - + df_splays_complet["delta_azimut"] = df_splays_complet["bissectrice"] - df_splays_complet["azimut_deg"] df_splays_complet["proj"] = np.sin(np.radians(df_splays_complet["bissectrice"] - df_splays_complet["azimut_deg"])) * df_splays_complet["longueur"] df_splays_complet["group_id"] = df_splays_complet["group_id"].astype(int) df_splays_complet["rank_in_group"] = df_splays_complet["rank_in_group"].astype(int) - - # print(f"\n df_splays_complet: {len(df_splays_complet)} :\n{df_splays_complet}") + + # print(f"\n df_splays_complet: {len(df_splays_complet)} :\n{df_splays_complet}") # Filtrage des extrêmes min/max par station name1 df_valid_proj = df_splays_complet.dropna(subset=["proj"]) - - # print(f"\n df_splays_complet: {len(df_splays_complet)} :\n{df_splays_complet}") - + + # print(f"\n df_splays_complet: {len(df_splays_complet)} :\n{df_splays_complet}") + idx_max = df_valid_proj.groupby(["group_id", "rank_in_group"])["proj"].idxmax() - df_result01 = df_valid_proj.loc[idx_max].reset_index(drop=True) + df_result01 = df_valid_proj.loc[idx_max].reset_index(drop=True) # idx_max = df_valid_proj.groupby("name1")["proj"].idxmax() - df_result01 = pd.concat([df_valid_proj.loc[idx_max]]).drop_duplicates() + df_result01 = pd.concat([df_valid_proj.loc[idx_max]]).drop_duplicates() df_sorted01 = df_result01.sort_values(by=["group_id", "rank_in_group"]).reset_index(drop=True) - + idx_min = df_valid_proj.groupby(["group_id", "rank_in_group"])["proj"].idxmin() - df_result02 = df_valid_proj.loc[idx_min].reset_index(drop=True) + df_result02 = df_valid_proj.loc[idx_min].reset_index(drop=True) # idx_min = df_valid_proj.groupby("name1")["proj"].idxmin() - df_result02 = pd.concat([df_valid_proj.loc[idx_min]]).drop_duplicates() + df_result02 = pd.concat([df_valid_proj.loc[idx_min]]).drop_duplicates() df_sorted02 = df_result02.sort_values(by=["group_id", "rank_in_group"]).reset_index(drop=True) - + # Affichage de contrôle - # print(f"\n df_sorted01: {len(df_sorted01)} :\n{df_sorted01}") - # print(f"\n df_sorted02: {len(df_sorted02)} :\n{df_sorted02}") - # print(f"\n idx_min: {len(idx_min)} :\n{idx_min}") - + # print(f"\n df_sorted01: {len(df_sorted01)} :\n{df_sorted01}") + # print(f"\n df_sorted02: {len(df_sorted02)} :\n{df_sorted02}") + # print(f"\n idx_min: {len(idx_min)} :\n{idx_min}") + smooth02 = [] smooth01 = [] - + for gid in sorted(df_sorted01["group_id"].unique()): df_group = df_sorted02[df_sorted02["group_id"] == gid] - - # _list += f"line wall\n" - _linex2 = 0.0 + + # _list += f"line wall\n" + _linex2 = 0.0 _liney2 = 0.0 - + for line in df_group.itertuples(index=False): - X = line.x2 + (- line.x2 + _linex2) / 2 - Y = line.y2 + (- line.y2 + _liney2) / 2 - if _linex2 == 0.0 and _liney2 == 0.0: - row = { - 'smoothX1': None, - 'smoothY1': None, - 'smoothX2': None, - 'smoothY2': None, - 'X': line.x2, - 'Y': line.y2, - 'Jump': False, - } - else : - row = { - 'smoothX1': X, - 'smoothY1': Y, - 'smoothX2': X, - 'smoothY2': Y, - 'X': line.x2, - 'Y': line.y2, - 'Jump': False, - } - - _linex2 = line.x2 + X = line.x2 + (-line.x2 + _linex2) / 2 + Y = line.y2 + (-line.y2 + _liney2) / 2 + if _linex2 == 0.0 and _liney2 == 0.0: + row = {"smoothX1": None, "smoothY1": None, "smoothX2": None, "smoothY2": None, "X": line.x2, "Y": line.y2, "Jump": False} + else: + row = {"smoothX1": X, "smoothY1": Y, "smoothX2": X, "smoothY2": Y, "X": line.x2, "Y": line.y2, "Jump": False} + + _linex2 = line.x2 _liney2 = line.y2 smooth02.append(row) - if line.x2 > x_max: x_max = line.x2 - if line.x2 < x_min: x_min = line.x2 - if line.y2 > y_max: y_max = line.y2 - if line.y2 < y_min: y_min = line.y2 - row = { - 'smoothX1': None, - 'smoothY1': None, - 'smoothX2': None, - 'smoothY2': None, - 'X': None, - 'Jump': True, - } + if line.x2 > x_max: # noqa: PLR1730 + x_max = line.x2 + if line.x2 < x_min: # noqa: PLR1730 + x_min = line.x2 + if line.y2 > y_max: # noqa: PLR1730 + y_max = line.y2 + if line.y2 < y_min: # noqa: PLR1730 + y_min = line.y2 + row = {"smoothX1": None, "smoothY1": None, "smoothX2": None, "smoothY2": None, "X": None, "Jump": True} smooth02.append(row) - - _linex2 = 0.0 + + _linex2 = 0.0 _liney2 = 0.0 - + df_group = df_sorted01[df_sorted01["group_id"] == gid] - + for line in df_group.itertuples(index=False): - X = line.x2 + (- line.x2 + _linex2) / 2 - Y = line.y2 + (- line.y2 + _liney2) / 2 - if _linex2 == 0.0 and _liney2 == 0.0: - row = { - 'smoothX1': None, - 'smoothY1': None, - 'smoothX2': None, - 'smoothY2': None, - 'X': line.x2, - 'Y': line.y2, - 'Jump': False, - } - else : - row = { - 'smoothX1': X, - 'smoothY1': Y, - 'smoothX2': X, - 'smoothY2': Y, - 'X': line.x2, - 'Y': line.y2, - 'Jump': False, - } - - _linex2 = line.x2 + X = line.x2 + (-line.x2 + _linex2) / 2 + Y = line.y2 + (-line.y2 + _liney2) / 2 + if _linex2 == 0.0 and _liney2 == 0.0: + row = {"smoothX1": None, "smoothY1": None, "smoothX2": None, "smoothY2": None, "X": line.x2, "Y": line.y2, "Jump": False} + else: + row = {"smoothX1": X, "smoothY1": Y, "smoothX2": X, "smoothY2": Y, "X": line.x2, "Y": line.y2, "Jump": False} + + _linex2 = line.x2 _liney2 = line.y2 smooth01.append(row) - if line.x2 > x_max: x_max = line.x2 - if line.x2 < x_min: x_min = line.x2 - if line.y2 > y_max: y_max = line.y2 - if line.y2 < y_min: y_min = line.y2 - - row = { - 'smoothX1': None, - 'smoothY1': None, - 'smoothX2': None, - 'smoothY2': None, - 'X': None, - 'Jump': True, - } + if line.x2 > x_max: # noqa: PLR1730 + x_max = line.x2 + if line.x2 < x_min: # noqa: PLR1730 + x_min = line.x2 + if line.y2 > y_max: # noqa: PLR1730 + y_max = line.y2 + if line.y2 < y_min: # noqa: PLR1730 + y_min = line.y2 + + row = {"smoothX1": None, "smoothY1": None, "smoothX2": None, "smoothY2": None, "X": None, "Jump": True} smooth01.append(row) - + df_smooth01 = pd.DataFrame(smooth01) df_smooth02 = pd.DataFrame(smooth02) - - # print(f"\n df_sorted01: {len(df_sorted01)} :\n{df_sorted01}") - # print(f"\n df_smooth01: {len(df_smooth01)} :\n{df_smooth01}") - + + # print(f"\n df_sorted01: {len(df_sorted01)} :\n{df_sorted01}") + # print(f"\n df_smooth01: {len(df_smooth01)} :\n{df_smooth01}") + if len(df_smooth01) > 1: _list = "line wall -reverse on\n" - + for i in range(len(df_smooth01) - 1): row_current = df_smooth01.iloc[i] row_next = df_smooth01.iloc[i + 1] - - if row_current['Jump'] == True : - _list +="\tsmooth off\nendline\n\nline wall -reverse on\n" + + if row_current["Jump"] == True: + _list += "\tsmooth off\nendline\n\nline wall -reverse on\n" continue - if pd.isna(row_current[['smoothX2', 'smoothY2', 'X', 'Y']]).any() or pd.isna(row_next[['smoothX1', 'smoothY1']]).any(): + if pd.isna(row_current[["smoothX2", "smoothY2", "X", "Y"]]).any() or pd.isna(row_next[["smoothX1", "smoothY1"]]).any(): _list += f"\t{row_current['X']} {row_current['Y']}\n" continue - result = align_points( - smoothX1=row_next['smoothX1'], - smoothY1=row_next['smoothY1'], - X=row_current['X'], - Y=row_current['Y'], - smoothX2=row_current['smoothX2'], - smoothY2=row_current['smoothY2'] + result = align_points( + smoothX1=row_next["smoothX1"], + smoothY1=row_next["smoothY1"], + X=row_current["X"], + Y=row_current["Y"], + smoothX2=row_current["smoothX2"], + smoothY2=row_current["smoothY2"], ) if result: (_sx1, _sy1), (_sx2, _sy2) = result - df_smooth01.at[i+1, 'smoothX1'] = _sx2 - df_smooth01.at[i+1, 'smoothY1'] = _sy2 - df_smooth01.at[i, 'smoothX2'] = _sx1 - df_smooth01.at[i, 'smoothY2'] = _sy1 - + df_smooth01.at[i + 1, "smoothX1"] = _sx2 + df_smooth01.at[i + 1, "smoothY1"] = _sy2 + df_smooth01.at[i, "smoothX2"] = _sx1 + df_smooth01.at[i, "smoothY2"] = _sy1 + _list += f"\t{row_current['smoothX1']:.2f} {row_current['smoothY1']:.2f} {row_current['smoothX2']:.2f} {row_current['smoothY2']:.2f} {row_current['X']} {row_current['Y']}\n" - + _list += "\tsmooth off\nendline\n\nline wall\n" - - + for i in range(len(df_smooth02) - 1): row_current = df_smooth02.iloc[i] row_next = df_smooth02.iloc[i + 1] # Vérifie qu'aucune valeur utilisée n'est NaN - if row_current['Jump'] == True : - _list +="\tsmooth off\nendline\n\nline wall\n" + if row_current["Jump"] == True: + _list += "\tsmooth off\nendline\n\nline wall\n" continue - if pd.isna(row_current[['smoothX2', 'smoothY2', 'X', 'Y']]).any() or pd.isna(row_next[['smoothX1', 'smoothY1']]).any(): + if pd.isna(row_current[["smoothX2", "smoothY2", "X", "Y"]]).any() or pd.isna(row_next[["smoothX1", "smoothY1"]]).any(): _list += f"\t{row_current['X']} {row_current['Y']}\n" continue - result = align_points( - smoothX1=row_next['smoothX1'], - smoothY1=row_next['smoothY1'], - X=row_current['X'], - Y=row_current['Y'], - smoothX2=row_current['smoothX2'], - smoothY2=row_current['smoothY2'] + result = align_points( + smoothX1=row_next["smoothX1"], + smoothY1=row_next["smoothY1"], + X=row_current["X"], + Y=row_current["Y"], + smoothX2=row_current["smoothX2"], + smoothY2=row_current["smoothY2"], ) if result: (_sx1, _sy1), (_sx2, _sy2) = result - df_smooth02.at[i+1, 'smoothX1'] = _sx2 - df_smooth02.at[i+1, 'smoothY1'] = _sy2 - df_smooth02.at[i, 'smoothX2'] = _sx1 - df_smooth02.at[i, 'smoothY2'] = _sy1 - + df_smooth02.at[i + 1, "smoothX1"] = _sx2 + df_smooth02.at[i + 1, "smoothY1"] = _sy2 + df_smooth02.at[i, "smoothX2"] = _sx1 + df_smooth02.at[i, "smoothY2"] = _sy1 + _list += f"\t{row_current['smoothX1']:.2f} {row_current['smoothY1']:.2f} {row_current['smoothX2']:.2f} {row_current['smoothY2']:.2f} {row_current['X']} {row_current['Y']}\n" - + _list += "\tsmooth off\nendline\n" - - th2_walls.append(globalData.th2wall.format(list = _list)) - + + th2_walls.append(globalData.th2wall.format(list=_list)) + return th2_walls, x_min, x_max, y_min, y_max @@ -657,7 +610,7 @@ def parse_xvi_file(thNameXvi): y_min, y_max = min(yValues), max(yValues) x_ecart = x_max - x_min y_ecart = y_max - y_min - + for line in xviShots.split("\n"): match = re.search(r"^\s*{\s*(-?\d+\.\d+)\s+(-?\d+\.\d+)\s+(-?\d+\.\d+)\s+(-?\d+\.\d+)(.*)}", line) if match: @@ -676,11 +629,11 @@ def parse_xvi_file(thNameXvi): # Vérifie s'il y a au moins 8 autres champs pour les splays additional_coords = re.findall(r"-?\d+\.\d+", rest) if len(additional_coords) >= 8: - splays.append([x1, y1, additional_coords[0], additional_coords[1], station1, "-"]) - # splays.append([x2, y2, additional_coords[2], additional_coords[3], station2, "-"]) - # splays.append([x2, y2, additional_coords[4], additional_coords[5], station2, "-"]) - splays.append([x1, y1, additional_coords[6], additional_coords[7], station1, "-"]) - + splays.append([x1, y1, additional_coords[0], additional_coords[1], station1, "-"]) + # splays.append([x2, y2, additional_coords[2], additional_coords[3], station2, "-"]) + # splays.append([x2, y2, additional_coords[4], additional_coords[5], station2, "-"]) + splays.append([x1, y1, additional_coords[6], additional_coords[7], station1, "-"]) + return stations, lines, splays, x_min, x_max, y_min, y_max, x_ecart, y_ecart @@ -693,57 +646,47 @@ def parse_therion_surveys(file_path): Returns: list: Une liste des noms des surveys trouvés dans le fichier. - """ + """ survey_names = [] - + try: - file, val, encodage = load_text_file_utf8(file_path, os.path.basename(file_path)) + file, val, encodage = load_text_file_utf8(file_path, os.path.basename(file_path)) # noqa: RUF059 # lines = file.readlines() lines = file.splitlines() # with open(filepath, 'r', encoding=enc) as f: # content = f.read() - + for line in lines: # Look for lines starting with survey line = line.strip() - if line.startswith('survey ') and ' -title ' in line: + if line.startswith("survey ") and " -title " in line: # Split the line and extract the survey name - start_index = line.find('survey ') + len('survey ') - end_index = line.find(' -title ') + start_index = line.find("survey ") + len("survey ") + end_index = line.find(" -title ") survey_name = line[start_index:end_index].strip() survey_names.append(survey_name) - + except FileNotFoundError: log.error(f"File {Colors.ENDC}{safe_relpath(file_path)}{Colors.ERROR} not found.{Colors.ENDC}") globalData.error_count += 1 - + except PermissionError: log.error(f"Insufficient permissions to read {Colors.ENDC}{safe_relpath(file_path)}") globalData.error_count += 1 - - except Exception as e: + + except Exception as e: # noqa: BLE001 log.error(f"An error occurred (parse_therion_surveys): {Colors.ENDC}{e}{Colors.ERROR}, file: {Colors.ENDC}{safe_relpath(file_path)}") globalData.error_count += 1 - + return survey_names -################################################################################################# +################################################################################################# # Création des fichiers et dossiers à partir d'un th file # -################################################################################################# -def create_th_folders(ENTRY_FILE, - PROJECTION = "all", - TARGET = "None", - FORMAT = "th2", - SCALE = "500", - UPDATE = False, - CONFIG_PATH = "", - totReadMeError = "", - args_file = "", - proj = "", ) : - +################################################################################################# +def create_th_folders(ENTRY_FILE, PROJECTION="all", TARGET="None", FORMAT="th2", SCALE="500", UPDATE=False, CONFIG_PATH="", totReadMeError="", args_file="", proj=""): """Création des dossiers et fichiers à partir d'un fichier .th - + Args: ENTRY_FILE (str): Chemin du fichier Therion d'entrée. PROJECTION (str): Type de projection à utiliser. @@ -753,224 +696,210 @@ def create_th_folders(ENTRY_FILE, UPDATE (bool): Indique si l'on met à jour les fichiers existants. CONFIG_PATH (str): Chemin vers le fichier de configuration Therion. totReadMeError (str): Message d'erreur pour le fichier README. - + Returns: bool: True si la création des dossiers et fichiers a réussi, False sinon. """ - + threads = [] totReadMe = "" TH_NAME = sanitize_filename(os.path.splitext(os.path.basename(ENTRY_FILE))[0]) DEST_PATH = os.path.dirname(ENTRY_FILE) + "/" + TH_NAME ABS_PATH = os.path.dirname(ENTRY_FILE) shortCurentFile = safe_relpath(ENTRY_FILE) - - log.debug(f"ENTRY_FILE: {ENTRY_FILE}") - log.debug(f"PROJECTION: {PROJECTION}") - log.debug(f"TARGET: {TARGET}") - log.debug(f"FORMAT: {FORMAT}") + + log.debug(f"ENTRY_FILE: {ENTRY_FILE}") + log.debug(f"PROJECTION: {PROJECTION}") + log.debug(f"TARGET: {TARGET}") + log.debug(f"FORMAT: {FORMAT}") log.debug(f"SCALE: {SCALE}") log.debug(f"TH_NAME: {TH_NAME}") log.debug(f"DEST_PATH: {DEST_PATH}") - log.debug(f"ABS_PATH: {ABS_PATH}") - + log.debug(f"ABS_PATH: {ABS_PATH}") + # if PROJECTION.lower() != "plan" and PROJECTION.lower() != "extended" and PROJECTION.lower() != "all": # log.critical(f"Sorry, projection '{Colors.ENDC}{PROJECTION}{Colors.ERROR}' not yet implemented{Colors.ENDC}") # # exit(1) - + if not os.path.isfile(ENTRY_FILE): log.critical(f"The Therion file didn't exist: {Colors.ENDC}{shortCurentFile}") - exit(1) + sys.exit(1) if FORMAT not in ["th2", "plt"]: log.critical(f"Please choose a supported format: th2, plt{Colors.ENDC}") - exit(1) + sys.exit(1) # Normalise name, namespace, key, file path log.info(f"Parsing therion survey entry file: {Colors.ENDC}{shortCurentFile}") survey_list = parse_therion_surveys(ENTRY_FILE) - - if TARGET == "None" : - if len(survey_list) > 1 : + + if TARGET == "None": # noqa: SIM102 + if len(survey_list) > 1: log.critical(f"Multiple surveys were found, not yet implemented{Colors.ENDC}") - exit(1) - + sys.exit(1) + TARGET = survey_list[0] - - log.info(f"Parsing therion survey target: {Colors.ENDC}{TARGET}") - + + log.info(f"Parsing therion survey target: {Colors.ENDC}{TARGET}") + loader = SurveyLoader(ENTRY_FILE) survey = loader.get_survey_by_id(survey_list[0]) - + if not survey: - raise NoSurveysFoundException(f"No survey found with that selector") - - if UPDATE : + raise NoSurveysFoundException("No survey found with that selector") + + if UPDATE: DEST_PATH = os.path.dirname(args_file) log.info(f"Update th2 files: {Colors.ENDC}{DEST_PATH}") log.debug(f"\t{Colors.BLUE}survey_file : {Colors.ENDC} {args_file}") - log.debug(f"\t{Colors.BLUE}ENTRY_FILE: {Colors.ENDC} {ENTRY_FILE}") - log.debug(f"\t{Colors.BLUE}PROJECTION: {Colors.ENDC} {PROJECTION}") - log.debug(f"\t{Colors.BLUE}TARGET: {Colors.ENDC} {TARGET}") - # log.info(f"\t{Colors.BLUE}OUTPUT: {Colors.ENDC} {OUTPUT}") - log.debug(f"\t{Colors.BLUE}FORMAT: {Colors.ENDC} {FORMAT}") + log.debug(f"\t{Colors.BLUE}ENTRY_FILE: {Colors.ENDC} {ENTRY_FILE}") + log.debug(f"\t{Colors.BLUE}PROJECTION: {Colors.ENDC} {PROJECTION}") + log.debug(f"\t{Colors.BLUE}TARGET: {Colors.ENDC} {TARGET}") + # log.info(f"\t{Colors.BLUE}OUTPUT: {Colors.ENDC} {OUTPUT}") + log.debug(f"\t{Colors.BLUE}FORMAT: {Colors.ENDC} {FORMAT}") log.debug(f"\t{Colors.BLUE}SCALE: {Colors.ENDC} {SCALE}") log.debug(f"\t{Colors.BLUE}TH_NAME: {Colors.ENDC} {TH_NAME}") log.debug(f"\t{Colors.BLUE}DEST_PATH: {Colors.ENDC} {DEST_PATH}") log.debug(f"\t{Colors.BLUE}ABS_PATH: {Colors.ENDC} {ABS_PATH}") - - ################################################################################################# + + ################################################################################################# # Copy template folders # ################################################################################################# - if not UPDATE: - log.debug(f"Copy template folder and adapte it") + if not UPDATE: + log.debug("Copy template folder and adapte it") copy_template_if_not_exists(globalData.templatePath, DEST_PATH) copy_file_with_copyright(ENTRY_FILE, DEST_PATH + "/Data", globalData.Copyright) - - - ################################################################################################# + + ################################################################################################# # Produce the parsable XVI file # - ################################################################################################# + ################################################################################################# log.info(f"Compiling 2D XVI file: {Colors.ENDC}{TH_NAME}") - - if UPDATE: + + if UPDATE: thFile = Path(DEST_PATH + "\\" + TH_NAME + ".th") thName = Path(DEST_PATH + "\\" + TH_NAME) - else : - thFile = Path(DEST_PATH + "\\Data\\" + TH_NAME + ".th") - thName = Path(DEST_PATH + "\\Data\\" + TH_NAME) + else: + thFile = Path(DEST_PATH + "\\Data\\" + TH_NAME + ".th") + thName = Path(DEST_PATH + "\\Data\\" + TH_NAME) - template_args = { - "th_file": thFile, - "selector": survey.therion_id, - "th_name": thName, - "XVIscale": globalData.XVIScale, - } + template_args = {"th_file": thFile, "selector": survey.therion_id, "th_name": thName, "XVIscale": globalData.XVIScale} logfile, tmpdir, totReadMeError = compile_template(globalData.thconfigTemplate, template_args, totReadMeError, cleanup=False, therion_path=globalData.therionPath) - - shutil.rmtree(tmpdir) - - if totReadMeError == "" : totReadMeError += f"\tNo errors found in {os.path.basename(thFile)}, perfect!\n" - + + shutil.rmtree(tmpdir) + + if totReadMeError == "": + totReadMeError += f"\tNo errors found in {os.path.basename(thFile)}, perfect!\n" + if logfile == "Therion error": - # log.error(f"Therion error in: {Colors.ENDC}{TH_NAME}") + # log.error(f"Therion error in: {Colors.ENDC}{TH_NAME}") flagErrorCompile = True stat = {"length": 0, "depth": 0} - log.info(f"File: {Colors.ENDC}{os.path.basename(thFile)}{Colors.INFO}, compilation error, length: {Colors.ENDC}{stat["length"]}m{Colors.INFO}, depth: {Colors.ENDC}{stat["depth"]}m") - totReadMe = f"\t{os.path.basename(thFile)} compilation error length: {stat["length"]} m, depth: {stat["depth"]} m\n" - - else : + log.info( + f"File: {Colors.ENDC}{os.path.basename(thFile)}{Colors.INFO}, compilation error, length: {Colors.ENDC}{stat['length']}m{Colors.INFO}, depth: {Colors.ENDC}{stat['depth']}m" + ) + totReadMe = f"\t{os.path.basename(thFile)} compilation error length: {stat['length']} m, depth: {stat['depth']} m\n" + + else: flagErrorCompile = False stat = get_stats_from_log(logfile) - log.info(f"File: {Colors.ENDC}{os.path.basename(thFile)}{Colors.INFO}, compilation successful, length: {Colors.ENDC}{stat["length"]}m{Colors.INFO}, depth: {Colors.ENDC}{stat["depth"]}m") - totReadMe = f"\t{os.path.basename(thFile)} compilation successful length: {stat["length"]} m, depth: {stat["depth"]} m\n" - - - ################################################################################################# + log.info( + f"File: {Colors.ENDC}{os.path.basename(thFile)}{Colors.INFO}, compilation successful, length: {Colors.ENDC}{stat['length']}m{Colors.INFO}, depth: {Colors.ENDC}{stat['depth']}m" + ) + totReadMe = f"\t{os.path.basename(thFile)} compilation successful length: {stat['length']} m, depth: {stat['depth']} m\n" + + ################################################################################################# # Update files # ################################################################################################# - if not UPDATE: - + if not UPDATE: # proj = args.proj.lower() - values = { - "none": ("# ", "# ", "# "), - "plan": ("", "", "# "), - "extended": ("", "# ", ""), - } + values = {"none": ("# ", "# ", "# "), "plan": ("", "", "# "), "extended": ("", "# ", "")} maps, plan, extended = values.get(proj, ("", "", "")) - - totdata = globalData.totfile.format( - TH_NAME = TH_NAME, - ERR = "# " if flagErrorCompile else "", - Plan = plan, - Extended = extended, - Maps = maps) - - # Adapte templates + + totdata = globalData.totfile.format(TH_NAME=TH_NAME, ERR="# " if flagErrorCompile else "", Plan=plan, Extended=extended, Maps=maps) + + # Adapte templates config_vars = { - 'fileName': TH_NAME, - 'caveName': TH_NAME.replace("_", " "), - 'Author': globalData.Author, - 'Copyright': globalData.Copyright, - 'Scale' : SCALE, - 'Target' : TARGET, - 'mapComment' : globalData.mapComment, - 'club' : globalData.club, - 'thanksto' : globalData.thanksto.replace("_", r"\_"), - 'datat' : globalData.datat.replace("_", r"\_"), - 'wpage' : globalData.wpage.replace("_", r"\_"), - 'cs' : globalData.cs, - 'configPath' : CONFIG_PATH, - 'totData' : totdata, - 'maps' : maps, - 'plan': plan, - 'XVIscale' : globalData.XVIScale, - 'extended' : extended, - 'XVIscale' : globalData.XVIScale, - 'readMeList': str(totReadMe), - 'errorList' : str(totReadMeError), - 'fixPointList' : str(" "), - 'other_scraps_plan' : "", - 'file_info' : f'# File generated by pyCreateTh.py version: {globalData.Version} date: {datetime.now().strftime("%Y.%m.%d %H:%M:%S")}', + "fileName": TH_NAME, + "caveName": TH_NAME.replace("_", " "), + "Author": globalData.Author, + "Copyright": globalData.Copyright, + "Scale": SCALE, + "Target": TARGET, + "mapComment": globalData.mapComment, + "club": globalData.club, + "thanksto": globalData.thanksto.replace("_", r"\_"), + "datat": globalData.datat.replace("_", r"\_"), + "wpage": globalData.wpage.replace("_", r"\_"), + "cs": globalData.cs, + "configPath": CONFIG_PATH, + "totData": totdata, + "maps": maps, + "plan": plan, + "XVIscale": globalData.XVIScale, + "extended": extended, + "XVIscale": globalData.XVIScale, # noqa: F601 + "readMeList": str(totReadMe), + "errorList": str(totReadMeError), + "fixPointList": str(" "), # noqa: UP018 + "other_scraps_plan": "", + "file_info": f"# File generated by pyCreateTh.py version: {globalData.Version} date: {datetime.now().strftime('%Y.%m.%d %H:%M:%S')}", # noqa: DTZ005 } - - update_template_files(DEST_PATH + '/template.thconfig', config_vars, DEST_PATH + '/' + TH_NAME + '.thconfig') - update_template_files(DEST_PATH + '/template-tot.th', config_vars, DEST_PATH + '/' + TH_NAME + '-tot.th') - update_template_files(DEST_PATH + '/template-readme.md', config_vars, DEST_PATH + '/' + TH_NAME + '-readme.md') - - ################################################################################################# + + update_template_files(DEST_PATH + "/template.thconfig", config_vars, DEST_PATH + "/" + TH_NAME + ".thconfig") + update_template_files(DEST_PATH + "/template-tot.th", config_vars, DEST_PATH + "/" + TH_NAME + "-tot.th") + update_template_files(DEST_PATH + "/template-readme.md", config_vars, DEST_PATH + "/" + TH_NAME + "-readme.md") + + ################################################################################################# # Parse the Plan XVI file # ################################################################################################# other_scraps_plan = "" - if PROJECTION.lower() == "plan" or PROJECTION.lower() == "all" and not flagErrorCompile : - if UPDATE: - thNameXvi = DEST_PATH + "/" + TH_NAME + "-Plan.xvi" - else : - thNameXvi = DEST_PATH + "/Data/" + TH_NAME + "-Plan.xvi" + if PROJECTION.lower() == "plan" or PROJECTION.lower() == "all" and not flagErrorCompile: + if UPDATE: + thNameXvi = DEST_PATH + "/" + TH_NAME + "-Plan.xvi" + else: + thNameXvi = DEST_PATH + "/Data/" + TH_NAME + "-Plan.xvi" log.info(f"Parsing Plan XVI file: {Colors.ENDC}{safe_relpath(thNameXvi)}") stations = {} lines = [] - + stations, lines, splays, x_min, x_max, y_min, y_max, x_ecart, y_ecart = parse_xvi_file(thNameXvi) - + # df_stations = pd.DataFrame.from_dict(stations, orient='index') df_lines = pd.DataFrame(lines, columns=["x1", "y1", "x2", "y2", "name1", "name2"]) df_splays = pd.DataFrame(splays, columns=["x1", "y1", "x2", "y2", "name1", "name2"]).drop_duplicates() - + df_splays["is_zero_length"] = (df_splays["x1"] == df_splays["x2"]) & (df_splays["y1"] == df_splays["y2"]) - # Identifier les groupes avec au moins un splay non nul non_zero_groups = df_splays.loc[~df_splays["is_zero_length"], ["name1", "name2"]] - non_zero_group_keys = set(tuple(x) for x in non_zero_groups.to_numpy()) - - df_splays = df_splays[(~df_splays["is_zero_length"]) | df_splays[["name1", "name2"]].apply(tuple, axis=1).isin(non_zero_group_keys) ] + non_zero_group_keys = set(tuple(x) for x in non_zero_groups.to_numpy()) # noqa: C401 + + df_splays = df_splays[(~df_splays["is_zero_length"]) | df_splays[["name1", "name2"]].apply(tuple, axis=1).isin(non_zero_group_keys)] # Supprimer la colonne temporaire si elle existe if "is_zero_length" in df_splays.columns: df_splays = df_splays.drop(columns="is_zero_length") - + th2_walls = [] - if globalData.wallLinesInTh2 : - th2_walls, x_min, x_max, y_min, y_max = wall_construction_smoothed(df_lines, df_splays, x_min, x_max, y_min, y_max) - - - if UPDATE: + if globalData.wallLinesInTh2: + th2_walls, x_min, x_max, y_min, y_max = wall_construction_smoothed(df_lines, df_splays, x_min, x_max, y_min, y_max) + + if UPDATE: th2_name = DEST_PATH + "/" + TH_NAME - else : + else: th2_name = DEST_PATH + "/Data/" + TH_NAME - - output_path = f'{th2_name}-Plan.{FORMAT}' - - scrap_to_add = int(len(stations)/globalData.stationByScrap)-1 + + output_path = f"{th2_name}-Plan.{FORMAT}" + + scrap_to_add = int(len(stations) / globalData.stationByScrap) - 1 # log.debug(stations) @@ -983,37 +912,37 @@ def create_th_folders(ENTRY_FILE, th2_points = [] th2_names = [] other_scraps_plan = f"\tSP-{TARGET}_01\n\tbreak\n" - + for line in lines: th2_lines.append(globalData.th2Line.format(x1=line[0], y1=line[1], x2=line[2], y2=line[3])) - coords1 = "{}.{}".format(line[0], line[1]) - + coords1 = "{}.{}".format(line[0], line[1]) # noqa: UP032 + if coords1 not in seen: seen.add(coords1) th2_points.append(globalData.th2Point.format(x=line[0], y=line[1], station=line[4])) th2_names.append(globalData.th2Name.format(x=line[0], y=line[1], station=line[4])) - coords2 = "{}.{}".format(line[2], line[3]) - - if "{}.{}".format(line[2], line[3]) not in seen: + coords2 = "{}.{}".format(line[2], line[3]) # noqa: UP032 + + if "{}.{}".format(line[2], line[3]) not in seen: # noqa: UP032 seen.add(coords2) if line[5] != None: th2_points.append(globalData.th2Point.format(x=line[2], y=line[3], station=line[5])) th2_names.append(globalData.th2Name.format(x=line[2], y=line[3], station=line[5])) - if isfile(output_path): log.warning(f"{Colors.ENDC}{os.path.basename(output_path)}{Colors.WARNING} file already exists - overwrite") - if True : - # name = TARGET, + if True: + # name = TARGET, log.debug(f"Therion output path: {Colors.ENDC}{safe_relpath(output_path)}") with open(str(output_path), "w+") as f: f.write(globalData.th2FileHeader) - f.write(globalData.th2File.format( - name = TARGET, - Copyright = globalData.Copyright, - Copyright_Short = globalData.CopyrightShort, + f.write( + globalData.th2File.format( + name=TARGET, + Copyright=globalData.Copyright, + Copyright_Short=globalData.CopyrightShort, points="\n".join(th2_points), lines="\n".join(th2_lines) if globalData.linesInTh2 else "", walls="\n".join(th2_walls) if globalData.wallLinesInTh2 else "", @@ -1021,53 +950,58 @@ def create_th_folders(ENTRY_FILE, projection="plan", projection_short="P", author=globalData.Author, - year=datetime.now().year, - version = globalData.Version, - date=datetime.now().strftime("%Y.%m.%d-%H:%M:%S"), - X_Min=x_min*1.2, - X_Max=x_max*1.2, - Y_Min=y_min*1.2, - Y_Max=y_max*1.2, - X_Max_X_Min =x_ecart, - Y_Max_Y_Min =y_ecart, - insert_XVI = "{" + stations[next(iter(stations))][0] + "1 1.0} {" - + stations[next(iter(stations))][1] + " " - + stations[next(iter(stations))][2] +"} " - + os.path.basename(thNameXvi) + " 0 {}", - ) + year=datetime.now().year, # noqa: DTZ005 + version=globalData.Version, + date=datetime.now().strftime("%Y.%m.%d-%H:%M:%S"), # noqa: DTZ005 + X_Min=x_min * 1.2, + X_Max=x_max * 1.2, + Y_Min=y_min * 1.2, + Y_Max=y_max * 1.2, + X_Max_X_Min=x_ecart, + Y_Max_Y_Min=y_ecart, + insert_XVI="{" + + stations[next(iter(stations))][0] + + "1 1.0} {" + + stations[next(iter(stations))][1] + + " " + + stations[next(iter(stations))][2] + + "} " + + os.path.basename(thNameXvi) + + " 0 {}", + ) ) - if scrap_to_add >= 1 : - for i in range(scrap_to_add): - f.write(globalData.th2Scrap.format( - name=TARGET, - projection="plan", - projection_short="P", - author=globalData.Author, - year=datetime.now().year, - Copyright_Short = globalData.CopyrightShort, - num=f"{i+2:02}", + if scrap_to_add >= 1: + for i in range(scrap_to_add): # noqa: FURB122 + f.write( + globalData.th2Scrap.format( + name=TARGET, + projection="plan", + projection_short="P", + author=globalData.Author, + year=datetime.now().year, # noqa: DTZ005 + Copyright_Short=globalData.CopyrightShort, + num=f"{i + 2:02}", ) ) - - ################################################################################################# + ################################################################################################# # Parse the Extended XVI file # ################################################################################################# other_scraps_extended = "" - if PROJECTION.lower() == "extended" or PROJECTION.lower() == "all" and not flagErrorCompile : - if UPDATE: - thNameXvi = DEST_PATH + "/" + TH_NAME + "-Extended.xvi" - else : - thNameXvi = DEST_PATH + "/Data/" + TH_NAME + "-Extended.xvi" + if PROJECTION.lower() == "extended" or PROJECTION.lower() == "all" and not flagErrorCompile: + if UPDATE: + thNameXvi = DEST_PATH + "/" + TH_NAME + "-Extended.xvi" + else: + thNameXvi = DEST_PATH + "/Data/" + TH_NAME + "-Extended.xvi" log.info(f"Parsing extended XVI file: {Colors.ENDC}{safe_relpath(thNameXvi)}") # Parse the Extended XVI file stations = {} lines = [] - + stations, lines, splays, x_min, x_max, y_min, y_max, x_ecart, y_ecart = parse_xvi_file(thNameXvi) - + # df_stations = pd.DataFrame.from_dict(stations, orient='index') df_lines = pd.DataFrame(lines, columns=["x1", "y1", "x2", "y2", "name1", "name2"]) df_splays = pd.DataFrame(splays, columns=["x1", "y1", "x2", "y2", "name1", "name2"]).drop_duplicates() @@ -1076,71 +1010,68 @@ def create_th_folders(ENTRY_FILE, # Identifier les groupes avec au moins un splay non nul non_zero_groups = df_splays.loc[~df_splays["is_zero_length"], ["name1", "name2"]] - non_zero_group_keys = set(tuple(x) for x in non_zero_groups.to_numpy()) - - df_splays = df_splays[(~df_splays["is_zero_length"]) | df_splays[["name1", "name2"]].apply(tuple, axis=1).isin(non_zero_group_keys) ] + non_zero_group_keys = set(tuple(x) for x in non_zero_groups.to_numpy()) # noqa: C401 + df_splays = df_splays[(~df_splays["is_zero_length"]) | df_splays[["name1", "name2"]].apply(tuple, axis=1).isin(non_zero_group_keys)] # Supprimer la colonne temporaire si elle existe if "is_zero_length" in df_splays.columns: df_splays = df_splays.drop(columns="is_zero_length") - + th2_walls = [] - - if globalData.wallLinesInTh2 : - th2_walls, x_min, x_max, y_min, y_max, = wall_construction_smoothed(df_lines, df_splays, x_min, x_max, y_min, y_max) - + + if globalData.wallLinesInTh2: + th2_walls, x_min, x_max, y_min, y_max = wall_construction_smoothed(df_lines, df_splays, x_min, x_max, y_min, y_max) if UPDATE: th2_name = DEST_PATH + "/" + TH_NAME - else : + else: th2_name = DEST_PATH + "/Data/" + TH_NAME - - output_path = f'{th2_name}-Extended.{FORMAT}' - scrap_to_add = int(len(stations)/globalData.stationByScrap)-1 - + output_path = f"{th2_name}-Extended.{FORMAT}" + + scrap_to_add = int(len(stations) / globalData.stationByScrap) - 1 + log.info(f"Writing output to: {Colors.ENDC}{safe_relpath(output_path)}") # Write TH2 if FORMAT == "th2": - seen = set() th2_lines = [] th2_points = [] th2_names = [] - + other_scraps_extended = f"\tSC-{TARGET}_01\n\tbreak\n" - + for line in lines: th2_lines.append(globalData.th2Line.format(x1=line[0], y1=line[1], x2=line[2], y2=line[3])) - coords1 = "{}.{}".format(line[0], line[1]) - + coords1 = "{}.{}".format(line[0], line[1]) # noqa: UP032 + if coords1 not in seen: seen.add(coords1) th2_points.append(globalData.th2Point.format(x=line[0], y=line[1], station=line[4])) th2_names.append(globalData.th2Name.format(x=line[0], y=line[1], station=line[4])) - coords2 = "{}.{}".format(line[2], line[3]) - - if "{}.{}".format(line[2], line[3]) not in seen: + coords2 = "{}.{}".format(line[2], line[3]) # noqa: UP032 + + if "{}.{}".format(line[2], line[3]) not in seen: # noqa: UP032 seen.add(coords2) if line[5] != None: th2_points.append(globalData.th2Point.format(x=line[2], y=line[3], station=line[5])) th2_names.append(globalData.th2Name.format(x=line[2], y=line[3], station=line[5])) - if isfile(output_path): log.warning(f"{Colors.ENDC}{os.path.basename(output_path)}{Colors.WARNING} file already exists - overwrite") - - if True : + + if True: log.debug(f"Therion output path :\t{Colors.ENDC}{output_path}") - + with open(str(output_path), "w+") as f: f.write(globalData.th2FileHeader) - f.write(globalData.th2File.format( - name = TARGET, - Copyright = globalData.Copyright, - Copyright_Short = globalData.CopyrightShort, + f.write( + globalData.th2File.format( + name=TARGET, + Copyright=globalData.Copyright, + Copyright_Short=globalData.CopyrightShort, points="\n".join(th2_points), lines="\n".join(th2_lines) if globalData.linesInTh2 else "", walls="\n".join(th2_walls) if globalData.wallLinesInTh2 else "", @@ -1148,77 +1079,78 @@ def create_th_folders(ENTRY_FILE, projection="extended", projection_short="C", author=globalData.Author, - year=datetime.now().year, - version = globalData.Version, - date=datetime.now().strftime("%Y.%m.%d-%H:%M:%S"), - X_Min=x_min*1.2, - X_Max=x_max*1.2, - Y_Min=y_min*1.2, - Y_Max=y_max*1.2, - X_Max_X_Min =x_ecart, - Y_Max_Y_Min =y_ecart, - insert_XVI = "{" + stations[next(iter(stations))][0] + "1 1.0} {" - + stations[next(iter(stations))][1] + " " - + stations[next(iter(stations))][2] +"} " - + os.path.basename(thNameXvi) + " 0 {}", + year=datetime.now().year, # noqa: DTZ005 + version=globalData.Version, + date=datetime.now().strftime("%Y.%m.%d-%H:%M:%S"), # noqa: DTZ005 + X_Min=x_min * 1.2, + X_Max=x_max * 1.2, + Y_Min=y_min * 1.2, + Y_Max=y_max * 1.2, + X_Max_X_Min=x_ecart, + Y_Max_Y_Min=y_ecart, + insert_XVI="{" + + stations[next(iter(stations))][0] + + "1 1.0} {" + + stations[next(iter(stations))][1] + + " " + + stations[next(iter(stations))][2] + + "} " + + os.path.basename(thNameXvi) + + " 0 {}", ) ) - if scrap_to_add >= 1 : + if scrap_to_add >= 1: for i in range(scrap_to_add): # other_scraps_extended = other_scraps_extended + f"\tSC-{TARGET[0]}_{i+2:02}\n\tbreak\n" - f.write(globalData.th2Scrap.format( - name=TARGET, - projection="extended", - projection_short="C", - author=globalData.Author, - Copyright_Short=globalData.CopyrightShort, - year=datetime.now().year, - num=f"{i+2:02}", + f.write( + globalData.th2Scrap.format( + name=TARGET, + projection="extended", + projection_short="C", + author=globalData.Author, + Copyright_Short=globalData.CopyrightShort, + year=datetime.now().year, # noqa: DTZ005 + num=f"{i + 2:02}", ) ) - - - ################################################################################################# - # Update -maps files # - ################################################################################################# - if not UPDATE: - - config_vars = { - 'fileName': TH_NAME, - 'caveName': TH_NAME.replace("_", " "), - 'Author': globalData.Author, - 'Copyright': globalData.Copyright, - 'Scale' : SCALE, - 'Target' : TARGET, - 'mapComment' : globalData.mapComment, - 'club' : globalData.club, - 'thanksto' : globalData.thanksto, - 'datat' : globalData.datat, - 'wpage' : globalData.wpage, - 'cs' : globalData.cs, - 'maps' : maps, - 'plan': plan, - 'extended': extended, - 'configPath' : CONFIG_PATH, - 'other_scraps_plan' : other_scraps_plan, - 'other_scraps_extended' : other_scraps_extended, - 'file_info' : f"# File generated by pyCreateTh.py version {globalData.Version} date: {datetime.now().strftime("%Y.%m.%d-%H:%M:%S")}", - } - - update_template_files(DEST_PATH + '/template-maps.th', config_vars, DEST_PATH + '/' + TH_NAME + '-maps.th') - - - ################################################################################################# + ################################################################################################# + # Update -maps files # + ################################################################################################# + if not UPDATE: + config_vars = { + "fileName": TH_NAME, + "caveName": TH_NAME.replace("_", " "), + "Author": globalData.Author, + "Copyright": globalData.Copyright, + "Scale": SCALE, + "Target": TARGET, + "mapComment": globalData.mapComment, + "club": globalData.club, + "thanksto": globalData.thanksto, + "datat": globalData.datat, + "wpage": globalData.wpage, + "cs": globalData.cs, + "maps": maps, + "plan": plan, + "extended": extended, + "configPath": CONFIG_PATH, + "other_scraps_plan": other_scraps_plan, + "other_scraps_extended": other_scraps_extended, + "file_info": f"# File generated by pyCreateTh.py version {globalData.Version} date: {datetime.now().strftime('%Y.%m.%d-%H:%M:%S')}", # noqa: DTZ005 + } + + update_template_files(DEST_PATH + "/template-maps.th", config_vars, DEST_PATH + "/" + TH_NAME + "-maps.th") + + ################################################################################################# # Final therion compilation # ################################################################################################# - if not UPDATE: + if not UPDATE: # noqa: SIM102 if globalData.finalTherionExe == True: - FILE = os.path.dirname(ENTRY_FILE) + "/" + TH_NAME + "/" + TH_NAME + ".thconfig" - # log.info(f"Final therion compilation: {Colors.ENDC}{safe_relpath(FILE)}") - if not flagErrorCompile : + FILE = os.path.dirname(ENTRY_FILE) + "/" + TH_NAME + "/" + TH_NAME + ".thconfig" + # log.info(f"Final therion compilation: {Colors.ENDC}{safe_relpath(FILE)}") + if not flagErrorCompile: t = compile_file(FILE, therion_path=globalData.therionPath) - threads.append(t) - - return flagErrorCompile, stat, totReadMeError, threads + threads.append(t) + return flagErrorCompile, stat, totReadMeError, threads diff --git a/Scripts/pyCreateTh/Lib/therion.py b/Scripts/pyCreateTh/Lib/therion.py index 25e11a0..82cdc61 100644 --- a/Scripts/pyCreateTh/Lib/therion.py +++ b/Scripts/pyCreateTh/Lib/therion.py @@ -1,30 +1,31 @@ """ !############################################################################################# -therion.py for pyCreateTh.py +therion.py for pyCreateTh.py !############################################################################################# """ -import tempfile, shutil, os, re, logging, threading, subprocess, time +import tempfile, shutil, os, re, logging, threading, subprocess, time # noqa: I001 from os.path import join -import Lib.global_data as global_data -from Lib.general_fonctions import Colors +import Lib.global_data as global_data # noqa: PLR0402 +from Lib.general_fonctions import Colors, safe_relpath log = logging.getLogger("Logger") -################################################################################################# + +################################################################################################# # Compilation Therion 'Template' (version sans blocage) # # Compiler une configuration générée dynamiquement à partir d'un template texte. # ################################################################################################# -def compile_template(template, template_args, totReadMeError = "", **kwargs ): +def compile_template(template, template_args, totReadMeError="", **kwargs): logfile = "" tmpdir = None try: tmpdir = tempfile.mkdtemp() config = template.format(**template_args, tmpdir=tmpdir.replace("\\", "/")) - + log.debug(f"{config}\n") config_file = join(tmpdir, "config.thconfig") @@ -37,44 +38,46 @@ def compile_template(template, template_args, totReadMeError = "", **kwargs ): tmp.flush() # Exécution de Therion - result = subprocess.run( + result = subprocess.run( # noqa: PLW1510 [therion_path, config_file, "-l", log_file], stdin=subprocess.DEVNULL, # Évite toute attente d'entrée clavier stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=kwargs.get("timeout", 30), - errors="replace" + errors="replace", ) # Lecture du fichier log try: with open(log_file, "r", encoding="cp1252", errors="replace") as f: logfile = f.read() - - except Exception as log_err: + + except Exception as log_err: # noqa: BLE001 log.warning(f"Could not read Therion log: {Colors.ENDC}{log_err}") # Analyse du code retour if result.returncode != 0 or "press any key" in result.stdout.lower(): - selector_value = template_args['selector'] - log.error(f"Therion compilation {Colors.ENDC}{selector_value}{Colors.ERROR}, failed with return code: {Colors.ENDC}{result.returncode}\n{Colors.WHITE}{result.stdout}") + selector_value = template_args["selector"] + log.error( + f"Therion compilation {Colors.ENDC}{selector_value}{Colors.ERROR}, failed with return code: {Colors.ENDC}{result.returncode}\n{Colors.WHITE}{result.stdout}" + ) totReadMeError += f"\tTherion compilation {selector_value}, failed with return code: {result.returncode}\n" global_data.error_count += 1 return "Therion error", tmpdir, totReadMeError stat = get_stats_from_log(logfile) - log.info(f"Therion compilation successful, length: {Colors.ENDC}{stat["length"]}m{Colors.INFO}, depth: {Colors.ENDC}{stat["depth"]}m") + log.info(f"Therion compilation successful, length: {Colors.ENDC}{stat['length']}m{Colors.INFO}, depth: {Colors.ENDC}{stat['depth']}m") return logfile, tmpdir, totReadMeError except subprocess.TimeoutExpired: log.error(f"Therion process timed out and was terminated: {Colors.ENDC}{logfile}") - totReadMeError += f"\tTherion process timed out and was terminated\n" + totReadMeError += "\tTherion process timed out and was terminated\n" global_data.error_count += 1 return "Therion error", tmpdir, totReadMeError - except Exception as e: + except Exception as e: # noqa: BLE001 log.error(f"Therion template compilation error: {Colors.ENDC}{e}") totReadMeError += f"\tTherion template compilation error: {e}\n" global_data.error_count += 1 @@ -84,11 +87,11 @@ def compile_template(template, template_args, totReadMeError = "", **kwargs ): if kwargs.get("cleanup", True) and tmpdir: try: shutil.rmtree(tmpdir) - except Exception as cleanup_err: + except Exception as cleanup_err: # noqa: BLE001 log.warning(f"Could not delete temp directory: {Colors.ENDC}{cleanup_err}") - -################################################################################################# + +################################################################################################# # Compilation Therion (version sans blocage) # ################################################################################################# def compile_file(filename, **kwargs): @@ -97,17 +100,12 @@ def compile_file(filename, **kwargs): therion_path = kwargs.get("therion_path", "therion") timeout = kwargs.get("timeout", 240) - log.info(f"Start therion [Therion Compile {Colors.WHITE}{os.path.basename(filename)[:-9]}{Colors.GREEN}], compilation file") + log.info(f"Start therion [Therion Compile {Colors.WHITE}{safe_relpath(os.path.basename(filename))[:-9]}{Colors.GREEN}], compilation file") def run(): try: process = subprocess.Popen( - [therion_path, filename, "-l", log_file], - cwd=tmpdir, - stdout=subprocess.PIPE, - stderr=subprocess.STDOUT, - universal_newlines=True, - bufsize=1 + [therion_path, filename, "-l", log_file], cwd=tmpdir, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, bufsize=1 ) last_output_time = time.time() @@ -115,7 +113,7 @@ def compile_file(filename, **kwargs): def read_output(proc): nonlocal last_output_time try: - for line in iter(proc.stdout.readline, ''): + for line in iter(proc.stdout.readline, ""): line = line.rstrip() last_output_time = time.time() # ← reset du timer ici lower_line = line.lower() @@ -123,18 +121,18 @@ def compile_file(filename, **kwargs): if "average loop error" in lower_line: continue elif "error" in lower_line: - log.error(f"[Therion_Compile {Colors.WHITE}{os.path.basename(filename)[:-9]}{Colors.ERROR}] {Colors.ENDC}{line}") + log.error(f"[Therion_Compile {Colors.WHITE}{safe_relpath(os.path.basename(filename))[:-9]}{Colors.ERROR}] {Colors.ENDC}{line}") elif "warning" in lower_line: - if not any(msg in line for msg in [ - "invalid scrap outline", - "average loop error", - "multiple scrap outer outlines not supported yet" - ]): - log.warning(f"[Therion compile {Colors.WHITE}{os.path.basename(filename)[:-9]}{Colors.WARNING}] {Colors.ENDC}{line}") + if not any(msg in line for msg in ["invalid scrap outline", "average loop error", "multiple scrap outer outlines not supported yet"]): + log.warning( + f"[Therion compile {Colors.WHITE}{safe_relpath(os.path.basename(filename))[:-9]}{Colors.WARNING}] {Colors.ENDC}{safe_relpath(line)}" + ) else: - log.debug(f"[Therion compile {Colors.WHITE}{os.path.basename(filename)[:-9]}{Colors.DEBUG}] {Colors.ENDC}{line}") - except Exception as e: - log.warning(f"Reading Therion [Therion_Compile {Colors.WHITE}{os.path.basename(filename)[:-9]}{Colors.WARNING}], output: {Colors.ENDC}{e}") + log.debug(f"[Therion compile {Colors.WHITE}{safe_relpath(os.path.basename(filename))[:-9]}{Colors.DEBUG}] {Colors.ENDC}{line}") + except Exception as e: # noqa: BLE001 + log.warning( + f"Reading Therion [Therion_Compile {Colors.WHITE}{safe_relpath(os.path.basename(filename))[:-9]}{Colors.WARNING}], output: {Colors.ENDC}{e}" + ) output_thread = threading.Thread(target=read_output, args=(process,)) output_thread.start() @@ -143,7 +141,9 @@ def compile_file(filename, **kwargs): while output_thread.is_alive(): output_thread.join(timeout=1) if time.time() - last_output_time > timeout: - log.error(f"Therion compilation [Therion_Compile {Colors.WHITE}{os.path.basename(filename)[:-9]}{Colors.ERROR}], timed out after {Colors.ENDC}{timeout}{Colors.ERROR} seconds of inactivity. Killing process...") + log.error( + f"Therion compilation [Therion_Compile {Colors.WHITE}{safe_relpath(os.path.basename(filename))[:-9]}{Colors.ERROR}], timed out after {Colors.ENDC}{timeout}{Colors.ERROR} seconds of inactivity. Killing process..." + ) global_data.error_count += 1 process.kill() break @@ -152,13 +152,15 @@ def compile_file(filename, **kwargs): process.wait() if process.returncode != 0: - log.error(f"Therion [Therion_Compile {Colors.WHITE}{os.path.basename(filename)[:-9]}{Colors.ERROR}], returned error code {Colors.ENDC}{process.returncode}") + log.error( + f"Therion [Therion_Compile {Colors.WHITE}{safe_relpath(os.path.basename(filename))[:-9]}{Colors.ERROR}], returned error code {Colors.ENDC}{process.returncode}" + ) global_data.error_count += 1 else: - log.info(f"Therion file: [Therion Compile {Colors.WHITE}{os.path.basename(filename)[:-9]}{Colors.GREEN}], compilation succeeded") + log.info(f"Therion file: [Therion Compile {Colors.WHITE}{safe_relpath(os.path.basename(filename))[:-9]}{Colors.GREEN}], compilation succeeded") - except Exception as e: - log.error(f"Therion file: [Therion Compile {Colors.WHITE}{os.path.basename(filename)[:-9]}{Colors.ERROR}], compilation error: {Colors.ENDC}{e}") + except Exception as e: # noqa: BLE001 + log.error(f"Therion file: [Therion Compile {Colors.WHITE}{safe_relpath(os.path.basename(filename))[:-9]}{Colors.ERROR}], compilation error: {Colors.ENDC}{e}") global_data.error_count += 1 # Lancer le thread principal pour cette compilation et le retourner @@ -166,6 +168,7 @@ def compile_file(filename, **kwargs): thread.start() return thread + ################################################################################################# def compile_file_th(filepath, **kwargs): template = """source {filepath} @@ -174,7 +177,7 @@ def compile_file_th(filepath, **kwargs): endlayout """ template_args = {"filepath": filepath} - logs, _, = compile_template(template, template_args, cleanup=True, **kwargs) + logs, _ = compile_template(template, template_args, cleanup=True, **kwargs) return logs @@ -186,27 +189,29 @@ fr_depthre = re.compile(r".*Longueur totale verticale =\s*(\S+)m") en_lengthre = re.compile(r".*Total length of survey legs = \s*(\S+)m") en_depthre = re.compile(r".*Vertical range =\s*(\S+)m") + def get_stats_from_log(log): lenmatch = fr_lengthre.findall(log) depmatch = fr_depthre.findall(log) - - if len(lenmatch) == 0 and len(depmatch) == 0: + + if len(lenmatch) == 0 and len(depmatch) == 0: lenmatch = en_lengthre.findall(log) depmatch = en_depthre.findall(log) - + if len(lenmatch) == 1 and len(depmatch) == 1: return {"length": lenmatch[0], "depth": depmatch[0]} - + return {"length": 0.0, "depth": 0.0} ################################################################################################# syscoord = re.compile(r".*output coordinate system: \s*(\S+)") + def get_syscoord_from_log(log): lenmatch = syscoord.findall(log) if len(lenmatch) == 1: return {"syscoord": lenmatch[0]} - - return {"syscoord": 0} \ No newline at end of file + + return {"syscoord": 0} diff --git a/Scripts/pyCreateTh/Lib/trox2th.py b/Scripts/pyCreateTh/Lib/trox2th.py index 97d0115..b4be7dd 100644 --- a/Scripts/pyCreateTh/Lib/trox2th.py +++ b/Scripts/pyCreateTh/Lib/trox2th.py @@ -1,92 +1,35 @@ """ - !---------------------------------------------------------! - ! ! - ! TroX to Therion ! - ! ! - ! Code to transform the .troX files ! - ! Visual Topo into files that can ! - ! be used by Therion ! - ! ! - ! Written by Alexandre Pont ! - ! ! - !---------------------------------------------------------! + !---------------------------------------------------------! + ! ! + ! TroX to Therion ! + ! ! + ! Code to transform the .troX files ! + ! Visual Topo into files that can ! + ! be used by Therion ! + ! ! + ! Written by Alexandre Pont ! + ! ! + !---------------------------------------------------------! - ENGLISH : - This code is to transform the .trox file from Visualtopo (http://vtopo.free.fr/) - into files that can be read by Therion (http://therion.speleo.sk/). - It reads .tro file and produce one .th file (file with survey data), - and one thconfig file (file that is used to compile and build the survey with Therion). - - Création Alex 2026 01 08 + ENGLISH : + This code is to transform the .trox file from Visualtopo (http://vtopo.free.fr/) + into files that can be read by Therion (http://therion.speleo.sk/). + It reads .tro file and produce one .th file (file with survey data), + and one thconfig file (file that is used to compile and build the survey with Therion). - - TODOS : -.... +Création Alex 2026 01 08 + + + TODOS : -.... """ -import xml.etree.ElementTree as ET +import xml.etree.ElementTree as ET # noqa: I001 from collections import defaultdict, Counter from pathlib import Path -from Lib.general_fonctions import Colors, safe_relpath -import Lib.global_data as global_data - - -def analyse_xml_balises_old(xml_path): - """ - Analyse un fichier XML et affiche : - - le nombre d'occurrences de chaque balise - - pour chaque balise, les attributs rencontrés et leurs occurrences - - Parameters - ---------- - xml_path : str | Path - Chemin vers le fichier XML - """ - - xml_path = Path(xml_path) - - if not xml_path.exists(): - raise FileNotFoundError(f"{Colors.ERROR}Fichier introuvable : {Colors.ENDC}{xml_path}") - - # Chargement XML - tree = ET.parse(xml_path) - root = tree.getroot() - - # Comptage des balises - tag_counter = Counter() - - # Dictionnaire : - # { tag_name : Counter({attr_name: nb_occurrences}) } - attributes_counter = defaultdict(Counter) - - # Parcours de tous les éléments - for elem in root.iter(): - tag_counter[elem.tag] += 1 - - for attr_name in elem.attrib.keys(): - attributes_counter[elem.tag][attr_name] += 1 - - # Affichage - print("\n") - print("=" * 80) - print(f"{Colors.INFO}Analyse du fichier : {Colors.ENDC}{xml_path.name}") - print("=" * 80) - - for tag in sorted(tag_counter.keys()): - print(f"\n{Colors.BLUE}Balise <{Colors.ENDC}{tag}{Colors.BLUE}>") - print(f" {Colors.CYAN}Occurrences : {Colors.ENDC}{tag_counter[tag]}") - - if attributes_counter[tag]: - print(f" {Colors.MAGENTA}Attributs :") - for attr, count in attributes_counter[tag].most_common(): - print(f" {Colors.MAGENTA}- {Colors.ENDC}{attr}{Colors.MAGENTA} : {Colors.ENDC}{count}") - else: - print(f" {Colors.RED}Attributs : aucun") - - print(f"\n{Colors.INFO}Analyse terminée.") - - +from Lib.general_fonctions import Colors +################################################################################################# def analyse_xml_balises(xml_path): """ Analyse un fichier XML et affiche : @@ -98,23 +41,15 @@ def analyse_xml_balises(xml_path): xml_path = Path(xml_path) if not xml_path.exists(): - raise FileNotFoundError( - f"{Colors.ERROR}Fichier introuvable : {Colors.ENDC}{xml_path}" - ) + raise FileNotFoundError(f"{Colors.ERROR}Fichier introuvable : {Colors.ENDC}{xml_path}") # ---------------------------- # Définition des catégories # ---------------------------- TAG_CATEGORIES = { - "Version": { - "version", "header", "metadata" - }, - "Mesures": { - "mesure", "measure", "value", "data", "record" - }, - "Param": { - "param", "parameter", "config", "setting" - }, + "Version": {"version", "header", "metadata"}, + "Mesures": {"mesure", "measure", "value", "data", "record"}, + "Param": {"param", "parameter", "config", "setting"}, } DEFAULT_CATEGORY = "Autres" @@ -159,26 +94,22 @@ def analyse_xml_balises(xml_path): # ---------------------------- # Affichage # ---------------------------- - print("\n" + "=" * 80) + print(f"{Colors.INFO}" + "=" * 80) print(f"{Colors.INFO}Analyse du fichier : {Colors.ENDC}{xml_path.name}") - print("=" * 80) + print(f"{Colors.INFO}" + "=" * 80) for category in sorted(categorized_tags.keys()): - print(f"\n{Colors.YELLOW}## {category}{Colors.ENDC}") - print("-" * 60) + print(f"{Colors.YELLOW}## {category}{Colors.ENDC}") + print(f"{Colors.INFO}" + "-" * 60) for tag in sorted(categorized_tags[category]): - print(f"\n {Colors.BLUE}Balise <{Colors.ENDC}{tag}{Colors.BLUE}>") - print(f" {Colors.CYAN}Occurrences : {Colors.ENDC}{tag_counter[tag]}") + print(f"{Colors.BLUE}Balise <{Colors.ENDC}{tag}{Colors.BLUE}>\t{Colors.CYAN}Occurrences : {Colors.ENDC}{tag_counter[tag]}") if attributes_counter[tag]: - print(f" {Colors.MAGENTA}Attributs :{Colors.ENDC}") + print(f"\t{Colors.MAGENTA}Attributs :{Colors.ENDC}") for attr, count in attributes_counter[tag].most_common(): - print( - f" {Colors.MAGENTA}- {Colors.ENDC}{attr}" - f"{Colors.MAGENTA} : {Colors.ENDC}{count}" - ) - else: - print(f" {Colors.RED}Attributs : aucun{Colors.ENDC}") + print(f"\t\t{Colors.MAGENTA}- {Colors.ENDC}{attr}{Colors.MAGENTA} : {Colors.ENDC}{count}") + # else: + # print(f"\t{Colors.RED}Attributs : aucun{Colors.ENDC}") - print(f"\n{Colors.INFO}Analyse terminée.{Colors.ENDC}") + print(f"{Colors.INFO}Analyse terminée.{Colors.ENDC}") diff --git a/Scripts/pyCreateTh/pyCreateTh.py b/Scripts/pyCreateTh/pyCreateTh.py index 30ff295..f2febb5 100644 --- a/Scripts/pyCreateTh/pyCreateTh.py +++ b/Scripts/pyCreateTh/pyCreateTh.py @@ -20,7 +20,7 @@ Merci à : - Tanguy Racine pour les scripts https://github.com/tr1813 - Xavier Robert pour les principes de base https://github.com/robertxa - Xavier Robert pour les scripts de conversion .tro https://github.com/robertxa/pytherion - - Benoit Urruty https://github.com/BenoitURRUTY + - Benoît Urruty https://github.com/BenoitURRUTY Sources documentaires : - Format des fichiers compass : https://fountainware.com/compass/Documents/FileFormats/FileFormats.htm @@ -47,11 +47,9 @@ En cours : ################################################################################################# ################################################################################################# -import os, re, argparse, shutil, sys, time, math -from os.path import isfile, join, abspath, splitext +import os, re, argparse, shutil, sys, time # noqa: I001 +from os.path import abspath, splitext from pathlib import Path -import numpy as np -import networkx as nx import pandas as pd # pd.set_option('future.no_silent_downcasting', True) @@ -61,32 +59,16 @@ from copy import deepcopy from alive_progress import alive_bar # https://github.com/rsalmei/alive-progress from contextlib import redirect_stdout -from Lib.survey import SurveyLoader, NoSurveysFoundException -from Lib.therion import compile_template, compile_file, get_stats_from_log +from Lib.therion import compile_file, get_stats_from_log from Lib.general_fonctions import setup_logger, Colors, safe_relpath, colored_help -from Lib.general_fonctions import ( - load_config, - select_file_tk_window, - release_log_file, - sanitize_filename, - load_text_file_utf8, -) -from Lib.general_fonctions import ( - copy_template_if_not_exists, - add_copyright_header, - copy_file_with_copyright, - update_template_files, -) +from Lib.general_fonctions import load_config, select_file_tk_window, release_log_file, sanitize_filename, load_text_file_utf8 +from Lib.general_fonctions import copy_template_if_not_exists, update_template_files, read_text_file import Lib.global_data as globalData from Lib.pytro2th.tro2th import convert_tro # Version local modifiée from Lib.trox2th import analyse_xml_balises from Lib.th2th import create_th_folders -################################################################################################# -debug_log = False # Mode debug des messages - - ################################################################################################# # Renommage des tableau pdFrame de station # ################################################################################################# @@ -159,29 +141,19 @@ def parse_therion_centerline(file_data): current_data.append(line) for p in parts[:2]: - if p.lower() not in globalData.THERION_KEYWORDS and not re.match( - r"^[0-9.+-]+$", p - ): + if p.lower() not in globalData.THERION_KEYWORDS and not re.match(r"^[0-9.+-]+$", p): current_stations.add(p) # Fin centerline if low.startswith("endcenterline"): - centerline_list.append( - { - "lines": current_block, - "DATA": current_data, - "date": current_date, - "type": sorted(current_stations), - } - ) - + centerline_list.append({"lines": current_block, "DATA": current_data, "date": current_date, "type": sorted(current_stations)}) in_centerline = False current_block = [] current_data = [] current_date = None current_stations = set() - except Exception as e: + except Exception as e: # noqa: BLE001 log.error(f"An error occurred (parse_therion_centerline): {Colors.ENDC}{e}") globalData.error_count += 1 @@ -208,9 +180,7 @@ def regroupe_date(centerline_list): for idx, cl in enumerate(centerline_list): # Sécurité : cl doit être un dict if not isinstance(cl, dict): - log.warning( - f"regroupe_date: entrée ignorée (index {idx}, type invalide)" - ) + log.warning(f"regroupe_date: entrée ignorée (index {idx}, type invalide)") continue date = cl.get("date") @@ -236,7 +206,7 @@ def regroupe_date(centerline_list): return result - except Exception as e: + except Exception as e: # noqa: BLE001 # noqa: BLE001 log.error(f"An error occurred (regroupe_date): {Colors.ENDC}{e}") globalData.error_count += 1 return [] @@ -267,15 +237,10 @@ def mak_to_th_file(ENTRY_FILE): totReadMeFixPoint = "" datFiles = [] - patternDat = re.compile( - r"^#.*?\.dat[,;]$", re.IGNORECASE - ) # Motif insensible à la casse + patternDat = re.compile(r"^#.*?\.dat[,;]$", re.IGNORECASE) # Motif insensible à la casse fixPoints = [] - patternFixPoints = re.compile( - r"^([\w-]+)\[(m|f)\s*[, ]\s*(-?\d+\.?\d*)\s*[, ]\s*(-?\d+\.?\d*)\s*[, ]\s*(-?\d+\.?\d*)\]\s*[,;]?\s*(?:/.*)?$", - re.IGNORECASE, - ) + patternFixPoints = re.compile(r"^([\w-]+)\[(m|f)\s*[, ]\s*(-?\d+\.?\d*)\s*[, ]\s*(-?\d+\.?\d*)\s*[, ]\s*(-?\d+\.?\d*)\]\s*[,;]?\s*(?:/.*)?$", re.IGNORECASE) UTM = [] @@ -287,18 +252,14 @@ def mak_to_th_file(ENTRY_FILE): line = line.strip() # Supprime les espaces et sauts de ligne if patternDat.match(line): # Supprime le '#' au début et '.dat,' ou '.dat;' à la fin (insensible à la casse) - cleaned_entry = re.sub( - r"^#|\.dat[,;]$", "", line, flags=re.IGNORECASE - ) + cleaned_entry = re.sub(r"^#|\.dat[,;]$", "", line, flags=re.IGNORECASE) datFiles.append(cleaned_entry + ".DAT") match = patternFixPoints.match(line) if match: name_point, mf, x, y, z = match.groups() - fixPoints.append( - [name_point, mf.lower(), float(x), float(y), float(z)] - ) + fixPoints.append([name_point, mf.lower(), float(x), float(y), float(z)]) if line.startswith("@") and line.endswith(";"): parts = line[1:-1].split(",") # Supprime "@" et ";", puis découpe @@ -314,33 +275,29 @@ def mak_to_th_file(ENTRY_FILE): log.error(f"The mak file {Colors.ENDC}{ENTRY_FILE}{Colors.ERROR} dit not exist") globalData.error_count += 1 - except Exception as e: + except Exception as e: # noqa: BLE001 log.error(f"An error occurred (readMakFile): {Colors.ENDC}{e}") globalData.error_count += 1 # Vérification des valeurs if len(Datums) > 1: - log.critical( - f"Several different Datums found in {Colors.ENDC}{shortCurentFile}{Colors.CRITICAL}, case not handled! : {Colors.ENDC}{Datums}" - ) - exit(0) + log.critical(f"Several different Datums found in {Colors.ENDC}{shortCurentFile}{Colors.CRITICAL}, case not handled! : {Colors.ENDC}{Datums}") + sys.exit() elif not Datums: log.critical(f"no datum found in mak file : {Colors.ENDC}{shortCurentFile}") - exit(0) + sys.exit() elif not datFiles: log.critical(f"No dat file found in mak file : {Colors.ENDC}{shortCurentFile}") - exit(0) + sys.exit() elif not fixPoints: - log.critical( - f"No fix points found in mak file : {Colors.ENDC}{shortCurentFile}" - ) - exit(0) + log.critical(f"No fix points found in mak file : {Colors.ENDC}{shortCurentFile}") + sys.exit() datum_lower = next(iter(Datums)).strip().lower().replace(" ", "") if datum_lower not in globalData.datumToEPSG: log.critical(f"Unknown Datum : {datum_lower}") - exit(0) + sys.exit() # Extraction du numéro de zone UTM et de l'hémisphère (N/S) if int(UTM[0]) >= 0: @@ -355,15 +312,11 @@ def mak_to_th_file(ENTRY_FILE): # Vérification de la validité de la zone UTM (1-60) if not 1 <= zone_num <= 60: log.critical("The UTM zone must be between 1 and 60") - exit(0) + sys.exit() # Construction du code EPSG epsg_prefix = globalData.datumToEPSG[datum_lower] - epsg_code = ( - f"{epsg_prefix}{zone_num}" - if hemisphere == "N" - else f"{epsg_prefix}{zone_num + 100}" - ) + epsg_code = f"{epsg_prefix}{zone_num}" if hemisphere == "N" else f"{epsg_prefix}{zone_num + 100}" # Génération du CRS QGIS (format WKT) crs_wkt = f"EPSG:{epsg_code}" @@ -377,9 +330,7 @@ def mak_to_th_file(ENTRY_FILE): for file in datFiles: ABS_file = os.path.dirname(abspath(args.file)) + "\\" + file - content, val, encodage = load_text_file_utf8( - ABS_file, os.path.basename(ABS_file) - ) + content, val, encodage = load_text_file_utf8(ABS_file, os.path.basename(ABS_file)) # noqa: RUF059 section = content.split("\x0c") QtySections += len(section) @@ -393,23 +344,17 @@ def mak_to_th_file(ENTRY_FILE): # Boucle pour lire les dat # ############################################################################################## - stationList = pd.DataFrame( - columns=["StationName", "Survey_Name_01", "Survey_Name_02"] - ) - totdata = f"\t## Input list:\n" + stationList = pd.DataFrame(columns=["StationName", "Survey_Name_01", "Survey_Name_02"]) + totdata = "\t## Input list:\n" totMapsPlan = "" totMapsExtended = "" proj = args.proj.lower() - values = { - "none": ("# ", "# ", "# "), - "plan": ("", "", "# "), - "extended": ("", "# ", ""), - } + values = {"none": ("# ", "# ", "# "), "plan": ("", "", "# "), "extended": ("", "# ", "")} maps, plan, extended = values.get(proj, ("", "", "")) - with ( + with ( # noqa: SIM117 alive_bar( QtySections, title=f"{Colors.GREEN}Surveys progress: {Colors.BLUE}", @@ -424,9 +369,7 @@ def mak_to_th_file(ENTRY_FILE): with redirect_stdout(sys.__stdout__): for file in datFiles: if globalData.error_count > 0: - bar.text( - f"{Colors.INFO}file: {Colors.ENDC}{file[:-4]}{Colors.ERROR}, error: {Colors.ENDC}{globalData.error_count}" - ) + bar.text(f"{Colors.INFO}file: {Colors.ENDC}{file[:-4]}{Colors.ERROR}, error: {Colors.ENDC}{globalData.error_count}") else: bar.text(f"{Colors.INFO}file: {Colors.ENDC}{file[:-4]}") @@ -437,28 +380,20 @@ def mak_to_th_file(ENTRY_FILE): totReadMeError += f"\t* file: {file}\n" totReadMeList += f"\tfile: {file}\n" - Station, SurveyTitle, totReadMeError, thread2 = dat_to_th_files( - ABS_file, fixPoints, crs_wkt, _ConfigPath, totReadMeError, bar - ) + Station, SurveyTitle, totReadMeError, thread2 = dat_to_th_files(ABS_file, fixPoints, crs_wkt, _ConfigPath, totReadMeError, bar) threads += thread2 totdata += f"\tinput Data/{SurveyTitle}/{SurveyTitle}-tot.th\n" - totMapsPlan += ( - f"\t{plan}MP-{SurveyTitle}-Plan-tot@{SurveyTitle}\n\t{plan}break\n" - ) + totMapsPlan += f"\t{plan}MP-{SurveyTitle}-Plan-tot@{SurveyTitle}\n\t{plan}break\n" totMapsExtended += f"\t{extended}MC-{SurveyTitle}-Extended-tot@{SurveyTitle}\n\t{extended}break\n" if not Station.empty: __stationList = pd.concat([stationList, Station], ignore_index=True) - __stationList.sort_values( - by="Survey_Name_02", inplace=True, ignore_index=True - ) + __stationList.sort_values(by="Survey_Name_02", inplace=True, ignore_index=True) stationList = __stationList.copy() - destination = os.path.join( - folderDest, "Sources", os.path.basename(ABS_file) - ) + destination = os.path.join(folderDest, "Sources", os.path.basename(ABS_file)) if os.path.exists(destination): os.remove(destination) @@ -470,41 +405,31 @@ def mak_to_th_file(ENTRY_FILE): # Gestion des equates ################################################################################################# - totdata += f"\n" + totdata += "\n" _stationList = stationList.copy() - _stationList["Survey_Name_01"] = ( - _stationList["Survey_Name_01"] - + "." - + _stationList["Survey_Name_01"] - + "." - + _stationList["Survey_Name_02"] - ) + _stationList["Survey_Name_01"] = _stationList["Survey_Name_01"] + "." + _stationList["Survey_Name_01"] + "." + _stationList["Survey_Name_02"] # On numérote les doublons de Survey_Name pour chaque StationName _stationList["Survey_Number"] = _stationList.groupby("StationName").cumcount() + 1 # print(_stationList) # On pivote le tableau pour que chaque Survey_Name devienne une colonne - tableau_pivot = _stationList.pivot( - index="StationName", columns="Survey_Number", values="Survey_Name_01" - ) + tableau_pivot = _stationList.pivot(index="StationName", columns="Survey_Number", values="Survey_Name_01") tableau_pivot.columns = [f"Survey_Name_{i}" for i in tableau_pivot.columns] # print(f"tableau_pivot : {Colors.ENDC}{tableau_pivot}{Colors.INFO} in {Colors.ENDC}{args.file}") - totdata += f"\n\t## Equates list:\n" + totdata += "\n\t## Equates list:\n" if "Survey_Name_2" in tableau_pivot.columns: # On réinitialise l'index pour avoir StationName comme colonne normale tableau_pivot = tableau_pivot.reset_index() tableau_equate = tableau_pivot[tableau_pivot["Survey_Name_2"].notna()] - log.info( - f"Total des '{Colors.ENDC}equates{Colors.INFO}' in mak file: {Colors.ENDC}{len(tableau_equate)}{Colors.INFO} in {Colors.ENDC}{safe_relpath(args.file)}" - ) + log.info(f"Total des '{Colors.ENDC}equates{Colors.INFO}' in mak file: {Colors.ENDC}{len(tableau_equate)}{Colors.INFO} in {Colors.ENDC}{safe_relpath(args.file)}") # print(tableau_equate) # print(f"fixPoints: {Colors.ENDC}{fixPoints}{Colors.INFO} in {Colors.ENDC}{args.file}") @@ -513,19 +438,13 @@ def mak_to_th_file(ENTRY_FILE): station = row["StationName"] # On récupère tous les Survey_Name non vides (NaN exclus) - surveys = [ - row[col] - for col in tableau_equate.columns - if col.startswith("Survey_Name") and pd.notna(row[col]) - ] + surveys = [row[col] for col in tableau_equate.columns if col.startswith("Survey_Name") and pd.notna(row[col])] # Pour chaque paire unique (i < j), on écrit la ligne 'equate' for i in range(len(surveys)): for j in range(i + 1, len(surveys)): if surveys[i].split(".")[2] != surveys[j].split(".")[2]: - totdata += ( - f"\tequate {station}@{surveys[i]} {station}@{surveys[j]}\n" - ) + totdata += f"\tequate {station}@{surveys[i]} {station}@{surveys[j]}\n" # print(f"\tequate {station}@{surveys[i]} {station}@{surveys[j]}") else: log.info(f"No 'equats' found in {Colors.ENDC}{args.file}") @@ -556,26 +475,14 @@ def mak_to_th_file(ENTRY_FILE): "readMeList": totReadMeList, "errorList": totReadMeError, "fixPointList": totReadMeFixPoint, - "file_info": f"# File generated by pyCreateTh.py version: {globalData.Version} date: {datetime.now().strftime('%Y.%m.%d-%H:%M:%S')}", + "file_info": f"# File generated by pyCreateTh.py version: {globalData.Version} date: {datetime.now().strftime('%Y.%m.%d-%H:%M:%S')}", # noqa: DTZ005 } DEST_PATH = os.path.dirname(args.file) + "/" + SurveyTitleMak - update_template_files( - DEST_PATH + "/template.thconfig", - config_vars, - DEST_PATH + "/" + SurveyTitleMak + ".thconfig", - ) - update_template_files( - DEST_PATH + "/template-tot.th", - config_vars, - DEST_PATH + "/" + SurveyTitleMak + "-tot.th", - ) - update_template_files( - DEST_PATH + "/template-maps.th", - config_vars, - DEST_PATH + "/" + SurveyTitleMak + "-maps.th", - ) + update_template_files(DEST_PATH + "/template.thconfig", config_vars, DEST_PATH + "/" + SurveyTitleMak + ".thconfig") + update_template_files(DEST_PATH + "/template-tot.th", config_vars, DEST_PATH + "/" + SurveyTitleMak + "-tot.th") + update_template_files(DEST_PATH + "/template-maps.th", config_vars, DEST_PATH + "/" + SurveyTitleMak + "-maps.th") ################################################################################################# # Final therion compilation # @@ -599,20 +506,14 @@ def mak_to_th_file(ENTRY_FILE): if stat["length"] != 0.0 and stat["depth"] != 0.0: totReadMeList += f"\tFinal compilation successful length: {stat['length']} m, depth: {stat['depth']} m\n" - log.info( - f"Final compilation successful length: {Colors.ENDC}{stat['length']}{Colors.INFO} m, depth: {Colors.ENDC}{stat['depth']}{Colors.INFO} m" - ) + log.info(f"Final compilation successful length: {Colors.ENDC}{stat['length']}{Colors.INFO} m, depth: {Colors.ENDC}{stat['depth']}{Colors.INFO} m") else: - totReadMeList += f"\tFinal compilation error, check log file\n" - log.error(f"Final compilation error, check log file") + totReadMeList += "\tFinal compilation error, check log file\n" + log.error("Final compilation error, check log file") config_vars["readMeList"] = totReadMeList - update_template_files( - DEST_PATH + "/template-readme.md", - config_vars, - DEST_PATH + "/" + SurveyTitle + "-readme.md", - ) + update_template_files(DEST_PATH + "/template-readme.md", config_vars, DEST_PATH + "/" + SurveyTitle + "-readme.md") return SurveyTitleMak, threads @@ -638,28 +539,16 @@ def station_list_dat(data, list, list_fixed, fixPoints, currentSurveyName): # stations = pd.concat([dfDATA.iloc[1:, 0], dfDATA.iloc[1:, 1]]).drop_duplicates().str.replace('[', '%').str.replace(']', '%%').str.replace('@', '_._') - stations = ( - pd.concat([dfDATA.iloc[1:, 0], dfDATA.iloc[1:, 1]]) - .drop_duplicates() - .stationName() - ) - stationsFixed = ( - pd.concat([dfDATA.iloc[1:, 0], dfDATA.iloc[1:, 1]]) - .drop_duplicates() - .stationName() - ) + stations = pd.concat([dfDATA.iloc[1:, 0], dfDATA.iloc[1:, 1]]).drop_duplicates().stationName() + stationsFixed = pd.concat([dfDATA.iloc[1:, 0], dfDATA.iloc[1:, 1]]).drop_duplicates().stationName() fixed_names = {point[0] for point in fixPoints} stations = stations[~stations.isin(fixed_names)] stations_fixed = stationsFixed[stationsFixed.isin(fixed_names)] - new_entries = pd.DataFrame( - {"StationName": stations, "Survey_Name_01": currentSurveyName} - ) + new_entries = pd.DataFrame({"StationName": stations, "Survey_Name_01": currentSurveyName}) - new_fixed = pd.DataFrame( - {"Station_Fix": stations_fixed, "Survey_Name": currentSurveyName} - ) + new_fixed = pd.DataFrame({"Station_Fix": stations_fixed, "Survey_Name": currentSurveyName}) list = pd.concat([list, new_entries], ignore_index=True) list_fixed = pd.concat([list_fixed, new_fixed], ignore_index=True) @@ -690,22 +579,8 @@ def station_list_th(data, list, list_fixed, fixPoints, currentSurveyName): # stations = pd.concat([dfDATA.iloc[1:, 0], dfDATA.iloc[1:, 1]]).drop_duplicates().stationName() # stations = pd.concat([dfDATA.iloc[:, 0], dfDATA.iloc[:, 1]]).drop_duplicates().reset_index(drop=True) - stations = ( - pd.concat([dfDATA.iloc[:, 0], dfDATA.iloc[:, 1]]) - .dropna() - .astype(str) - .loc[lambda s: ~s.isin(["-", "*"])] - .drop_duplicates() - .reset_index(drop=True) - ) - stationsFixed = ( - pd.concat([dfDATA.iloc[:, 0], dfDATA.iloc[:, 1]]) - .dropna() - .astype(str) - .loc[lambda s: ~s.isin(["-", "*"])] - .drop_duplicates() - .reset_index(drop=True) - ) + stations = pd.concat([dfDATA.iloc[:, 0], dfDATA.iloc[:, 1]]).dropna().astype(str).loc[lambda s: ~s.isin(["-", "*"])].drop_duplicates().reset_index(drop=True) + stationsFixed = pd.concat([dfDATA.iloc[:, 0], dfDATA.iloc[:, 1]]).dropna().astype(str).loc[lambda s: ~s.isin(["-", "*"])].drop_duplicates().reset_index(drop=True) # print(stations) @@ -713,13 +588,9 @@ def station_list_th(data, list, list_fixed, fixPoints, currentSurveyName): stations = stations[~stations.isin(fixed_names)] stations_fixed = stationsFixed[stationsFixed.isin(fixed_names)] - new_entries = pd.DataFrame( - {"StationName": stations, "Survey_Name_01": currentSurveyName} - ) + new_entries = pd.DataFrame({"StationName": stations, "Survey_Name_01": currentSurveyName}) - new_fixed = pd.DataFrame( - {"Station_Fix": stations_fixed, "Survey_Name": currentSurveyName} - ) + new_fixed = pd.DataFrame({"Station_Fix": stations_fixed, "Survey_Name": currentSurveyName}) list = pd.concat([list, new_entries], ignore_index=True) list_fixed = pd.concat([list_fixed, new_fixed], ignore_index=True) @@ -757,83 +628,48 @@ def formated_station_list(df, dataFormat, unit="meter", shortCurentFile="None"): if "length" in columns: col_name = df_data.columns[columns.index("length") - 2] - df_data.iloc[:, col_name] = ( - df_data.iloc[:, col_name].astype(float) * Koef - ).apply(lambda x: f"{x:.2f}") + df_data.iloc[:, col_name] = (df_data.iloc[:, col_name].astype(float) * Koef).apply(lambda x: f"{x:.2f}") if "up" in columns: col_name = df_data.columns[columns.index("up") - 2] df_data[col_name] = pd.to_numeric(df_data[col_name], errors="coerce") * Koef - df_data[col_name] = df_data[col_name].apply( - lambda x: ( - "-" if pd.notna(x) and x < 0 else f"{x:.2f}" if pd.notna(x) else "" - ) - ) + df_data[col_name] = df_data[col_name].apply(lambda x: "-" if pd.notna(x) and x < 0 else f"{x:.2f}" if pd.notna(x) else "") if "down" in columns: col_name = df_data.columns[columns.index("down") - 2] df_data[col_name] = pd.to_numeric(df_data[col_name], errors="coerce") * Koef - df_data[col_name] = df_data[col_name].apply( - lambda x: ( - "-" if pd.notna(x) and x < 0 else f"{x:.2f}" if pd.notna(x) else "" - ) - ) + df_data[col_name] = df_data[col_name].apply(lambda x: "-" if pd.notna(x) and x < 0 else f"{x:.2f}" if pd.notna(x) else "") if "right" in columns: col_name = df_data.columns[columns.index("right") - 2] df_data[col_name] = pd.to_numeric(df_data[col_name], errors="coerce") * Koef - df_data[col_name] = df_data[col_name].apply( - lambda x: ( - "-" if pd.notna(x) and x < 0 else f"{x:.2f}" if pd.notna(x) else "" - ) - ) + df_data[col_name] = df_data[col_name].apply(lambda x: "-" if pd.notna(x) and x < 0 else f"{x:.2f}" if pd.notna(x) else "") if "left" in columns: col_name = df_data.columns[columns.index("left") - 2] df_data[col_name] = pd.to_numeric(df_data[col_name], errors="coerce") * Koef - df_data[col_name] = df_data[col_name].apply( - lambda x: ( - "-" if pd.notna(x) and x < 0 else f"{x:.2f}" if pd.notna(x) else "" - ) - ) + df_data[col_name] = df_data[col_name].apply(lambda x: "-" if pd.notna(x) and x < 0 else f"{x:.2f}" if pd.notna(x) else "") if "compass" in columns: - df_data.iloc[:, columns.index("compass") - 2] = ( - df_data.iloc[:, columns.index("compass") - 2].astype(float) - ).apply(lambda x: f"{x:.1f}") + df_data.iloc[:, columns.index("compass") - 2] = (df_data.iloc[:, columns.index("compass") - 2].astype(float)).apply(lambda x: f"{x:.1f}") if "clino" in columns: - df_data.iloc[:, columns.index("clino") - 2] = ( - df_data.iloc[:, columns.index("clino") - 2].astype(float) - ).apply(lambda x: f"{x:.1f}") + df_data.iloc[:, columns.index("clino") - 2] = (df_data.iloc[:, columns.index("clino") - 2].astype(float)).apply(lambda x: f"{x:.1f}") if "from" in columns: - df_data.iloc[:, columns.index("from") - 2] = ( - df_data.iloc[:, columns.index("from") - 2].astype(str).stationName() - ) + df_data.iloc[:, columns.index("from") - 2] = df_data.iloc[:, columns.index("from") - 2].astype(str).stationName() if "to" in columns: - df_data.iloc[:, columns.index("to") - 2] = ( - df_data.iloc[:, columns.index("to") - 2].astype(str).stationName() - ) + df_data.iloc[:, columns.index("to") - 2] = df_data.iloc[:, columns.index("to") - 2].astype(str).stationName() # Remplacer les NaN par des espaces après transformation df_data = df_data.fillna(" ") # Ajouter un '# ' au début de la colonne 9 (si non vide) - df_data.iloc[:, 9] = df_data.iloc[:, 9].apply( - lambda x: f"# {x}" if str(x).strip() and str(x) != " " else x - ) + df_data.iloc[:, 9] = df_data.iloc[:, 9].apply(lambda x: f"# {x}" if str(x).strip() and str(x) != " " else x) # Ajouter "_hab" à la colonne 2 si FROM == TO - df_data.iloc[:, 1] = df_data.apply( - lambda row: ( - f"{row.iloc[1]}_hab" - if str(row.iloc[0]).strip() == str(row.iloc[1]).strip() - else row.iloc[1] - ), - axis=1, - ) + df_data.iloc[:, 1] = df_data.apply(lambda row: f"{row.iloc[1]}_hab" if str(row.iloc[0]).strip() == str(row.iloc[1]).strip() else row.iloc[1], axis=1) # Gestion des flags surface et not surface new_rows = [] @@ -896,9 +732,7 @@ def formated_station_list(df, dataFormat, unit="meter", shortCurentFile="None"): not_surface_row = [" "] * len(row) not_surface_row[0] = "# flags not exclude from plot no implemented" new_rows.append(not_surface_row) - log.warning( - f"Flags exclude from plot #|P# not implemented in therion, line {Colors.ENDC}{idx + 1}{Colors.WARNING} in {Colors.ENDC}{shortCurentFile}" - ) + log.warning(f"Flags exclude from plot #|P# not implemented in therion, line {Colors.ENDC}{idx + 1}{Colors.WARNING} in {Colors.ENDC}{shortCurentFile}") # Si la colonne 10 contient #|C# exclude from closure elif "#|C#" in col10: @@ -911,9 +745,7 @@ def formated_station_list(df, dataFormat, unit="meter", shortCurentFile="None"): not_surface_row = [" "] * len(row) not_surface_row[0] = "# flags not exclude from closure no implemented" new_rows.append(not_surface_row) - log.warning( - f"Flags #|C# exclude from closure not implemented in therion, line {Colors.ENDC}{idx + 1}{Colors.WARNING} in {Colors.ENDC}{shortCurentFile}" - ) + log.warning(f"Flags #|C# exclude from closure not implemented in therion, line {Colors.ENDC}{idx + 1}{Colors.WARNING} in {Colors.ENDC}{shortCurentFile}") # Si la colonne 10 contient #|PL# exclude from plotting and Length ( i.e converti en splay) elif "#|PL#" in col10 or "#|LP#" in col10: @@ -975,47 +807,29 @@ def formated_station_list(df, dataFormat, unit="meter", shortCurentFile="None"): else: new_rows.append(row.tolist()) - prev_row = row # Garder trace de la ligne précédente + # prev_row = row # Garder trace de la ligne précédente cleaned_rows = [] i = 0 while i < len(new_rows): current = new_rows[i] - if ( + if i + 1 < len(new_rows) and str(current[0]).strip() == "flags not surface" and str(new_rows[i + 1][0]).strip() == "flags surface": # noqa: SIM114 + i += 2 + elif i + 1 < len(new_rows) and str(current[0]).strip() == "flags not splay" and str(new_rows[i + 1][0]).strip() == "flags splay": # noqa: SIM114 + i += 2 + elif i + 1 < len(new_rows) and str(current[0]).strip() == "flags not duplicate" and str(new_rows[i + 1][0]).strip() == "flags duplicate": # noqa: SIM114 + i += 2 + elif ( # noqa: SIM114 i + 1 < len(new_rows) - and str(current[0]).strip() == "flags not surface" - and str(new_rows[i + 1][0]).strip() == "flags surface" + and str(current[0]).strip() == "# flags not exclude from closure no implemented" + and str(new_rows[i + 1][0]).strip() == "# flags exclude from closure no implemented" ): i += 2 elif ( i + 1 < len(new_rows) - and str(current[0]).strip() == "flags not splay" - and str(new_rows[i + 1][0]).strip() == "flags splay" - ): - i += 2 - elif ( - i + 1 < len(new_rows) - and str(current[0]).strip() == "flags not duplicate" - and str(new_rows[i + 1][0]).strip() == "flags duplicate" - ): - i += 2 - elif ( - i + 1 < len(new_rows) - and str(current[0]).strip() - == "# flags not exclude from closure no implemented" - and str(new_rows[i + 1][0]).strip() - == "# flags exclude from closure no implemented" - ): - i += 2 - elif ( - i + 1 < len(new_rows) - and str(current[0]).strip() - == "# flags not exclude from plot no implemented" - and str(new_rows[i + 1][0]).strip() - == "# flags exclude from plot no implemented" - ): - i += 2 - elif ( + and str(current[0]).strip() == "# flags not exclude from plot no implemented" + and str(new_rows[i + 1][0]).strip() == "# flags exclude from plot no implemented" + ) or ( i + 1 < len(new_rows) and str(current[0]).strip() == "# flags not unknown no implemented" and str(new_rows[i + 1][0]).strip() == "# flags unknown no implemented" @@ -1040,10 +854,10 @@ def formated_station_list(df, dataFormat, unit="meter", shortCurentFile="None"): if str(i) == " ": row_str += "" elif str(i).startswith("#") or flag == True: - row_str += f" {str(i)}" + row_str += f" {str(i)}" # noqa: RUF010 flag = True else: - row_str += f"\t{str(i)}" + row_str += f"\t{str(i)}" # noqa: RUF010 output.append(row_str) return "\n".join(output) @@ -1075,9 +889,7 @@ def find_duplicates_by_date_and_team(data): # Construire un mapping ID -> stations id_to_entry = {entry["ID"]: entry for entry in entries} - id_to_stations = { - entry["ID"]: set(entry["STATION"].iloc[:, 0]) for entry in entries - } + id_to_stations = {entry["ID"]: set(entry["STATION"].iloc[:, 0]) for entry in entries} # Construire les connexions directes (graphe implicite) adjacency = defaultdict(set) @@ -1094,10 +906,10 @@ def find_duplicates_by_date_and_team(data): visited = set() def dfs(node, component): - visited.add(node) + visited.add(node) # noqa: B023 component.append(node) - for neighbor in adjacency[node]: - if neighbor not in visited: + for neighbor in adjacency[node]: # noqa: B023 + if neighbor not in visited: # noqa: B023 dfs(neighbor, component) for id_ in ids: @@ -1109,20 +921,10 @@ def find_duplicates_by_date_and_team(data): stations_union = set() for i in range(len(component)): for j in range(i + 1, len(component)): - common = ( - id_to_stations[component[i]] - & id_to_stations[component[j]] - ) + common = id_to_stations[component[i]] & id_to_stations[component[j]] stations_union.update(common) - duplicates.append( - { - "SURVEY_DATE": key[0], - "SURVEY_TEAM": key[1], - "IDS": sorted(component), - "COMMON_STATIONS": sorted(stations_union), - } - ) + duplicates.append({"SURVEY_DATE": key[0], "SURVEY_TEAM": key[1], "IDS": sorted(component), "COMMON_STATIONS": sorted(stations_union)}) return duplicates @@ -1153,9 +955,7 @@ def find_duplicates_by_date(data): # Construire un mapping ID -> stations id_to_entry = {entry["ID"]: entry for entry in entries} - id_to_stations = { - entry["ID"]: set(entry["STATION"].iloc[:, 0]) for entry in entries - } + id_to_stations = {entry["ID"]: set(entry["STATION"].iloc[:, 0]) for entry in entries} # Construire les connexions directes (graphe implicite) adjacency = defaultdict(set) @@ -1172,10 +972,10 @@ def find_duplicates_by_date(data): visited = set() def dfs(node, component): - visited.add(node) + visited.add(node) # noqa: B023 component.append(node) - for neighbor in adjacency[node]: - if neighbor not in visited: + for neighbor in adjacency[node]: # noqa: B023 + if neighbor not in visited: # noqa: B023 dfs(neighbor, component) for id_ in ids: @@ -1187,22 +987,14 @@ def find_duplicates_by_date(data): stations_union = set() for i in range(len(component)): for j in range(i + 1, len(component)): - common = ( - id_to_stations[component[i]] - & id_to_stations[component[j]] - ) + common = id_to_stations[component[i]] & id_to_stations[component[j]] stations_union.update(common) # Utiliser le SURVEY_TEAM de la première occurrence first_entry = id_to_entry[component[0]] duplicates.append( - { - "SURVEY_DATE": survey_date, - "SURVEY_TEAM": first_entry["SURVEY_TEAM"], - "IDS": sorted(component), - "COMMON_STATIONS": sorted(stations_union), - } + {"SURVEY_DATE": survey_date, "SURVEY_TEAM": first_entry["SURVEY_TEAM"], "IDS": sorted(component), "COMMON_STATIONS": sorted(stations_union)} ) return duplicates @@ -1285,13 +1077,7 @@ def merge_duplicate_surveys(data, duplicates, id_offset=10000): } # Liste des champs texte simples à hériter (on peut affiner selon stratégie souhaitée) - text_fields = [ - "SURVEY_TITLE", - "COMMENT", - "DECLINATION", - "FORMAT", - "CORRECTIONS", - ] + text_fields = ["SURVEY_TITLE", "COMMENT", "DECLINATION", "FORMAT", "CORRECTIONS"] # Regrouper les valeurs pour tous les champs à fusionner text_values = {field: set() for field in text_fields} @@ -1370,9 +1156,7 @@ def merge_duplicate_surveys(data, duplicates, id_offset=10000): ################################################################################################# -def dat_survey_format_extract( - section_data, headerData, currentSurveyName, fichier, totReadMeError -): +def dat_survey_format_extract(section_data, headerData, currentSurveyName, fichier, totReadMeError): """Extracts and validates the format code from the section data. Args: @@ -1387,20 +1171,10 @@ def dat_survey_format_extract( """ - if ( - section_data["FORMAT"] is None - or len(section_data["FORMAT"]) < 11 - or len(section_data["FORMAT"]) > 15 - ): - log.error( - f"Error in format code {Colors.ENDC}{section_data['FORMAT']}{Colors.ERROR} in {Colors.ENDC}{currentSurveyName}" - ) - log.debug( - f"Error in format code SURVEY_NAME {Colors.ENDC}{section_data['SURVEY_NAME']}" - ) - log.debug( - f"Error in format code SURVEY_DATE {Colors.ENDC}{section_data['SURVEY_DATE']}" - ) + if section_data["FORMAT"] is None or len(section_data["FORMAT"]) < 11 or len(section_data["FORMAT"]) > 15: + log.error(f"Error in format code {Colors.ENDC}{section_data['FORMAT']}{Colors.ERROR} in {Colors.ENDC}{currentSurveyName}") + log.debug(f"Error in format code SURVEY_NAME {Colors.ENDC}{section_data['SURVEY_NAME']}") + log.debug(f"Error in format code SURVEY_DATE {Colors.ENDC}{section_data['SURVEY_DATE']}") log.debug(f"SURVEY TITLE: {Colors.ENDC}{section_data['SURVEY_TITLE']}") log.debug(f"COMMENT: {Colors.ENDC}{section_data['COMMENT']}") log.debug(f"SURVEY TEAM: {Colors.ENDC}{section_data['SURVEY_TEAM']}") @@ -1412,9 +1186,7 @@ def dat_survey_format_extract( log.debug(f"STATION: {Colors.ENDC}{(section_data['STATION'])}") log.debug(f"SOURCE: {Colors.ENDC}{section_data['SOURCE']}\n") globalData.error_count += 1 - totReadMeError += ( - f"\tError in format code {section_data['FORMAT']} in {currentSurveyName}\n" - ) + totReadMeError += f"\tError in format code {section_data['FORMAT']} in {currentSurveyName}\n" def Dimension(string=""): directions = {"U": " up", "D": " down", "R": " right", "L": " left"} @@ -1424,14 +1196,14 @@ def dat_survey_format_extract( log.error( f"Error in format str {Colors.ENDC}{string}{Colors.ERROR} code {Colors.ENDC}{section_data['FORMAT']}{Colors.ERROR} in {Colors.ENDC}{fichier}{Colors.ERROR} in {Colors.ENDC}{currentSurveyName}" ) - totReadMeError += f"\tError in format str {string} code {section_data['FORMAT']} in {fichier} in {currentSurveyName}\n" + # totReadMeError += f"\tError in format str {string} code {section_data['FORMAT']} in {fichier} in {currentSurveyName}\n" globalData.error_count += 1 return "" def LRUD_association(string=""): # In Therion the standard LRUD association is the shot and not the station # LRUD Association: F=From Station, T=To Station - if string == "F": + if string == "F": # noqa: SIM114 return "" elif string == "T": return "" @@ -1439,17 +1211,13 @@ def dat_survey_format_extract( log.error( f"Error in format str {Colors.ENDC}{string}{Colors.ERROR} code {Colors.ENDC}{section_data['FORMAT']}{Colors.ERROR} in {Colors.ENDC}{fichier}{Colors.ERROR} in {Colors.ENDC}{currentSurveyName}" ) - totReadMeError += f"\tError in format str {string} code {section_data['FORMAT']} in {fichier} in {currentSurveyName}\n" + # totReadMeError += f"\tError in format str {string} code {section_data['FORMAT']} in {fichier} in {currentSurveyName}\n" globalData.error_count += 1 return "" - def Backsight( - string="", - ): # Backsight: B=Redundant, N or empty=No Redundant Backsights. + def Backsight(string=""): # Backsight: B=Redundant, N or empty=No Redundant Backsights. if string == "B": - log.error( - f"Backsight unit not yet implemented {Colors.ENDC}{section_data['FORMAT']}{Colors.ERROR} in {Colors.ENDC}{currentSurveyName}" - ) + log.error(f"Backsight unit not yet implemented {Colors.ENDC}{section_data['FORMAT']}{Colors.ERROR} in {Colors.ENDC}{currentSurveyName}") totReadMeError += f"\tBacksight unit not yet implemented {Colors.ENDC}{section_data['FORMAT']}{Colors.ERROR} in {Colors.ENDC}{currentSurveyName}\n" globalData.error_count += 1 return "" @@ -1481,7 +1249,7 @@ def dat_survey_format_extract( log.error( f"Error in format str {Colors.ENDC}{string}{Colors.ERROR} code {Colors.ENDC}{section_data['FORMAT']}{Colors.ERROR} in {Colors.ENDC}{fichier}{Colors.ERROR} in {Colors.ENDC}{currentSurveyName}" ) - totReadMeError += f"\tError in format str {string} code {section_data['FORMAT']} in {fichier} in {currentSurveyName}\n" + # totReadMeError += f"\tError in format str {string} code {section_data['FORMAT']} in {fichier} in {currentSurveyName}\n" globalData.error_count += 1 return "" @@ -1494,9 +1262,7 @@ def dat_survey_format_extract( compass = "compass grads" else: compass = "Compass_error" - log.error( - f"Compass bearing unit 'quads' not yet implemented in {Colors.ENDC}{currentSurveyName}" - ) + log.error(f"Compass bearing unit 'quads' not yet implemented in {Colors.ENDC}{currentSurveyName}") globalData.error_count += 1 totReadMeError += f"\tCompass bearing unit 'quads' not yet implemented in survey {currentSurveyName}\n" @@ -1506,9 +1272,7 @@ def dat_survey_format_extract( length = "length meter" else: length = "Length_error" - log.error( - f"Length unit 'Feet and Inches' not yet implemented in {Colors.ENDC}{currentSurveyName}" - ) + log.error(f"Length unit 'Feet and Inches' not yet implemented in {Colors.ENDC}{currentSurveyName}") globalData.error_count += 1 totReadMeError += f"\tLength unit 'Feet and Inches' not yet implemented in {currentSurveyName}\n" @@ -1523,13 +1287,9 @@ def dat_survey_format_extract( type_Data = "normal" # Depth Gauge else: clino = "Inclination_error" - log.error( - f"Inclination unit not yet implemented in {Colors.ENDC}{currentSurveyName}" - ) + log.error(f"Inclination unit not yet implemented in {Colors.ENDC}{currentSurveyName}") globalData.error_count += 1 - totReadMeError += ( - f"\tInclination unit not yet implemented in {currentSurveyName}\n" - ) + totReadMeError += f"\tInclination unit not yet implemented in {currentSurveyName}\n" ################################################ Section dimensions 4-7 ############################################### dataFormat = " " + headerData[5].lower() @@ -1538,16 +1298,10 @@ def dat_survey_format_extract( dataFormat += " " + headerData[8].lower() ################################################ Section Shot 8-11 ou 13 ############################################### - if ( - len(section_data["FORMAT"]) == 11 - or len(section_data["FORMAT"]) == 12 - or len(section_data["FORMAT"]) == 13 - ): + if len(section_data["FORMAT"]) == 11 or len(section_data["FORMAT"]) == 12 or len(section_data["FORMAT"]) == 13: if len(section_data["FORMAT"]) == 13: # UUUUDDDDSSSBL dataFormat = LRUD_association(section_data["FORMAT"][12]) + dataFormat - dataFormat = ( - Backsight(section_data["FORMAT"][11]) + dataFormat - ) # UUUUDDDDSSSB + dataFormat = Backsight(section_data["FORMAT"][11]) + dataFormat # UUUUDDDDSSSB elif len(section_data["FORMAT"]) == 12: dataFormat = Backsight(section_data["FORMAT"][11]) + dataFormat dataFormat = ShotOrder(section_data["FORMAT"][10]) + dataFormat @@ -1571,18 +1325,7 @@ def dat_survey_format_extract( ################################################################################################# # Convertit un fichier .tro en fichiers .th # ################################################################################################# -def tro_to_th_files( - ENTRY_FILE, - centerlines=[], - entrance="", - fileTitle="", - coordinates=[], - coordsyst="", - fle_th_fnme="", - CONFIG_PATH="", - totReadMeError="", - bar=None, -): +def tro_to_th_files(ENTRY_FILE, centerlines=[], entrance="", fileTitle="", coordinates=[], coordsyst="", fle_th_fnme="", CONFIG_PATH="", totReadMeError="", bar=None): # noqa: B006 """ Convertit un fichier .tro en fichiers .th @@ -1600,9 +1343,9 @@ def tro_to_th_files( ################################################################################################# # 1 : Initialisations # ################################################################################################# - data = [] - unique_id = 1 - totdata = f"\t## Input list:\n" + # data = [] + # unique_id = 1 + totdata = "\t## Input list:\n" totMapsPlan = "" totMapsExtended = "" totReadMeErrorDat = "" @@ -1619,9 +1362,7 @@ def tro_to_th_files( fixPoints = [] fixPoints.append([entrance, " ", coordinates[0], coordinates[1], coordinates[2]]) - log.debug( - f"{Colors.INFO}------------------------------------------------------------------------------------------------------------------{Colors.ENDC}" - ) + log.debug(f"{Colors.INFO}------------------------------------------------------------------------------------------------------------------{Colors.ENDC}") SurveyTitle = sanitize_filename(os.path.basename(ENTRY_FILE)[:-4]) folderDest = os.path.dirname(ENTRY_FILE) + "\\" + SurveyTitle @@ -1632,12 +1373,8 @@ def tro_to_th_files( # 2 : Boucle pour convertir les centerlines # ################################################################################################# - for i, cl in enumerate( - sorted(centerlines, key=lambda x: (x["date"] is None, x["date"])), start=1 - ): - currentSurveyName = ( - f"{globalData.SurveyPrefixName}{i:02d}_{sanitize_filename(cl['date'])}" - ) + for i, cl in enumerate(sorted(centerlines, key=lambda x: (x["date"] is None, x["date"])), start=1): + currentSurveyName = f"{globalData.SurveyPrefixName}{i:02d}_{sanitize_filename(cl['date'])}" fileName = folderDest + "\\Data\\" + currentSurveyName + ".th" log.debug(f"{Colors.INFO}Centerline # {Colors.ENDC}{i}") @@ -1646,8 +1383,8 @@ def tro_to_th_files( log.debug(f"{Colors.INFO}Lignes :{Colors.ENDC}") add_lines = "\nencoding utf-8\n" - add_lines += f"# File generated by pyCreateTh.py version: {globalData.Version} date: {datetime.now().strftime('%Y.%m.%d %H:%M:%S')}\n" - add_lines += f'\nsurvey {globalData.SurveyPrefixName}{i:02d}_{sanitize_filename(cl["date"])} -title "{fileTitle} Explo num {i:02d}"' + add_lines += f"# File generated by pyCreateTh.py version: {globalData.Version} date: {datetime.now().strftime('%Y.%m.%d %H:%M:%S')}\n" # noqa: DTZ005 + add_lines += f'\nsurvey {globalData.SurveyPrefixName}{i:02d}_{sanitize_filename(cl["date"])} -title "{fileTitle} Explo {i:03d}"' cl["lines"] = [add_lines] + cl["lines"] + ["endsurvey"] @@ -1658,38 +1395,24 @@ def tro_to_th_files( log.debug(line) f.write(f"{line}\n") - f.write( - f"\n\n#############################################################################################" - ) + f.write("\n\n#############################################################################################") f.write(f"\n# Originals data file : {args.file}") if globalData.error_count == 0: - f.write( - f"\n# Conversion with pyCreateTh version {globalData.Version}, the {datetime.now().strftime('%Y.%m.%d %H:%M:%S')}, without error" - ) + f.write(f"\n# Conversion with pyCreateTh version {globalData.Version}, the {datetime.now().strftime('%Y.%m.%d %H:%M:%S')}, without error") # noqa: DTZ005 else: f.write( - f"\n# Conversion with pyCreateTh version {globalData.Version}, the {datetime.now().strftime('%Y.%m.%d %H:%M:%S')}, with {globalData.error_count} error(s)" + f"\n# Conversion with pyCreateTh version {globalData.Version}, the {datetime.now().strftime('%Y.%m.%d %H:%M:%S')}, with {globalData.error_count} error(s)" # noqa: DTZ005 ) - f.write( - f"\n#############################################################################################\n\n" - ) + f.write("\n#############################################################################################\n\n") for line in source_content.splitlines(): f.write(f"# {line}\n") - log.debug( - f"{Colors.INFO}------------------------------------------------------------------------------------------------------------------{Colors.ENDC}" - ) + log.debug(f"{Colors.INFO}------------------------------------------------------------------------------------------------------------------{Colors.ENDC}") # Ajouter les données de la section à la liste if len(cl["DATA"]) > 0: - listStationSectionFixed, listStationSection, dfDATA = station_list_th( - cl, - listStationSection, - listStationSectionFixed, - fixPoints, - currentSurveyName, - ) + listStationSectionFixed, listStationSection, dfDATA = station_list_th(cl, listStationSection, listStationSectionFixed, fixPoints, currentSurveyName) # noqa: RUF059 # print(f"Explo {i}, dfDATA : {dfDATA}") # print(listStationSection) @@ -1714,7 +1437,7 @@ def tro_to_th_files( if not StatCreateFolder: totMapsPlan += f"\t{plan}MP-{currentSurveyName}-Plan-tot@{currentSurveyName}\n\t{plan}break\n" totMapsExtended += f"\t{extended}MC-{currentSurveyName}-Extended-tot@{currentSurveyName}\n\t{extended}break\n" - surveyCount += 1 + surveyCount += 1 # noqa: SIM113 totdata += f"\tinput Data/{currentSurveyName}/{currentSurveyName}-tot.th\n" @@ -1734,8 +1457,7 @@ def tro_to_th_files( # Gestion des equates ################################################################################################# - totdata += f"\n" - + totdata += "\n" _stationList = listStationSection.copy() # On numérote les doublons de Survey_Name pour chaque StationName @@ -1744,24 +1466,20 @@ def tro_to_th_files( # print(f"{Colors.DEBUG}_stationList : {Colors.ENDC}{_stationList}") # On pivote le tableau pour que chaque Survey_Name devienne une colonne - tableau_pivot = _stationList.pivot( - index="StationName", columns="Survey_Number", values="Survey_Name_01" - ) + tableau_pivot = _stationList.pivot(index="StationName", columns="Survey_Number", values="Survey_Name_01") tableau_pivot.columns = [f"Survey_Name_{i}" for i in tableau_pivot.columns] # print(f"{Colors.DEBUG}tableau_pivot : {Colors.ENDC}{tableau_pivot}{Colors.DEBUG} in {Colors.ENDC}{currentSurveyName}") - totdata += f"\n\t## equates list:\n" + totdata += "\n\t## equates list:\n" if "Survey_Name_2" in tableau_pivot.columns: # On réinitialise l'index pour avoir StationName comme colonne normale tableau_pivot = tableau_pivot.reset_index() tableau_equate = tableau_pivot[tableau_pivot["Survey_Name_2"].notna()] - log.info( - f"Total 'equates' founds: {Colors.ENDC}{len(tableau_equate)}{Colors.INFO} in {Colors.ENDC}{currentSurveyName}" - ) + log.info(f"Total 'equates' founds: {Colors.ENDC}{len(tableau_equate)}{Colors.INFO} in {Colors.ENDC}{currentSurveyName}") # print(f"{Colors.DEBUG}tableau_equate : {Colors.ENDC}{tableau_equate}") # print(f"{Colors.DEBUG}fixePoints : {Colors.ENDC}{fixPoints}{Colors.DEBUG} in {Colors.ENDC}{currentSurveyName}") @@ -1771,11 +1489,7 @@ def tro_to_th_files( station = row["StationName"] # On récupère tous les Survey_Name non vides (NaN exclus) - surveys = [ - row[col] - for col in tableau_equate.columns - if col.startswith("Survey_Name") and pd.notna(row[col]) - ] + surveys = [row[col] for col in tableau_equate.columns if col.startswith("Survey_Name") and pd.notna(row[col])] # Pour chaque paire unique (i < j), on écrit la ligne 'equate' for i in range(len(surveys)): @@ -1791,9 +1505,7 @@ def tro_to_th_files( for index, row in listStationSectionFixed.iterrows(): # log.info(f"Fixed station : {Colors.ENDC}{row['Station_Fix']}{Colors.INFO}, Survey : {Colors.ENDC}{row['Survey_Name']}") - totReadMeFixPoint += ( - f"\tFixed station : {row['Station_Fix']}, Survey : {row['Survey_Name']}\n" - ) + totReadMeFixPoint += f"\tFixed station : {row['Station_Fix']}, Survey : {row['Survey_Name']}\n" config_vars = { "fileName": SurveyTitle, @@ -1819,7 +1531,7 @@ def tro_to_th_files( "errorList": totReadMeErrorDat, "fixPointList": totReadMeFixPoint, "other_scraps_extended": totMapsExtended, - "file_info": f"# File generated by pyCreateTh.py version: {globalData.Version} date: {datetime.now().strftime('%Y.%m.%d-%H:%M:%S')}", + "file_info": f"# File generated by pyCreateTh.py version: {globalData.Version} date: {datetime.now().strftime('%Y.%m.%d-%H:%M:%S')}", # noqa: DTZ005 } DEST_PATH = os.path.dirname(ENTRY_FILE) + "/" + SurveyTitle @@ -1828,21 +1540,9 @@ def tro_to_th_files( # pprint(config_vars, width=120, depth=2) - update_template_files( - DEST_PATH + "/template.thconfig", - config_vars, - DEST_PATH + "/" + SurveyTitle + ".thconfig", - ) - update_template_files( - DEST_PATH + "/template-tot.th", - config_vars, - DEST_PATH + "/" + SurveyTitle + "-tot.th", - ) - update_template_files( - DEST_PATH + "/template-maps.th", - config_vars, - DEST_PATH + "/" + SurveyTitle + "-maps.th", - ) + update_template_files(DEST_PATH + "/template.thconfig", config_vars, DEST_PATH + "/" + SurveyTitle + ".thconfig") + update_template_files(DEST_PATH + "/template-tot.th", config_vars, DEST_PATH + "/" + SurveyTitle + "-tot.th") + update_template_files(DEST_PATH + "/template-maps.th", config_vars, DEST_PATH + "/" + SurveyTitle + "-maps.th") ################################################################################################# # Final therion compilation # @@ -1858,28 +1558,20 @@ def tro_to_th_files( logfile = (DEST_PATH + "/therion.log").replace("\\", "/") - with open(logfile, "r") as f: - content = f.read() - # print(content) + content = read_text_file(logfile) stat = get_stats_from_log(content) if stat["length"] != 0.0 and stat["depth"] != 0.0: totReadMe += f"\tFinal compilation successful length: {stat['length']} m, depth: {stat['depth']} m\n" - log.info( - f"Final compilation successful length: {Colors.ENDC}{stat['length']}{Colors.INFO} m, depth: {Colors.ENDC}{stat['depth']}{Colors.INFO} m" - ) + log.info(f"Final compilation successful length: {Colors.ENDC}{stat['length']}{Colors.INFO} m, depth: {Colors.ENDC}{stat['depth']}{Colors.INFO} m") else: - totReadMe += f"\tFinal compilation error, check log file\n" - log.error(f"Final compilation error, check log file") + totReadMe += "\tFinal compilation error, check log file\n" + log.error("Final compilation error, check log file") config_vars["readMeList"] = totReadMe - update_template_files( - DEST_PATH + "/template-readme.md", - config_vars, - DEST_PATH + "/" + SurveyTitle + "-readme.md", - ) + update_template_files(DEST_PATH + "/template-readme.md", config_vars, DEST_PATH + "/" + SurveyTitle + "-readme.md") return _stationList, SurveyTitle, totReadMeError, threads @@ -1887,9 +1579,7 @@ def tro_to_th_files( ################################################################################################# # Convertit un fichier .dat en fichiers .th # ################################################################################################# -def dat_to_th_files( - ENTRY_FILE, fixPoints=[], crs_wkt="", CONFIG_PATH="", totReadMeError="", bar=None -): +def dat_to_th_files(ENTRY_FILE, fixPoints=[], crs_wkt="", CONFIG_PATH="", totReadMeError="", bar=None): # noqa: B006 """ Convertit un fichier .dat en fichiers .th @@ -1912,7 +1602,7 @@ def dat_to_th_files( # 1 : Lecture du fichier dat # ################################################################################################# - content, totReadMe, enc = load_text_file_utf8(ENTRY_FILE, shortCurentFile) + content, totReadMe, enc = load_text_file_utf8(ENTRY_FILE, shortCurentFile) # noqa: RUF059 ################################################################################################# # Séparer les sections # @@ -1922,7 +1612,7 @@ def dat_to_th_files( # Listes pour stocker les données data = [] unique_id = 1 - totdata = f"\t## Input list:\n" + totdata = "\t## Input list:\n" totMapsPlan = "" totMapsExtended = "" totReadMeErrorDat = "" @@ -1930,9 +1620,7 @@ def dat_to_th_files( threads = [] # Tableau global pour stocker toutes les stations - stationList = pd.DataFrame( - columns=["StationName", "Survey_Name_01", "Survey_Name_02"] - ) + stationList = pd.DataFrame(columns=["StationName", "Survey_Name_01", "Survey_Name_02"]) stationList_Fixed = pd.DataFrame(columns=["StationName", "Survey_Name"]) section0 = True @@ -2001,9 +1689,7 @@ def dat_to_th_files( line = line.strip() elif line.startswith("SURVEY NAME:"): - section_data["SURVEY_NAME"] = sanitize_filename( - line.split(":", 1)[1].strip() - ) + section_data["SURVEY_NAME"] = sanitize_filename(line.split(":", 1)[1].strip()) elif line.startswith("SURVEY DATE:"): # current_field = 'DATE' @@ -2013,14 +1699,9 @@ def dat_to_th_files( mois, jour, annee = date.split() date_convertie = f"{int(annee):04d} {int(mois):02d} {int(jour):02d}" section_data["SURVEY_DATE"] = date_convertie - if ( - section_data["SURVEY_DATE"] == None - or section_data["SURVEY_DATE"] == "" - ): + if section_data["SURVEY_DATE"] == None or section_data["SURVEY_DATE"] == "": section_data["SURVEY_DATE"] = "2000 01 01" - log.warning( - f"Survey {Colors.ENDC}{section_data['SURVEY_NAME']}{Colors.WARNING} with no date, add default date 2000 01 01 " - ) + log.warning(f"Survey {Colors.ENDC}{section_data['SURVEY_NAME']}{Colors.WARNING} with no date, add default date 2000 01 01 ") if len(date_parts) > 1: section_data["COMMENT"] = date_parts[1].strip() @@ -2051,11 +1732,7 @@ def dat_to_th_files( # Ajouter les données de la section à la liste if len(section_data["DATA"]) > 0: listStationSection_Fixed, listStationSection, dfDATA = station_list_dat( - section_data, - listStationSection, - listStationSection_Fixed, - fixPoints, - section_data["SURVEY_NAME"], + section_data, listStationSection, listStationSection_Fixed, fixPoints, section_data["SURVEY_NAME"] ) section_data["STATION"] = listStationSection section_data["STATION_FIXED"] = listStationSection_Fixed @@ -2093,9 +1770,7 @@ def dat_to_th_files( ) bar(val2) else: - log.info( - f"Read dat file: {Colors.ENDC}{shortCurentFile}{Colors.INFO} with {Colors.ENDC}{len(data)}{Colors.INFO} survey(s)" - ) + log.info(f"Read dat file: {Colors.ENDC}{shortCurentFile}{Colors.INFO} with {Colors.ENDC}{len(data)}{Colors.INFO} survey(s)") ################################################################################################# # Créer le dossier pour les fichiers convertis # @@ -2130,11 +1805,7 @@ def dat_to_th_files( # totReadMe += f"* Source file: {os.path.basename(ENTRY_FILE)}\n" proj = args.proj.lower() - values = { - "none": ("# ", "# ", "# "), - "plan": ("", "", "# "), - "extended": ("", "# ", ""), - } + values = {"none": ("# ", "# ", "# "), "plan": ("", "", "# "), "extended": ("", "# ", "")} maps, plan, extended = values.get(proj, ("", "", "")) @@ -2163,9 +1834,7 @@ def dat_to_th_files( globalData.error_count += 1 if _line["CORRECTIONS2"] != None: - _CorrectionValues3 = [ - float(val) for val in _line["CORRECTIONS2"].strip().split() - ] + _CorrectionValues3 = [float(val) for val in _line["CORRECTIONS2"].strip().split()] if all(val == 0.0 for val in _CorrectionValues): _CorrectionValues3 = "" @@ -2185,24 +1854,17 @@ def dat_to_th_files( discovery = f"{_line['SURVEY_DATE']} # '????'" if _line["PREFIX"] != None: - log.error( - f"PREFIX: {Colors.ENDC}{_line['PREFIX']}, not yet implemented in {Colors.ENDC}{currentSurveyName}" - ) + log.error(f"PREFIX: {Colors.ENDC}{_line['PREFIX']}, not yet implemented in {Colors.ENDC}{currentSurveyName}") totReadMeError += f"\tPREFIX: {_line['PREFIX']}, not yet implemented in {currentSurveyName}\n" globalData.error_count += 1 - SurveyNameCount = { - "surveyCount": f"{currentSurveyName}", - "SURVEY_NAME": _line["SURVEY_NAME"], - } + SurveyNameCount = {"surveyCount": f"{currentSurveyName}", "SURVEY_NAME": _line["SURVEY_NAME"]} # noqa: F841 ################################################################################################# # gestion des DATA # ################################################################################################# - stationList_Fixed, stationList, dfDATA = station_list_dat( - _line, stationList, stationList_Fixed, fixPoints, currentSurveyName - ) + stationList_Fixed, stationList, dfDATA = station_list_dat(_line, stationList, stationList_Fixed, fixPoints, currentSurveyName) headerData = dfDATA.iloc[0].tolist() @@ -2237,11 +1899,7 @@ def dat_to_th_files( # Gestion des formats ################################################################################################# - dataFormat, length, compass, clino, totReadMeErrorDat = ( - dat_survey_format_extract( - _line, headerData, currentSurveyName, shortCurentFile, totReadMeErrorDat - ) - ) + dataFormat, length, compass, clino, totReadMeErrorDat = dat_survey_format_extract(_line, headerData, currentSurveyName, shortCurentFile, totReadMeErrorDat) if "grads" in compass: _compass = "grads" @@ -2256,7 +1914,7 @@ def dat_to_th_files( f.write( globalData.thFileDat.format( VERSION=globalData.Version, - DATE=datetime.now().strftime("%Y.%m.%d-%H:%M:%S"), + DATE=datetime.now().strftime("%Y.%m.%d-%H:%M:%S"), # noqa: DTZ005 # SURVEY_NAME = sanitize_filename(_line['SURVEY_NAME']), SURVEY_NAME=f"{currentSurveyName}", SURVEY_TITLE=_line["SURVEY_NAME"].replace("_", " "), @@ -2268,31 +1926,19 @@ def dat_to_th_files( CLINO=clino, DATA_FORMAT=dataFormat, CORRECTIONS=_corrections, - DECLINATION=f"\t\tdeclination {_line['DECLINATION']} {_compass}\n" - if (crs_wkt == "" and _line["DECLINATION"] != 0.0) - else "", - DATA=formated_station_list( - dfDATA, dataFormat, length, shortCurentFile - ), - COMMENT=sanitize_filename( - _line["SURVEY_NAME"] + " " + _line["COMMENT"] - ) - .replace('"', "'") - .replace("_", " "), + DECLINATION=f"\t\tdeclination {_line['DECLINATION']} {_compass}\n" if (crs_wkt == "" and _line["DECLINATION"] != 0.0) else "", + DATA=formated_station_list(dfDATA, dataFormat, length, shortCurentFile), + COMMENT=sanitize_filename(_line["SURVEY_NAME"] + " " + _line["COMMENT"]).replace('"', "'").replace("_", " "), FIX_POINTS=fixPoint, EXPLO_DATE=discovery, EXPLO_TEAM=f"{_line['SURVEY_TEAM']} # '????'", - SOURCE="\n".join( - "# " + line for line in _line["SOURCE"].splitlines() - ), + SOURCE="\n".join("# " + line for line in _line["SOURCE"].splitlines()), ) ) totdata += f"\tinput Data/{currentSurveyName}/{currentSurveyName}-tot.th\n" - log.info( - f"Therion file : {Colors.ENDC}{safe_relpath(output_file)}{Colors.GREEN} created from {Colors.ENDC}{os.path.basename(ENTRY_FILE)}" - ) + log.info(f"Therion file : {Colors.ENDC}{safe_relpath(output_file)}{Colors.GREEN} created from {Colors.ENDC}{os.path.basename(ENTRY_FILE)}") ################################################################################################# # Création des dossiers @@ -2337,9 +1983,7 @@ def dat_to_th_files( f"{Colors.INFO}file: {Colors.ENDC}{os.path.basename(ENTRY_FILE)[:-4]}{Colors.INFO}, survey: {Colors.ENDC}{currentSurveyName}{Colors.ERROR}, error: {Colors.ENDC}{globalData.error_count}" ) else: - bar.text( - f"{Colors.INFO}file: {Colors.ENDC}{os.path.basename(ENTRY_FILE)[:-4]}{Colors.INFO}, survey: {Colors.ENDC}{currentSurveyName}" - ) + bar.text(f"{Colors.INFO}file: {Colors.ENDC}{os.path.basename(ENTRY_FILE)[:-4]}{Colors.INFO}, survey: {Colors.ENDC}{currentSurveyName}") bar() ################################################################################################# @@ -2350,7 +1994,7 @@ def dat_to_th_files( # Gestion des equates ################################################################################################# - totdata += f"\n" + totdata += "\n" _stationList = stationList.copy() @@ -2360,24 +2004,20 @@ def dat_to_th_files( # print(_stationList) # On pivote le tableau pour que chaque Survey_Name devienne une colonne - tableau_pivot = _stationList.pivot( - index="StationName", columns="Survey_Number", values="Survey_Name_01" - ) + tableau_pivot = _stationList.pivot(index="StationName", columns="Survey_Number", values="Survey_Name_01") tableau_pivot.columns = [f"Survey_Name_{i}" for i in tableau_pivot.columns] # print(f"tableau_pivot: {Colors.ENDC}{tableau_pivot}{Colors.INFO} in {Colors.ENDC}{ENTRY_FILE}") - totdata += f"\n\t## equates list:\n" + totdata += "\n\t## equates list:\n" if "Survey_Name_2" in tableau_pivot.columns: # On réinitialise l'index pour avoir StationName comme colonne normale tableau_pivot = tableau_pivot.reset_index() tableau_equate = tableau_pivot[tableau_pivot["Survey_Name_2"].notna()] - log.info( - f"Total '{Colors.ENDC}equates{Colors.INFO}' founds : {Colors.ENDC}{len(tableau_equate)}{Colors.INFO} in {Colors.ENDC}{shortCurentFile}" - ) + log.info(f"Total '{Colors.ENDC}equates{Colors.INFO}' founds : {Colors.ENDC}{len(tableau_equate)}{Colors.INFO} in {Colors.ENDC}{shortCurentFile}") # print(tableau_equate) # print(f"fixePoints : {Colors.ENDC}{fixed_names}{Colors.INFO} in {Colors.ENDC}{ENTRY_FILE}") @@ -2386,20 +2026,14 @@ def dat_to_th_files( station = row["StationName"] # On récupère tous les Survey_Name non vides (NaN exclus) - surveys = [ - row[col] - for col in tableau_equate.columns - if col.startswith("Survey_Name") and pd.notna(row[col]) - ] + surveys = [row[col] for col in tableau_equate.columns if col.startswith("Survey_Name") and pd.notna(row[col])] # Pour chaque paire unique (i < j), on écrit la ligne 'equate' for i in range(len(surveys)): for j in range(i + 1, len(surveys)): totdata += f"\tequate {station}@{surveys[i]}.{surveys[i]} {station}@{surveys[j]}.{surveys[j]}\n" else: - log.info( - f"No '{Colors.ENDC}equates{Colors.INFO}' found in {Colors.ENDC}{ENTRY_FILE}" - ) + log.info(f"No '{Colors.ENDC}equates{Colors.INFO}' found in {Colors.ENDC}{ENTRY_FILE}") totdata += f"\n\t## Maps list:\n\t{maps}input {SurveyTitle}-maps.th\n" @@ -2410,9 +2044,7 @@ def dat_to_th_files( for index, row in stationList_Fixed.iterrows(): # log.info(f"Fixed station: {Colors.ENDC}{row['Station_Fix']}{Colors.INFO}, survey: {Colors.ENDC}{row['Survey_Name']}") - totReadMeFixPoint += ( - f"\tFixed station: {row['Station_Fix']}, Survey: {row['Survey_Name']}\n" - ) + totReadMeFixPoint += f"\tFixed station: {row['Station_Fix']}, Survey: {row['Survey_Name']}\n" config_vars = { "fileName": SurveyTitle, @@ -2438,26 +2070,14 @@ def dat_to_th_files( "errorList": totReadMeErrorDat, "fixPointList": totReadMeFixPoint, "other_scraps_extended": totMapsExtended, - "file_info": f"# File generated by pyCreateTh.py version: {globalData.Version} date: {datetime.now().strftime('%Y.%m.%d-%H:%M:%S')}", + "file_info": f"# File generated by pyCreateTh.py version: {globalData.Version} date: {datetime.now().strftime('%Y.%m.%d-%H:%M:%S')}", # noqa: DTZ005 } DEST_PATH = os.path.dirname(ENTRY_FILE) + "/" + SurveyTitle - update_template_files( - DEST_PATH + "/template.thconfig", - config_vars, - DEST_PATH + "/" + SurveyTitle + ".thconfig", - ) - update_template_files( - DEST_PATH + "/template-tot.th", - config_vars, - DEST_PATH + "/" + SurveyTitle + "-tot.th", - ) - update_template_files( - DEST_PATH + "/template-maps.th", - config_vars, - DEST_PATH + "/" + SurveyTitle + "-maps.th", - ) + update_template_files(DEST_PATH + "/template.thconfig", config_vars, DEST_PATH + "/" + SurveyTitle + ".thconfig") + update_template_files(DEST_PATH + "/template-tot.th", config_vars, DEST_PATH + "/" + SurveyTitle + "-tot.th") + update_template_files(DEST_PATH + "/template-maps.th", config_vars, DEST_PATH + "/" + SurveyTitle + "-maps.th") ################################################################################################# # Final therion compilation # @@ -2481,20 +2101,14 @@ def dat_to_th_files( if stat["length"] != 0.0 and stat["depth"] != 0.0: totReadMe += f"\tFinal compilation successful length: {stat['length']} m, depth: {stat['depth']} m\n" - log.info( - f"Final compilation successful length: {Colors.ENDC}{stat['length']}{Colors.INFO} m, depth: {Colors.ENDC}{stat['depth']}{Colors.INFO} m" - ) + log.info(f"Final compilation successful length: {Colors.ENDC}{stat['length']}{Colors.INFO} m, depth: {Colors.ENDC}{stat['depth']}{Colors.INFO} m") else: - totReadMe += f"\tFinal compilation error, check log file\n" - log.error(f"Final compilation error, check log file") + totReadMe += "\tFinal compilation error, check log file\n" + log.error("Final compilation error, check log file") config_vars["readMeList"] = totReadMe - update_template_files( - DEST_PATH + "/template-readme.md", - config_vars, - DEST_PATH + "/" + SurveyTitle + "-readme.md", - ) + update_template_files(DEST_PATH + "/template-readme.md", config_vars, DEST_PATH + "/" + SurveyTitle + "-readme.md") stationList["Survey_Name_02"] = SurveyTitle @@ -2524,9 +2138,7 @@ def wait_until_file_is_released(filepath, timeout=30): except PermissionError: if time.time() - start > timeout: - log.Error( - f"Timeout: The file remains locked after {Colors.ENDC}{timeout}{Colors.ERROR} secondes: {Colors.ENDC}{filepath}" - ) + log.Error(f"Timeout: The file remains locked after {Colors.ENDC}{timeout}{Colors.ERROR} secondes: {Colors.ENDC}{filepath}") time.sleep(0.1) # attend 100 ms @@ -2534,7 +2146,7 @@ def wait_until_file_is_released(filepath, timeout=30): # main function # ################################################################################################# if __name__ == "__main__": - start_time = datetime.now() + start_time = datetime.now() # noqa: DTZ005 threads = [] fileTitle = "" _fileTitle = "" @@ -2548,22 +2160,9 @@ if __name__ == "__main__": formatter_class=argparse.RawDescriptionHelpFormatter, ) parser.print_help = colored_help.__get__(parser) - parser.add_argument( - "--file", - help="the file (*.th, *.mak, *.dat, *.tro) to perform e.g. './Therion_file.th'", - default="", - ) - parser.add_argument( - "--proj", - choices=["All", "Plan", "Extended", "None"], - help="the th2 files scrap projection to produce, default: All", - default="All", - ) - parser.add_argument( - "--scale", - help="scale for the pdf layout exports, default value: 1000 (i.e. xvi files scale is 100)", - default="1000", - ) + parser.add_argument("--file", help="the file (*.th, *.mak, *.dat, *.tro) to perform e.g. './Therion_file.th'", default="") + parser.add_argument("--proj", choices=["All", "Plan", "Extended", "None"], help="the th2 files scrap projection to produce, default: All", default="All") + parser.add_argument("--scale", help="scale for the pdf layout exports, default value: 1000 (i.e. xvi files scale is 100)", default="1000") parser.add_argument( "--update", help=f"th2 files update mode (only for th input files, no folders created), {Colors.RED}attention : save your old th2 files", @@ -2595,7 +2194,7 @@ if __name__ == "__main__": # print(f"Selected file : {args.file}") output_log = splitext(abspath(args.file))[0] + ".log" - log = setup_logger(output_log, debug_log) + log = setup_logger(output_log, globalData.debug_log) # log.debug("Ceci est un message de debug") # log.info("Tout va bien") @@ -2625,9 +2224,7 @@ if __name__ == "__main__": def pad_line(texte, center=False): # Supprimer les séquences ANSI pour le calcul de longueur visuelle visible_len = len(ansi_escape.sub("", texte)) - espace_total = ( - titre_largeur - visible_len - 2 - ) # 2 pour les * à gauche et droite + espace_total = titre_largeur - visible_len - 2 # 2 pour les * à gauche et droite if center: left = espace_total // 2 @@ -2638,20 +2235,13 @@ if __name__ == "__main__": _titre = [ bordure, - pad_line( - f"{Colors.BOLD}{Colors.YELLOW}Files conversion th, dat, mak, tro and trox to therion files and folders", - center=True, - ), + pad_line(f"{Colors.BOLD}{Colors.YELLOW}Files conversion th, dat, mak, tro and trox to therion files and folders", center=True), pad_line(f"Script pyCreateTh by : {Colors.BLUE}alexandre.pont@yahoo.fr"), pad_line(f"Version : {Colors.ENDC}{globalData.Version}"), pad_line(f"Input file : {Colors.ENDC}{safe_relpath(args.file)}"), - pad_line( - f"Output folder : {Colors.ENDC}{safe_relpath(splitext(abspath(args.file))[0])}" - ), + pad_line(f"Output folder : {Colors.ENDC}{safe_relpath(splitext(abspath(args.file))[0])}"), pad_line(f"Log file : {Colors.ENDC}{os.path.basename(output_log)}"), - pad_line( - f"Config file : {Colors.ENDC}{safe_relpath(config_file)}{Colors.GREEN}, profile : {Colors.ENDC}{profile}" - ), + pad_line(f"Config file : {Colors.ENDC}{safe_relpath(config_file)}{Colors.GREEN}, profile : {Colors.ENDC}{profile}"), pad_line(""), bordure, ] @@ -2660,8 +2250,8 @@ if __name__ == "__main__": log.info(line) if args.file == "": - log.critical(f"No valid file selected, try again") - exit(0) + log.critical("No valid file selected, try again") + sys.exit() # print(f"{Colors.BLUE}Author = {Colors.ENDC}{globalData.Author}") # print(f"{Colors.BLUE}Copyright = {Colors.ENDC}{globalData.Copyright}") @@ -2698,10 +2288,8 @@ if __name__ == "__main__": DEST_PATH = os.path.dirname(args.file) + "/" + SurveyTitleMak if os.path.isdir(DEST_PATH): - log.critical( - f"The folder {Colors.ENDC}{SurveyTitleMak}{Colors.ERROR}{Colors.BOLD}, all ready exist : update mode is not possible for mak files" - ) - exit(0) + log.critical(f"The folder {Colors.ENDC}{SurveyTitleMak}{Colors.ERROR}{Colors.BOLD}, all ready exist : update mode is not possible for mak files") + sys.exit() fileTitle, thread2 = mak_to_th_file(abspath(args.file)) threads += thread2 @@ -2730,40 +2318,27 @@ if __name__ == "__main__": folderDest = os.path.dirname(args.file) + "\\" + SurveyTitleDat if os.path.isdir(folderDest): - log.critical( - f"The folder {Colors.ENDC}{SurveyTitleDat}{Colors.ERROR}{Colors.BOLD}, all ready exist : update mode is not possible for mak files" - ) - exit(0) + log.critical(f"The folder {Colors.ENDC}{SurveyTitleDat}{Colors.ERROR}{Colors.BOLD}, all ready exist : update mode is not possible for mak files") + sys.exit() - with ( - alive_bar( - QtySections, - title=f"{Colors.GREEN}Dat to Th conversion progress: {Colors.BLUE}", - length=20, - enrich_print=False, - stats=True, # Désactive les stats par défaut pour plus de lisibilité - elapsed=True, # Optionnel : masque le temps écoulé - monitor=True, # Optionnel : masque les métriques (ex: "eta") - bar="smooth", # Style de la barre (autres options: "smooth", "classic", "blocks") - ) as bar - ): + with alive_bar( # noqa: SIM117 + QtySections, + title=f"{Colors.GREEN}Dat to Th conversion progress: {Colors.BLUE}", + length=20, + enrich_print=False, + stats=True, # Désactive les stats par défaut pour plus de lisibilité + elapsed=True, # Optionnel : masque le temps écoulé + monitor=True, # Optionnel : masque les métriques (ex: "eta") + bar="smooth", # Style de la barre (autres options: "smooth", "classic", "blocks") + ) as bar: with redirect_stdout(sys.__stdout__): for i in range(1): if globalData.error_count > 0: - bar.text( - f"{Colors.INFO}file: {Colors.ENDC}{os.path.basename(ABS_file)[:-4]}{Colors.ERROR}, error: {Colors.ENDC}{globalData.error_count}" - ) + bar.text(f"{Colors.INFO}file: {Colors.ENDC}{os.path.basename(ABS_file)[:-4]}{Colors.ERROR}, error: {Colors.ENDC}{globalData.error_count}") else: - bar.text( - f"{Colors.INFO}file: {Colors.ENDC}{os.path.basename(ABS_file)[:-4]}" - ) + bar.text(f"{Colors.INFO}file: {Colors.ENDC}{os.path.basename(ABS_file)[:-4]}") stationList, fileTitle, totReadMeError, thread2 = dat_to_th_files( - ABS_file, - fixPoints=[], - crs_wkt="", - CONFIG_PATH=_ConfigPath, - totReadMeError="", - bar=bar, + ABS_file, fixPoints=[], crs_wkt="", CONFIG_PATH=_ConfigPath, totReadMeError="", bar=bar ) threads += thread2 bar() @@ -2775,9 +2350,7 @@ if __name__ == "__main__": SrcFile = abspath(args.file) DestFile = SrcFile[:-4] + ".th" - source_content, val, encodage = load_text_file_utf8( - SrcFile, os.path.basename(SrcFile) - ) + source_content, val, encodage = load_text_file_utf8(SrcFile, os.path.basename(SrcFile)) entrance, fileTitle, coordinates, coordsyst, fle_th_fnme = convert_tro( fle_tro_fnme=SrcFile, @@ -2792,56 +2365,45 @@ if __name__ == "__main__": ) if coordsyst == None: - log.critical( - f"The VisualTopo file {Colors.ENDC}{SrcFile}{Colors.ERROR}{Colors.BOLD}, have no coordinate system define. Correct it and try again" - ) - exit(0) + log.critical(f"The VisualTopo file {Colors.ENDC}{SrcFile}{Colors.ERROR}{Colors.BOLD}, have no coordinate system define. Correct it and try again") + sys.exit() - content, val, encodage = load_text_file_utf8( - fle_th_fnme, os.path.basename(fle_th_fnme) - ) + content, val, encodage = load_text_file_utf8(fle_th_fnme, os.path.basename(fle_th_fnme)) + content = content.replace("\t\t\tflags not duplicate\n\t\t\tflags duplicate\n", "") if globalData.parse_tro_files_by_explo: _centerlines = parse_therion_centerline(content) centerlines = regroupe_date(_centerlines) - with ( - alive_bar( - len(centerlines) + 1, - title=f"{Colors.GREEN}Tro to Th conversion progress: {Colors.BLUE}", - length=20, - enrich_print=False, - stats=True, # Désactive les stats par défaut pour plus de lisibilité - elapsed=True, # Optionnel : masque le temps écoulé - monitor=True, # Optionnel : masque les métriques (ex: "eta") - bar="smooth", # Style de la barre (autres options: "smooth", "classic", "blocks") - ) as bar - ): + with alive_bar( # noqa: SIM117 + len(centerlines) + 1, + title=f"{Colors.GREEN}Tro to Th conversion progress: {Colors.BLUE}", + length=20, + enrich_print=False, + stats=True, # Désactive les stats par défaut pour plus de lisibilité + elapsed=True, # Optionnel : masque le temps écoulé + monitor=True, # Optionnel : masque les métriques (ex: "eta") + bar="smooth", # Style de la barre (autres options: "smooth", "classic", "blocks") + ) as bar: with redirect_stdout(sys.__stdout__): for i in range(1): if globalData.error_count > 0: - bar.text( - f"{Colors.INFO}file: {Colors.ENDC}{os.path.basename(SrcFile)}{Colors.ERROR}, error: {Colors.ENDC}{globalData.error_count}" - ) + bar.text(f"{Colors.INFO}file: {Colors.ENDC}{os.path.basename(SrcFile)}{Colors.ERROR}, error: {Colors.ENDC}{globalData.error_count}") else: - bar.text( - f"{Colors.INFO}file: {Colors.ENDC}{os.path.basename(SrcFile)}" - ) + bar.text(f"{Colors.INFO}file: {Colors.ENDC}{os.path.basename(SrcFile)}") - stationList, fileTitle, totReadMeError, thread2 = ( - tro_to_th_files( - ENTRY_FILE=SrcFile, - centerlines=centerlines, - entrance=entrance, - fileTitle=fileTitle, - coordinates=coordinates, - coordsyst=coordsyst, - fle_th_fnme=fle_th_fnme, - CONFIG_PATH="", - totReadMeError="", - bar=bar, - ) + stationList, fileTitle, totReadMeError, thread2 = tro_to_th_files( + ENTRY_FILE=SrcFile, + centerlines=centerlines, + entrance=entrance, + fileTitle=fileTitle, + coordinates=coordinates, + coordsyst=coordsyst, + fle_th_fnme=fle_th_fnme, + CONFIG_PATH="", + totReadMeError="", + bar=bar, ) threads += thread2 bar() @@ -2851,25 +2413,17 @@ if __name__ == "__main__": with open(str(fle_th_fnme), "w+", encoding="utf-8") as f: f.write(content) - with open( - fle_th_fnme, "a", encoding="utf-8" - ) as file: # Données originales en commentaire dans le fichier th - file.write( - f"\n\n#############################################################################################" - ) - file.write(f"\n# Originals data file : {args.file}") + with open(fle_th_fnme, "a", encoding="utf-8") as file: # Ajout des données originales en commentaire dans le fichier th + file.write("\n\n#############################################################################################") + file.write("\n# Originals data file : {args.file}") if globalData.error_count == 0: - file.write( - f"\n# Conversion with pyCreateTh version {globalData.Version}, the {datetime.now().strftime('%Y.%m.%d %H:%M:%S')}, without error" - ) + file.write(f"\n# Conversion with pyCreateTh version {globalData.Version}, the {datetime.now().strftime('%Y.%m.%d %H:%M:%S')}, without error") # noqa: DTZ005 else: file.write( - f"\n# Conversion with pyCreateTh version {globalData.Version}, the {datetime.now().strftime('%Y.%m.%d %H:%M:%S')}, with {globalData.error_count} error(s)" + f"\n# Conversion with pyCreateTh version {globalData.Version}, the {datetime.now().strftime('%Y.%m.%d %H:%M:%S')}, with {globalData.error_count} error(s)" # noqa: DTZ005 ) - file.write( - f"\n#############################################################################################\n\n" - ) + file.write("\n#############################################################################################\n\n") for line in source_content.splitlines(): file.write(f"# {line}\n") @@ -2894,6 +2448,7 @@ if __name__ == "__main__": # Fichier TROX # ################################################################################################# elif args.file[-4:].lower() == "trox": + log.warning(f"trox file {Colors.ENDC}{safe_relpath(args.file)}{Colors.ERROR} not yet supported, use tro file") SrcFile = abspath(args.file) analyse_xml_balises(SrcFile) fileTitle = sanitize_filename(os.path.basename(SrcFile)[:-4]) @@ -2902,9 +2457,7 @@ if __name__ == "__main__": # Autres types # ################################################################################################# else: - log.error( - f"file {Colors.ENDC}{safe_relpath(args.file)}{Colors.ERROR} not yet supported" - ) + log.error(f"file {Colors.ENDC}{safe_relpath(args.file)}{Colors.ERROR} not yet supported") globalData.error_count += 1 for t in threads: @@ -2916,12 +2469,10 @@ if __name__ == "__main__": wait_until_file_is_released(output_log) - duration = (datetime.now() - start_time).total_seconds() + duration = (datetime.now() - start_time).total_seconds() # noqa: DTZ005 if globalData.error_count == 0: - log.info( - f"All files processed successfully in {Colors.ENDC}{duration:.2f}{Colors.INFO} secondes, without error" - ) + log.info(f"All files processed successfully in {Colors.ENDC}{duration:.2f}{Colors.INFO} secondes, without error") else: log.error( f"There were {Colors.ENDC}{globalData.error_count}{Colors.ERROR} errors during {Colors.ENDC}{duration:.2f}{Colors.ERROR} secondes, check the log file: {Colors.ENDC}{os.path.basename(output_log)}" diff --git a/Scripts/pyCreateTh/pyCreateTh_VSCode.code-workspace b/Scripts/pyCreateTh/pyCreateTh_VSCode.code-workspace index 2620a53..1485639 100644 --- a/Scripts/pyCreateTh/pyCreateTh_VSCode.code-workspace +++ b/Scripts/pyCreateTh/pyCreateTh_VSCode.code-workspace @@ -25,6 +25,7 @@ "etrs", "european", "fnme", + "FURB", "geocentricdatumofaustralia", "geocentricofaustralia", "icomments",