mn1_rec.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. '''
  2. Schéma de validation des données MN1
  3. @author: olivier.massot, 2018
  4. '''
  5. import logging
  6. from qgis.core import QgsProject, QgsGeometry
  7. from core.cerberus_ import is_float, is_multi_int, is_int, \
  8. is_modern_french_date, CerberusValidator, CerberusErrorHandler, \
  9. _translate_messages
  10. from core.checking import BaseChecker
  11. from core.mncheck import QgsModel
  12. logger = logging.getLogger("mncheck")
  13. SCHEMA_NAME = "Schéma MN v1 REC"
  14. XMIN, XMAX, YMIN, YMAX = 1341999, 1429750, 8147750, 8294000
  15. CRS = 'EPSG:3949' # Coordinate Reference System
  16. TOLERANCE = 1
  17. class Artere(QgsModel):
  18. layername = "artere_geo"
  19. geom_type = QgsModel.GEOM_LINE
  20. crs = CRS
  21. bounding_box = (XMIN,YMIN,XMAX,YMAX)
  22. schema = {'AR_ID_INSE': {'type': 'string', 'empty': False, 'regex': r'50\d{3}'},
  23. 'AR_LONG': {'empty': False, 'validator': is_float},
  24. 'AR_ETAT': {'type': 'string', 'empty': False, 'allowed': ['0', '1', '2', '3', '4']},
  25. 'AR_OCCP': {'type': 'string', 'empty': False, 'allowed': ['0', '1.1', '1.2', '2', '3', '4']},
  26. 'AR_NOEUD_A': {'type': 'string', 'empty': False, 'maxlength': 20},
  27. 'AR_NOEUD_B': {'type': 'string', 'empty': False, 'maxlength': 20},
  28. 'AR_NB_FOUR': {'empty': False, 'validator': is_multi_int},
  29. 'AR_FOU_DIS': {'empty': False, 'validator': is_int},
  30. 'AR_TYPE_FO': {'type': 'string', 'multiallowed': ['PVC', 'PEHD', 'SOUS-TUBAGE PEHD', 'SOUS-TUBAGE SOUPLE', 'FACADE', 'AERIEN', 'ENCORBELLEMENT', 'AUTRE']},
  31. 'AR_DIAM_FO': {'type': 'string', 'multiallowed': ['10', '14', '18', '25', '28', '32', '40', '45', '60', '80', '150', 'NUL']},
  32. 'AR_PRO_FOU': {'type': 'string', 'multiallowed': ['MANCHE NUMERIQUE', 'COLLECTIVITE', 'ORANGE', 'PRIVE', 'ERDF', 'AUTRE (à préciser)']},
  33. 'AR_PRO_CAB': {'type': 'string', 'empty': False, 'allowed': ['MANCHE NUMERIQUE']},
  34. 'AR_GEST_FO': {'type': 'string', 'multiallowed': ['MANCHE NUMERIQUE', 'MANCHE TELECOM', 'COLLECTIVITE', 'ORANGE', 'MANCHE FIBRE', 'PRIVE', 'ERDF', 'AUTRE (à préciser)', 'NUL']},
  35. 'AR_UTIL_FO': {'type': 'string', 'multiallowed': ['MANCHE NUMERIQUE', 'MANCHE TELECOM', 'COLLECTIVITE', 'ORANGE', 'MANCHE FIBRE', 'PRIVE', 'AUTRE (à préciser)', 'NUL']},
  36. 'AR_DATE_IN': {'empty': False, 'validator': is_modern_french_date},
  37. 'AR_DATE_RE': {'empty': False, 'validator': is_modern_french_date},
  38. 'AR_REF_PLA': {'type': 'string', 'maxlength': 100},
  39. 'AR_SRC_GEO': {'type': 'string', 'maxlength': 50},
  40. 'AR_QLT_GEO': {'type': 'string', 'empty': False, 'allowed': ['A', 'B', 'C']},
  41. 'AR_PRO_MD': {'type': 'string', 'empty': False, 'default': 'MANCHE NUMERIQUE', 'allowed': ['MANCHE NUMERIQUE']},
  42. 'AR_COMMENT': {'type': 'string', 'maxlength': 300, 'empty': True},
  43. 'AR_STATUT': {'type': 'string', 'empty': False, 'allowed': ['APS', 'APD', 'EXE', 'REC']}}
  44. def __repr__(self):
  45. return f"Artere {self.AR_NOEUD_A}-{self.AR_NOEUD_B}"
  46. class Cable(QgsModel):
  47. layername = "cable_geo"
  48. geom_type = QgsModel.GEOM_LINE
  49. crs = CRS
  50. bounding_box = (XMIN,YMIN,XMAX,YMAX)
  51. pk = "CA_NUMERO"
  52. schema = {'CA_NUMERO': {'type': 'string', 'maxlength': 17},
  53. 'CA_TYPE': {'type': 'string', 'maxlength': 10, 'empty': False, 'allowed': ['AERIEN', 'IMMEUBLE', 'FACADE', 'MIXTE', 'SOUTERRAIN']},
  54. 'CA_ETAT': {'type': 'string', 'maxlength': 1, 'empty': False, 'allowed': ['0', '1', '2', '3', '4']},
  55. 'CA_LONG': {'validator': is_float},
  56. 'CA_EQ_A': {'type': 'string', 'maxlength': 18},
  57. 'CA_EQ_B': {'type': 'string', 'maxlength': 18},
  58. 'CA_DIAMETR': {'empty': False, 'validator': is_float},
  59. 'CA_COULEUR': {'type': 'string', 'maxlength': 20, 'empty': False, 'allowed': ['NOIR', 'BLEU', 'BLANC']},
  60. 'CA_TECHNOL': {'type': 'string', 'maxlength': 17, 'empty': False, 'allowed': ['G657A2_M6', 'G657A2_M12']},
  61. 'CA_NB_FO': {'validator': is_int},
  62. 'CA_NB_FO_U': {'empty': False, 'validator': is_int},
  63. 'CA_NB_FO_D': {'empty': False, 'validator': is_int},
  64. 'CA_PRO': {'type': 'string', 'maxlength': 20, 'empty': False, 'allowed': ['MANCHE NUMERIQUE']},
  65. 'CA_GEST': {'type': 'string', 'maxlength': 20, 'empty': False, 'allowed': ['MANCHE FIBRE']},
  66. 'CA_DATE_IN': {'empty': False, 'validator': is_modern_french_date},
  67. 'CA_COMMENT': {'type': 'string', 'maxlength': 300, 'empty': True},
  68. 'CA_STATUT': {'type': 'string', 'maxlength': 14, 'empty': False, 'allowed': ['APS', 'APD', 'EXE', 'REC']}}
  69. def __repr__(self):
  70. return f"Cable {self.CA_EQ_A}-{self.CA_EQ_B}"
  71. class Equipement(QgsModel):
  72. layername = "equipement_passif"
  73. geom_type = QgsModel.GEOM_POINT
  74. crs = CRS
  75. bounding_box = (XMIN,YMIN,XMAX,YMAX)
  76. pk = "EQ_NOM"
  77. schema = {'EQ_NOM': {'type': 'string', 'maxlength': 10, 'contains_any_of': ['PBO', 'BPE', 'BAI']},
  78. 'EQ_NOM_NOE': {'type': 'string', 'maxlength': 30},
  79. 'EQ_ETAT': {'type': 'string', 'maxlength': 1, 'empty': False, 'allowed': ['0', '1', '2', '3', '4']},
  80. 'EQ_OCCP': {'type': 'string', 'maxlength': 3, 'empty': False, 'allowed': ['0', '1.1', '1.2', '2', '3', '4']},
  81. 'EQ_TYPE': {'type': 'string', 'empty': False, 'allowed': ['PBO', 'PBOE', 'BPE', 'BAI']},
  82. 'EQ_TYPE_LQ': {'type': 'string', 'maxlength': 6, 'empty': False, 'allowed': ['PBO', 'BPE JB', 'BPE JD', 'BAIDC', 'BAIOP']},
  83. 'EQ_TYPE_PH': {'type': 'string', 'maxlength': 24, 'empty': False, 'allowed': ['PBO 6', 'PBO 12', 'BPE 12EP', 'BPE 24EP', 'BPE 48EP', 'BPE 72EP', 'BPE 96EP', 'BPE 144EP', 'BPE 288EP', 'BPE 576EP', 'BPE 720EP', 'BAI']},
  84. 'EQ_PRO': {'type': 'string', 'maxlength': 20, 'empty': False, 'allowed': ['MANCHE NUMERIQUE', 'COLLECTIVITE', 'ORANGE', 'PRIVE', 'AUTRE (à préciser)', 'NUL']},
  85. 'EQ_GEST': {'type': 'string', 'maxlength': 20, 'empty': False, 'allowed': ['MANCHE NUMERIQUE', 'MANCHE TELECOM', 'COLLECTIVITE', 'ORANGE', 'MANCHE FIBRE', 'PRIVE', 'AUTRE (à préciser)', 'NUL']},
  86. 'EQ_HAUT': {'empty': False, 'validator': is_float},
  87. 'EQ_DATE_IN': {'empty': False, 'validator': is_modern_french_date},
  88. 'EQ_COMMENT': {'type': 'string', 'maxlength': 300, 'empty': True},
  89. 'EQ_STATUT': {'type': 'string', 'maxlength': 14, 'empty': False, 'allowed': ['APS', 'APD', 'EXE', 'REC']}}
  90. def __repr__(self):
  91. return f"Equipement {self.EQ_NOM}"
  92. class Noeud(QgsModel):
  93. layername = "noeud_geo"
  94. geom_type = QgsModel.GEOM_POINT
  95. crs = CRS
  96. bounding_box = (XMIN,YMIN,XMAX,YMAX)
  97. pk = "NO_NOM"
  98. schema = {'NO_NOM': {'type': 'string', 'maxlength': 30},
  99. 'NO_ID_INSE': {'type': 'string', 'empty': False, 'regex': r'50\d{3}'},
  100. 'NO_VOIE': {'type': 'string', 'maxlength': 100},
  101. 'NO_ETAT': {'type': 'string', 'maxlength': 1, 'empty': False, 'allowed': ['0', '1', '2', '3', '4']},
  102. 'NO_OCCP': {'type': 'string', 'maxlength': 3, 'empty': False, 'allowed': ['0', '1.1', '1.2', '2', '3', '4']},
  103. 'NO_TYPE': {'type': 'string', 'maxlength': 3, 'empty': False, 'allowed': ['CHA', 'POT', 'LTE', 'SEM', 'FAC', 'OUV', 'IMM']},
  104. 'NO_TYPE_LQ': {'type': 'string', 'maxlength': 10, 'empty': False, 'allowed': ['CHTIR', 'CHRACC', 'POT', 'NRO', 'PM', 'MIMO', 'FAC', 'OUV', 'IMM']},
  105. 'NO_TYPE_PH': {'type': 'string', 'maxlength': 20, 'empty': False, 'allowed': ['CHAMBRE', 'POTEAU', 'ARMOIRE', 'SHELTER', 'BATIMENT', 'SITE MIMO', 'FACADE', 'OUVRAGE', 'IMMEUBLE']},
  106. 'NO_CODE_PH': {'type': 'string', 'maxlength': 20},
  107. 'NO_TECH_PS': {'type': 'string', 'maxlength': 20, 'multiallowed': ['COAX', 'CUT', 'ECL', 'ELEC', 'VP', 'OPT', 'NC']},
  108. 'NO_AMO': {'type': 'string', 'maxlength': 20},
  109. 'NO_PLINOX': {'required':False, 'type': 'string', 'maxlength': 3, 'allowed': ['OUI', 'NON']},
  110. 'NO_X': {'empty': False, 'validator': is_float},
  111. 'NO_Y': {'empty': False, 'validator': is_float},
  112. 'NO_PRO': {'type': 'string', 'maxlength': 20, 'empty': False, 'allowed': ['MANCHE NUMERIQUE', 'COLLECTIVITE', 'ORANGE', 'ERDF', 'PRIVE', 'ENEDIS', 'AUTRE (à préciser)', 'NUL']},
  113. 'NO_GEST': {'type': 'string', 'maxlength': 20, 'empty': False, 'allowed': ['MANCHE NUMERIQUE', 'MANCHE TELECOM', 'COLLECTIVITE', 'ORANGE', 'ERDF', 'ENEDIS', 'MANCHE FIBRE', 'PRIVE', 'AUTRE (à préciser)', 'NUL']},
  114. 'NO_HAUT': {'empty': False, 'validator': is_float},
  115. 'NO_DATE_IN': {'empty': False, 'validator': is_modern_french_date},
  116. 'NO_REF_PLA': {'type': 'string', 'maxlength': 100},
  117. 'NO_SRC_GEO': {'type': 'string', 'maxlength': 50},
  118. 'NO_QLT_GEO': {'type': 'string', 'maxlength': 1, 'empty': False, 'allowed': ['A', 'B', 'C']},
  119. 'NO_PRO_MD': {'type': 'string', 'maxlength': 20, 'empty': False, 'allowed': ['MANCHE NUMERIQUE']},
  120. 'NO_COMMENT': {'type': 'string', 'maxlength': 300, 'empty': True},
  121. 'NO_STATUT': {'type': 'string', 'maxlength': 14, 'empty': False, 'allowed': ['APS', 'APD', 'EXE', 'REC']}}
  122. def __repr__(self):
  123. return f"Noeud {self.NO_NOM}"
  124. class Tranchee(QgsModel):
  125. layername = "tranchee_geo"
  126. geom_type = QgsModel.GEOM_LINE
  127. crs = CRS
  128. bounding_box = (XMIN,YMIN,XMAX,YMAX)
  129. schema = {'TR_ID_INSE': {'type': 'string', 'empty': False, 'regex': r'50\d{3}'},
  130. 'TR_VOIE': {'type': 'string', 'maxlength': 200},
  131. 'TR_TYP_IMP': {'type': 'string', 'empty': False, 'allowed': ['ACCOTEMENT STABILISE', 'ACCOTEMENT NON STABILISE', 'CHAUSSEE LOURDE', 'CHAUSSEE LEGERE', 'FOSSE', 'TROTTOIR', 'ESPACE VERT', 'ENCORBELLEMENT']},
  132. 'TR_MOD_POS': {'type': 'string', 'empty': False, 'allowed': ['TRADITIONNEL', 'MICRO TRANCHEE', 'FONCAGE 60', 'FONCAGE 90', 'FONCAGE 120', 'TRANCHEUSE', 'FORAGE URBAIN', 'FORAGE RURAL', 'ENCORBELLEMENT']},
  133. 'TR_LONG': {'empty': False, 'validator': is_float},
  134. 'TR_LARG': {'empty': False, 'validator': is_float},
  135. 'TR_REVET': {'empty':True, 'type': 'string', 'allowed': ['SABLE', 'BICOUCHE', 'ENROBE', 'BETON', 'PAVE', 'TERRAIN NATUREL']},
  136. 'TR_CHARGE': {'empty': False, 'validator': is_float},
  137. 'TR_GRILLAG': {'empty':True, 'validator': is_float},
  138. 'TR_REMBLAI': {'type': 'string'},
  139. 'TR_PLYNOX': {'type': 'string', 'empty': False, 'allowed': ['OUI', 'NON']},
  140. 'TR_PRO_VOI': {'type': 'string', 'empty': False, 'allowed': ['COMMUNE', 'COMMUNAUTE DE COMMUNES', 'DEPARTEMENT', 'ETAT', 'PRIVE']},
  141. 'TR_GEST_VO': {'type': 'string', 'empty': False, 'allowed': ['COMMUNE', 'COMMUNAUTE DE COMMUNES', 'DEPARTEMENT', 'ETAT', 'PRIVE']},
  142. 'TR_SCHEMA': {'maxlength': 100, 'type': 'string'},
  143. 'TR_DATE_IN': {'empty': False, 'validator': is_modern_french_date},
  144. 'TR_SRC_GEO': {'type': 'string', 'maxlength': 50},
  145. 'TR_QLT_GEO': {'type': 'string', 'empty': False, 'allowed': ['A', 'B', 'C']},
  146. 'TR_PRO_MD': {'type': 'string', 'maxlength': 20},
  147. 'TR_COMMENT': {'type': 'string', 'maxlength': 300, 'empty': True},
  148. 'TR_STATUT': {'type': 'string', 'empty': False, 'allowed': ['APS', 'APD', 'EXE', 'REC']}}
  149. def __repr__(self):
  150. return f"Tranchee {self.TR_VOIE}"
  151. class Zapbo(QgsModel):
  152. layername = "zapbo_geo"
  153. geom_type = QgsModel.GEOM_POLYGON
  154. crs = CRS
  155. bounding_box = (XMIN,YMIN,XMAX,YMAX)
  156. pk = "ID_ZAPBO"
  157. schema = {'ID_ZAPBO': {'type': 'string', 'maxlength': 30, 'contains_any_of': ['PBO', 'BPE']},
  158. 'COMMENTAIR': {'type': 'string', 'maxlength': 254, 'empty': True},
  159. 'STATUT': {'type': 'string', 'empty': False, 'allowed': ['APS', 'APD', 'EXE', 'REC']}}
  160. def __repr__(self):
  161. return f"Zapbo {self.ID_ZAPBO}"
  162. models = [Artere, Cable, Equipement, Noeud, Tranchee, Zapbo]
  163. ####### Validateur
  164. class Mn1Checker(BaseChecker):
  165. def test_load_layers(self):
  166. """ Chargement des données
  167. Contrôle la présence des couches attendues
  168. """
  169. self.dataset = {}
  170. for model in models:
  171. layername = model.layername
  172. try:
  173. layer = next((l for l in QgsProject.instance().mapLayers().values() if l.name().lower() == layername.lower()))
  174. except StopIteration:
  175. self.log_critical("Couche manquante", model=model)
  176. continue
  177. if model.pk:
  178. if not model.pk.lower() in [f.name().lower() for f in layer.fields()]:
  179. self.log_critical(f"Clef primaire manquante ({model.pk})", model=model)
  180. continue
  181. model.layer = layer
  182. self.dataset[model] = [model(f) for f in layer.getFeatures()]
  183. self.arteres = self.dataset.get(Artere, [])
  184. self.cables = self.dataset.get(Cable, [])
  185. self.equipements = self.dataset.get(Equipement, [])
  186. self.noeuds = self.dataset.get(Noeud, [])
  187. self.tranchees = self.dataset.get(Tranchee, [])
  188. self.zapbos = self.dataset.get(Zapbo, [])
  189. def test_scr(self):
  190. """ Contrôle des projections
  191. Vérifie que les couches ont le bon sytème de projection
  192. """
  193. for model in models:
  194. if model.layer.crs().authid() != model.crs:
  195. self.log_error(f"Mauvaise projection (attendu: {model.crs})", model=model)
  196. def _validate_structure(self, model, items):
  197. v = CerberusValidator(model.schema, purge_unknown=True, error_handler=CerberusErrorHandler, require_all=True)
  198. for item in items:
  199. v.validate(item.__dict__)
  200. for field, verrors in v.errors.items():
  201. for err in verrors:
  202. self.log_error(f"{field} : {_translate_messages(err)}", item=item)
  203. def test_structure_arteres(self):
  204. """ Structure des données: Artères
  205. Contrôle les données attributaires de la couche ARTERE_GEO:
  206. présence, format, valeurs autorisées...
  207. """
  208. self._validate_structure(Artere, self.arteres)
  209. def test_structure_cables(self):
  210. """ Structure des données: Cables
  211. Contrôle les données attributaires de la couche CABLE_GEO:
  212. présence, format, valeurs autorisées...
  213. """
  214. self._validate_structure(Cable, self.cables)
  215. def test_structure_equipements(self):
  216. """ Structure des données: Equipements
  217. Contrôle les données attributaires de la couche EQUIPEMENT_GEO:
  218. présence, format, valeurs autorisées...
  219. """
  220. self._validate_structure(Equipement, self.equipements)
  221. def test_structure_noeuds(self):
  222. """ Structure des données: Noeuds
  223. Contrôle les données attributaires de la couche NOEUD_GEO:
  224. présence, format, valeurs autorisées...
  225. """
  226. self._validate_structure(Noeud, self.noeuds)
  227. def test_structure_tranchees(self):
  228. """ Structure des données: Tranchées
  229. Contrôle les données attributaires de la couche TRANCHEE_GEO:
  230. présence, format, valeurs autorisées...
  231. """
  232. self._validate_structure(Tranchee, self.tranchees)
  233. def test_structure_zapbos(self):
  234. """ Structure des données: Zapbos
  235. Contrôle les données attributaires de la couche ZAPBO_GEO:
  236. présence, format, valeurs autorisées...
  237. """
  238. self._validate_structure(Zapbo, self.zapbos)
  239. def test_geometry_validity(self):
  240. """ Contrôle de la validité des géométries
  241. """
  242. for model in models:
  243. for item in self.dataset[model]:
  244. if not item.is_geometry_valid():
  245. self.log_error("La géométrie de l'objet est invalide", item=item)
  246. def test_geometry_type(self):
  247. """ Contrôle des types de géométries
  248. """
  249. for model in models:
  250. for item in self.dataset[model]:
  251. geom_type = item.get_geom_type()
  252. if geom_type != model.geom_type:
  253. self.log_error(f"Type de géométrie invalide (attendu: {QgsModel.GEOM_NAMES[geom_type]})", item=item)
  254. def test_bounding_box(self):
  255. """ Contrôle des emprises
  256. Vérifie que les objets sont dans le périmètre attendu
  257. """
  258. for model in models:
  259. xmin, ymin, xmax, ymax = model.bounding_box
  260. for item in self.dataset[model]:
  261. x1, y1, x2, y2 = item.get_bounding_box()
  262. if any(x < xmin or x > xmax for x in (x1, x2)) or \
  263. any(y < ymin or y > ymax for y in (y1, y2)):
  264. self.log_error("Hors de l'emprise autorisée", item=item)
  265. def test_duplicates(self):
  266. """ Recherche de doublons
  267. Recherche d'éventuels doublons dans des champs qui supposent l'unicité
  268. """
  269. tmp = []
  270. for noeud in self.noeuds:
  271. if not noeud.NO_NOM:
  272. continue
  273. if not noeud.NO_NOM in tmp:
  274. tmp.append(noeud.NO_NOM)
  275. else:
  276. self.log_error("Doublons dans le champs NO_NOM", item=noeud)
  277. tmp = []
  278. for equipement in self.equipements:
  279. if not equipement.EQ_NOM:
  280. continue
  281. if not equipement.EQ_NOM in tmp:
  282. tmp.append(equipement.EQ_NOM)
  283. else:
  284. self.log_error("Doublons dans le champs EQ_NOM", item=equipement)
  285. tmp = []
  286. for zapbo in self.zapbos:
  287. if not zapbo.ID_ZAPBO:
  288. continue
  289. if not zapbo.ID_ZAPBO in tmp:
  290. tmp.append(zapbo.ID_ZAPBO)
  291. else:
  292. self.log_error("Doublons dans le champs ID_ZAPBO", item=zapbo)
  293. def test_constraints_arteres_noeuds(self):
  294. """ Application des contraintes: Artères / Noeuds
  295. Vérifie que les noeuds attachés aux artères existent
  296. """
  297. for artere in self.arteres:
  298. try:
  299. artere.noeud_a = next((n for n in self.noeuds if n.NO_NOM == artere.AR_NOEUD_A))
  300. except StopIteration:
  301. artere.noeud_a = None
  302. self.log_error(f"Le noeud lié '{artere.AR_NOEUD_A}' n'existe pas", item=artere)
  303. try:
  304. artere.noeud_b = next((n for n in self.noeuds if n.NO_NOM == artere.AR_NOEUD_B))
  305. except StopIteration:
  306. artere.noeud_b = None
  307. self.log_error(f"Le noeud lié '{artere.AR_NOEUD_B}' n'existe pas", item=artere)
  308. def test_constraints_cables_equipements(self):
  309. """ Application des contraintes: Equipements / Cables
  310. Vérifie que les équipements attachés aux cables existent """
  311. for cable in self.cables:
  312. try:
  313. cable.equipement_a = next((e for e in self.equipements if e.EQ_NOM == cable.CA_EQ_A))
  314. except StopIteration:
  315. cable.equipement_a = None
  316. self.log_error(f"L'équipement lié '{cable.CA_EQ_A}' n'existe pas", item=cable)
  317. try:
  318. cable.equipement_b = next((e for e in self.equipements if e.EQ_NOM == cable.CA_EQ_B))
  319. except StopIteration:
  320. cable.equipement_b = None
  321. self.log_error(f"L'équipement lié '{cable.CA_EQ_B}' n'existe pas", item=cable)
  322. def test_constraints_cables_equipements_b(self):
  323. """ Application des contraintes: Equipements B
  324. Vérifie que tous les équipements sont l'équipement B d'au moins un cable """
  325. equipements_b = [cable.CA_EQ_B for cable in self.cables]
  326. for equipement in self.equipements:
  327. if equipement.EQ_TYPE == "BAI":
  328. continue
  329. if not equipement.EQ_NOM in equipements_b:
  330. self.log_error(f"L'equipement lié '{equipement.EQ_NOM}' n'est l'équipement B d'aucun cable", item=equipement)
  331. def test_constraints_equipements_noeuds(self):
  332. """ Application des contraintes: Noeuds / Equipements
  333. Vérifie que les noeuds attachés aux équipements existent
  334. """
  335. for equipement in self.equipements:
  336. try:
  337. equipement.noeud = next((n for n in self.noeuds if n.NO_NOM == equipement.EQ_NOM_NOE))
  338. except StopIteration:
  339. equipement.noeud = None
  340. self.log_error(f"Le noeud lié '{equipement.EQ_NOM_NOE}' n'existe pas", item=equipement)
  341. def test_graphic_duplicates(self):
  342. """ Recherche de doublons graphiques """
  343. for i, tranchee in enumerate(self.tranchees):
  344. for other in self.tranchees[i+1:]:
  345. if tranchee.geom == other.geom:
  346. self.log_error("Une entité graphique est dupliquée", item=tranchee)
  347. for i, artere in enumerate(self.arteres):
  348. for other in self.arteres[i+1:]:
  349. if artere.geom == other.geom:
  350. self.log_error("Une entité graphique est dupliquée", item=artere)
  351. for i, cable in enumerate(self.cables):
  352. for other in self.cables[i+1:]:
  353. if cable.geom == other.geom and cable.CA_EQ_A == other.CA_EQ_A and cable.CA_EQ_B == other.CA_EQ_B:
  354. self.log_error("Une entité graphique est dupliquée", item=cable)
  355. for i, noeud in enumerate(self.noeuds):
  356. for other in self.noeuds[i+1:]:
  357. if noeud.geom == other.geom:
  358. self.log_error("Une entité graphique est dupliquée", item=noeud)
  359. for i, zapbo in enumerate(self.zapbos):
  360. for other in self.zapbos[i+1:]:
  361. if zapbo.geom == other.geom:
  362. self.log_error("Une entité graphique est dupliquée", item=zapbo)
  363. def test_positions_noeuds(self):
  364. """ Topologie: Noeuds / Artères
  365. Compare la géométrie des noeuds à celle des artères
  366. """
  367. for artere in self.arteres:
  368. if not artere.noeud_a or not artere.noeud_b:
  369. continue
  370. artere_points = artere.get_points()
  371. noeud_a_point = artere.noeud_a.get_points()[0]
  372. noeud_b_point = artere.noeud_b.get_points()[0]
  373. if not any(((artere_points[0].distanceSquared(noeud_a_point) <= TOLERANCE and \
  374. artere_points[-1].distanceSquared(noeud_b_point) <= TOLERANCE),
  375. (artere_points[0].distanceSquared(noeud_b_point) <= TOLERANCE and \
  376. artere_points[-1].distanceSquared(noeud_a_point) <= TOLERANCE))):
  377. self.log_error("Pas de noeud aux coordonnées attendues", item=artere)
  378. def test_positions_equipements(self):
  379. """ Topologie: Equipements / Cables
  380. Compare la géométrie des équipements à celle des cables """
  381. for cable in self.cables:
  382. if not cable.equipement_a or not cable.equipement_b or not cable.is_geometry_valid() or not cable.equipement_a.noeud or not cable.equipement_b.noeud:
  383. continue
  384. #! attention: on utilise la géométrie du noeud associé à l'équipement, pas celle de l'équipement lui-même
  385. cable_points = cable.get_points()
  386. equip_a_point = cable.equipement_a.noeud.get_points()[0]
  387. equip_b_point = cable.equipement_b.noeud.get_points()[0]
  388. if not any(((cable_points[0].distanceSquared(equip_a_point) <= TOLERANCE and \
  389. cable_points[-1].distanceSquared(equip_b_point) <= TOLERANCE),
  390. (cable_points[0].distanceSquared(equip_b_point) <= TOLERANCE and \
  391. cable_points[-1].distanceSquared(equip_a_point) <= TOLERANCE))):
  392. self.log_error("Pas d'équipement aux coordonnées attendues", item=cable)
  393. def test_tranchee_artere(self):
  394. """ Topologie: Tranchées / Artères
  395. Compare la géométrie des tranchées à celle des artères """
  396. arteres_full_buffer = Artere.full_buffer(TOLERANCE)
  397. if not arteres_full_buffer.isGeosValid():
  398. raise ValueError("Buffer: géométrie invalide")
  399. for tranchee in self.tranchees:
  400. if not arteres_full_buffer.contains(tranchee.geom):
  401. self.log_error("Tranchée ou portion de tranchée sans artère", item=tranchee)
  402. def test_cable_artere(self):
  403. """ Topologie: Cables / Artères
  404. Compare la géométrie des cables à celle des artères """
  405. # Vérifie que chaque cable a au moins une artère (sauf si commentaire contient 'baguette')
  406. arteres_full_buffer = Artere.full_buffer(TOLERANCE)
  407. if not arteres_full_buffer.isGeosValid():
  408. raise ValueError("Buffer: géométrie invalide")
  409. for cable in self.cables:
  410. if "baguette" in cable.CA_COMMENT.lower() or not cable.is_geometry_valid():
  411. continue
  412. if not arteres_full_buffer.contains(cable.geom):
  413. self.log_error("Cable ou portion de cable sans artère", item=cable)
  414. def test_artere_cable(self):
  415. """ Topologie: Artères / Cables
  416. Compare la géométrie des artères à celle des cables """
  417. # Vérifie que chaque artère a au moins un cable (sauf si commentaire contient un de ces mots 'racco client adductio attente bus 'sans cable'')
  418. cables_full_buffer = Cable.full_buffer(TOLERANCE)
  419. if not cables_full_buffer.isGeosValid():
  420. raise ValueError("Buffer: géométrie invalide")
  421. for artere in self.arteres:
  422. if any(x in artere.AR_COMMENT.lower() for x in ['racco','client','adductio','attente','bus','sans cable']):
  423. continue
  424. if not cables_full_buffer.contains(artere.geom):
  425. self.log_error("Artère ou portion d'artère sans cable", item=artere)
  426. def test_dimensions_fourreaux(self):
  427. """ Dimensions logiques: fourreaux
  428. Vérifie que les nombres de fourreaux renseignés sont cohérents """
  429. for artere in self.arteres:
  430. try:
  431. if not int(artere.AR_FOU_DIS) <= int(artere.AR_NB_FOUR):
  432. self.log_error("Le nombre de fourreaux disponibles (AR_FOU_DIS) doit être inférieur au nombre total (AR_NB_FOUR)", item=artere)
  433. except (TypeError, ValueError):
  434. pass
  435. for cable in self.cables:
  436. try:
  437. if not int(cable.CA_NB_FO_U) <= int(cable.CA_NB_FO):
  438. self.log_error("Le nombre de fourreaux utilisés (CA_NB_FO_U) doit être inférieur au nombre total (CA_NB_FO)", item=cable)
  439. if not int(cable.CA_NB_FO_D) <= int(cable.CA_NB_FO):
  440. self.log_error("Le nombre de fourreaux disponibles (CA_NB_FO_D) doit être inférieur au nombre total (CA_NB_FO)", item=cable)
  441. except (TypeError, ValueError):
  442. pass
  443. def test_pbos(self):
  444. """ Topologie: PBO / ZAPBO
  445. Compare la géométrie et le nom des équipements de type PBO à celle des ZAPBO
  446. """
  447. # Verifier que chaque equipement de type PBO est contenu dans une zapbo, et que le nom de la zapbo contient le nom de l'equipement
  448. for equipement in self.equipements:
  449. if not equipement.EQ_TYPE == "PBO":
  450. continue
  451. #zapbos englobant l'equipement
  452. candidates = []
  453. for zapbo in self.zapbos:
  454. if zapbo.geom.contains(equipement.geom):
  455. candidates.append(zapbo)
  456. # le pbo doit être contenu dans une zapbo
  457. if not candidates:
  458. self.log_error("Le PBO n'est contenu dans aucune ZAPBO", item=equipement)
  459. continue
  460. # On se base sur le nom pour trouver la zapbo correspondante
  461. try:
  462. equipement.zapbo = next((z for z in candidates if equipement.EQ_NOM in z.ID_ZAPBO))
  463. except StopIteration:
  464. self.log_error("Le nom du PBO ne coincide avec le nom d'aucune des ZAPBO qui le contiennent", item=equipement)
  465. break
  466. # a venir (webservice?)
  467. def __test_pbo_dimension(self):
  468. """ Dimensionnement des PBO """
  469. for equipement in self.equipements:
  470. if not equipement.EQ_TYPE == "PBO":
  471. continue
  472. if not hasattr(equipement.zapbo, "nb_prises") or equipement.zapbo.nb_prises is None:
  473. equipement.zapbo.nb_prises = 0
  474. # Controle du dimensionnement des PBO
  475. if equipement.EQ_TYPE_PH == 'PBO 6' and not equipement.zapbo.nb_prises < 6:
  476. self.log_error("Le PBO 6 contient plus de 5 prises", item=equipement)
  477. if equipement.EQ_TYPE_PH == 'PBO 12' and not equipement.zapbo.nb_prises >= 6 and equipement.zapbo.nb_prises <= 8:
  478. self.log_error("Le PBO 12 contient mois de 6 prises ou plus de 8 prises", item=equipement)
  479. if equipement.zapbo.STATUT == "REC" and not equipement.EQ_STATUT == "REC":
  480. self.log_error("Le statut du PBO n'est pas cohérent avec le statut de sa ZAPBO", item=equipement)
  481. if equipement.EQ_STATUT == "REC" and not equipement.zapbo.STATUT == "REC" and not equipement.zapbo.ID_ZAPBO[:4].lower() == "att_":
  482. self.log_error("Le statut du PBO n'est pas cohérent avec le statut de sa ZAPBO", item=equipement)