mn1_rec.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  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, QgsWkbTypes
  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.checker import BaseChecker
  11. from core.validation_errors import UniqueError, RelationError, \
  12. DuplicatedGeom, MissingItem, DimensionError, TechnicalValidationError
  13. from core.validator import QgsModel, BaseValidator
  14. logger = logging.getLogger("mncheck")
  15. SCHEMA_NAME = "Schéma MN v1 REC"
  16. XMIN, XMAX, YMIN, YMAX = 1341999, 1429750, 8147750, 8294000
  17. CRS = 'EPSG:3949' # Coordinate Reference System
  18. TOLERANCE = 1
  19. class Artere(QgsModel):
  20. layername = "artere_geo"
  21. geom_type = QgsModel.GEOM_LINE
  22. crs = CRS
  23. bounding_box = (XMIN,YMIN,XMAX,YMAX)
  24. schema = {'AR_ID_INSE': {'type': 'string', 'empty': False, 'regex': r'50\d{3}'},
  25. 'AR_LONG': {'empty': False, 'validator': is_float},
  26. 'AR_ETAT': {'type': 'string', 'empty': False, 'allowed': ['0', '1', '2', '3', '4']},
  27. 'AR_OCCP': {'type': 'string', 'empty': False, 'allowed': ['0', '1.1', '1.2', '2', '3', '4']},
  28. 'AR_NOEUD_A': {'type': 'string', 'empty': False, 'maxlength': 20},
  29. 'AR_NOEUD_B': {'type': 'string', 'empty': False, 'maxlength': 20},
  30. 'AR_NB_FOUR': {'empty': False, 'validator': is_multi_int},
  31. 'AR_FOU_DIS': {'empty': False, 'validator': is_int},
  32. 'AR_TYPE_FO': {'type': 'string', 'multiallowed': ['PVC', 'PEHD', 'SOUS-TUBAGE PEHD', 'SOUS-TUBAGE SOUPLE', 'FACADE', 'AERIEN', 'ENCORBELLEMENT', 'AUTRE']},
  33. 'AR_DIAM_FO': {'type': 'string', 'multiallowed': ['10', '14', '18', '25', '28', '32', '40', '45', '60', '80', '150', 'NUL']},
  34. 'AR_PRO_FOU': {'type': 'string', 'multiallowed': ['MANCHE NUMERIQUE', 'COLLECTIVITE', 'ORANGE', 'PRIVE', 'ERDF', 'AUTRE (à préciser)']},
  35. 'AR_PRO_CAB': {'type': 'string', 'empty': False, 'allowed': ['MANCHE NUMERIQUE']},
  36. 'AR_GEST_FO': {'type': 'string', 'multiallowed': ['MANCHE NUMERIQUE', 'MANCHE TELECOM', 'COLLECTIVITE', 'ORANGE', 'MANCHE FIBRE', 'PRIVE', 'ERDF', 'AUTRE (à préciser)', 'NUL']},
  37. 'AR_UTIL_FO': {'type': 'string', 'multiallowed': ['MANCHE NUMERIQUE', 'MANCHE TELECOM', 'COLLECTIVITE', 'ORANGE', 'MANCHE FIBRE', 'PRIVE', 'AUTRE (à préciser)', 'NUL']},
  38. 'AR_DATE_IN': {'empty': False, 'validator': is_modern_french_date},
  39. 'AR_DATE_RE': {'empty': False, 'validator': is_modern_french_date},
  40. 'AR_REF_PLA': {'type': 'string', 'maxlength': 100},
  41. 'AR_SRC_GEO': {'type': 'string', 'maxlength': 50},
  42. 'AR_QLT_GEO': {'type': 'string', 'empty': False, 'allowed': ['A', 'B', 'C']},
  43. 'AR_PRO_MD': {'type': 'string', 'empty': False, 'default': 'MANCHE NUMERIQUE', 'allowed': ['MANCHE NUMERIQUE']},
  44. 'AR_COMMENT': {'type': 'string', 'maxlength': 300, 'empty': True},
  45. 'AR_STATUT': {'type': 'string', 'empty': False, 'allowed': ['APS', 'APD', 'EXE', 'REC']}}
  46. def __repr__(self):
  47. return "Artere {}-{}".format(self.AR_NOEUD_A, self.AR_NOEUD_B)
  48. class Cable(QgsModel):
  49. layername = "cable_geo"
  50. geom_type = QgsModel.GEOM_LINE
  51. crs = CRS
  52. bounding_box = (XMIN,YMIN,XMAX,YMAX)
  53. schema = {'CA_NUMERO': {'type': 'string', 'maxlength': 17},
  54. 'CA_TYPE': {'type': 'string', 'maxlength': 10, 'empty': False, 'allowed': ['AERIEN', 'IMMEUBLE', 'FACADE', 'MIXTE', 'SOUTERRAIN']},
  55. 'CA_ETAT': {'type': 'string', 'maxlength': 1, 'empty': False, 'allowed': ['0', '1', '2', '3', '4']},
  56. 'CA_LONG': {'validator': is_float},
  57. 'CA_EQ_A': {'type': 'string', 'maxlength': 18},
  58. 'CA_EQ_B': {'type': 'string', 'maxlength': 18},
  59. 'CA_DIAMETR': {'empty': False, 'validator': is_float},
  60. 'CA_COULEUR': {'type': 'string', 'maxlength': 20, 'empty': False, 'allowed': ['NOIR', 'BLEU', 'BLANC']},
  61. 'CA_TECHNOL': {'type': 'string', 'maxlength': 17, 'empty': False, 'allowed': ['G657A2_M6', 'G657A2_M12']},
  62. 'CA_NB_FO': {'validator': is_int},
  63. 'CA_NB_FO_U': {'empty': False, 'validator': is_int},
  64. 'CA_NB_FO_D': {'empty': False, 'validator': is_int},
  65. 'CA_PRO': {'type': 'string', 'maxlength': 20, 'empty': False, 'allowed': ['MANCHE NUMERIQUE']},
  66. 'CA_GEST': {'type': 'string', 'maxlength': 20, 'empty': False, 'allowed': ['MANCHE FIBRE']},
  67. 'CA_DATE_IN': {'empty': False, 'validator': is_modern_french_date},
  68. 'CA_COMMENT': {'type': 'string', 'maxlength': 300, 'empty': True},
  69. 'CA_STATUT': {'type': 'string', 'maxlength': 14, 'empty': False, 'allowed': ['APS', 'APD', 'EXE', 'REC']}}
  70. def __repr__(self):
  71. return "Cable {}-{}".format(self.CA_EQ_A, self.CA_EQ_B)
  72. class Equipement(QgsModel):
  73. layername = "equipement_passif"
  74. geom_type = QgsModel.GEOM_POINT
  75. crs = CRS
  76. bounding_box = (XMIN,YMIN,XMAX,YMAX)
  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 "Equipement {}".format(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. schema = {'NO_NOM': {'type': 'string', 'maxlength': 30},
  98. 'NO_ID_INSE': {'type': 'string', 'empty': False, 'regex': r'50\d{3}'},
  99. 'NO_VOIE': {'type': 'string', 'maxlength': 100},
  100. 'NO_ETAT': {'type': 'string', 'maxlength': 1, 'empty': False, 'allowed': ['0', '1', '2', '3', '4']},
  101. 'NO_OCCP': {'type': 'string', 'maxlength': 3, 'empty': False, 'allowed': ['0', '1.1', '1.2', '2', '3', '4']},
  102. 'NO_TYPE': {'type': 'string', 'maxlength': 3, 'empty': False, 'allowed': ['CHA', 'POT', 'LTE', 'SEM', 'FAC', 'OUV', 'IMM']},
  103. 'NO_TYPE_LQ': {'type': 'string', 'maxlength': 10, 'empty': False, 'allowed': ['CHTIR', 'CHRACC', 'POT', 'NRO', 'PM', 'MIMO', 'FAC', 'OUV', 'IMM']},
  104. 'NO_TYPE_PH': {'type': 'string', 'maxlength': 20, 'empty': False, 'allowed': ['CHAMBRE', 'POTEAU', 'ARMOIRE', 'SHELTER', 'BATIMENT', 'SITE MIMO', 'FACADE', 'OUVRAGE', 'IMMEUBLE']},
  105. 'NO_CODE_PH': {'type': 'string', 'maxlength': 20},
  106. 'NO_TECH_PS': {'type': 'string', 'maxlength': 20, 'multiallowed': ['COAX', 'CUT', 'ECL', 'ELEC', 'VP', 'OPT', 'NC']},
  107. 'NO_AMO': {'type': 'string', 'maxlength': 20},
  108. 'NO_PLINOX': {'required':False, 'type': 'string', 'maxlength': 3, 'allowed': ['OUI', 'NON']},
  109. 'NO_X': {'empty': False, 'validator': is_float},
  110. 'NO_Y': {'empty': False, 'validator': is_float},
  111. 'NO_PRO': {'type': 'string', 'maxlength': 20, 'empty': False, 'allowed': ['MANCHE NUMERIQUE', 'COLLECTIVITE', 'ORANGE', 'ERDF', 'PRIVE', 'ENEDIS', 'AUTRE (à préciser)', 'NUL']},
  112. 'NO_GEST': {'type': 'string', 'maxlength': 20, 'empty': False, 'allowed': ['MANCHE NUMERIQUE', 'MANCHE TELECOM', 'COLLECTIVITE', 'ORANGE', 'ERDF', 'ENEDIS', 'MANCHE FIBRE', 'PRIVE', 'AUTRE (à préciser)', 'NUL']},
  113. 'NO_HAUT': {'empty': False, 'validator': is_float},
  114. 'NO_DATE_IN': {'empty': False, 'validator': is_modern_french_date},
  115. 'NO_REF_PLA': {'type': 'string', 'maxlength': 100},
  116. 'NO_SRC_GEO': {'type': 'string', 'maxlength': 50},
  117. 'NO_QLT_GEO': {'type': 'string', 'maxlength': 1, 'empty': False, 'allowed': ['A', 'B', 'C']},
  118. 'NO_PRO_MD': {'type': 'string', 'maxlength': 20, 'empty': False, 'allowed': ['MANCHE NUMERIQUE']},
  119. 'NO_COMMENT': {'type': 'string', 'maxlength': 300, 'empty': True},
  120. 'NO_STATUT': {'type': 'string', 'maxlength': 14, 'empty': False, 'allowed': ['APS', 'APD', 'EXE', 'REC']}}
  121. def __repr__(self):
  122. return "Noeud {}".format(self.NO_NOM)
  123. class Tranchee(QgsModel):
  124. layername = "tranchee_geo"
  125. geom_type = QgsModel.GEOM_LINE
  126. crs = CRS
  127. bounding_box = (XMIN,YMIN,XMAX,YMAX)
  128. schema = {'TR_ID_INSE': {'type': 'string', 'empty': False, 'regex': r'50\d{3}'},
  129. 'TR_VOIE': {'type': 'string', 'maxlength': 200},
  130. 'TR_TYP_IMP': {'type': 'string', 'empty': False, 'allowed': ['ACCOTEMENT STABILISE', 'ACCOTEMENT NON STABILISE', 'CHAUSSEE LOURDE', 'CHAUSSEE LEGERE', 'FOSSE', 'TROTTOIR', 'ESPACE VERT', 'ENCORBELLEMENT']},
  131. 'TR_MOD_POS': {'type': 'string', 'empty': False, 'allowed': ['TRADITIONNEL', 'MICRO TRANCHEE', 'FONCAGE 60', 'FONCAGE 90', 'FONCAGE 120', 'TRANCHEUSE', 'FORAGE URBAIN', 'FORAGE RURAL', 'ENCORBELLEMENT']},
  132. 'TR_LONG': {'empty': False, 'validator': is_float},
  133. 'TR_LARG': {'empty': False, 'validator': is_float},
  134. 'TR_REVET': {'empty':True, 'type': 'string', 'allowed': ['SABLE', 'BICOUCHE', 'ENROBE', 'BETON', 'PAVE', 'TERRAIN NATUREL']},
  135. 'TR_CHARGE': {'empty': False, 'validator': is_float},
  136. 'TR_GRILLAG': {'empty':True, 'validator': is_float},
  137. 'TR_REMBLAI': {'type': 'string'},
  138. 'TR_PLYNOX': {'type': 'string', 'empty': False, 'allowed': ['OUI', 'NON']},
  139. 'TR_PRO_VOI': {'type': 'string', 'empty': False, 'allowed': ['COMMUNE', 'COMMUNAUTE DE COMMUNES', 'DEPARTEMENT', 'ETAT', 'PRIVE']},
  140. 'TR_GEST_VO': {'type': 'string', 'empty': False, 'allowed': ['COMMUNE', 'COMMUNAUTE DE COMMUNES', 'DEPARTEMENT', 'ETAT', 'PRIVE']},
  141. 'TR_SCHEMA': {'maxlength': 100, 'type': 'string'},
  142. 'TR_DATE_IN': {'empty': False, 'validator': is_modern_french_date},
  143. 'TR_SRC_GEO': {'type': 'string', 'maxlength': 50},
  144. 'TR_QLT_GEO': {'type': 'string', 'empty': False, 'allowed': ['A', 'B', 'C']},
  145. 'TR_PRO_MD': {'type': 'string', 'maxlength': 20},
  146. 'TR_COMMENT': {'type': 'string', 'maxlength': 300, 'empty': True},
  147. 'TR_STATUT': {'type': 'string', 'empty': False, 'allowed': ['APS', 'APD', 'EXE', 'REC']}}
  148. def __repr__(self):
  149. return "Tranchee {}".format(self.TR_VOIE)
  150. class Zapbo(QgsModel):
  151. layername = "zapbo_geo"
  152. geom_type = QgsModel.GEOM_POLYGON
  153. crs = CRS
  154. bounding_box = (XMIN,YMIN,XMAX,YMAX)
  155. schema = {'ID_ZAPBO': {'type': 'string', 'maxlength': 30, 'contains_any_of': ['PBO', 'BPE']},
  156. 'COMMENTAIR': {'type': 'string', 'maxlength': 254, 'empty': True},
  157. 'STATUT': {'type': 'string', 'empty': False, 'allowed': ['APS', 'APD', 'EXE', 'REC']}}
  158. def __repr__(self):
  159. return "Zapbo {}".format(self.ID_ZAPBO)
  160. models = [Artere, Cable, Equipement, Noeud, Tranchee, Zapbo]
  161. ####### Validateur
  162. class Mn1Checker(BaseChecker):
  163. def __init__(self):
  164. super().__init__()
  165. def test_load_layers(self):
  166. """ Chargement des données """
  167. for model in models:
  168. layername = model.layername
  169. layer = next((l for l in QgsProject.instance().mapLayers().values() if l.name().lower() == layername.lower()))
  170. if not layer:
  171. self.log_error("Couche manquante", layername=layername, critical=True)
  172. continue
  173. model.layer = layer
  174. self.arteres = list(Artere.layer.getFeatures())
  175. self.cables = list(Cable.layer.getFeatures())
  176. # self.equipements = list(Equipement.layer.getFeatures())
  177. # self.noeuds = list(Noeud.layer.getFeatures())
  178. self.tranchees = list(Tranchee.layer.getFeatures())
  179. # self.zapbos = list(Zapbo.layer.getFeatures())
  180. self.dataset = {Artere: self.arteres,
  181. Cable: self.cables,
  182. Equipement: self.equipements,
  183. Noeud: self.noeuds,
  184. Tranchee: self.tranchees,
  185. Zapbo: self.zapbos}
  186. def test_scr(self):
  187. """ Contrôle des projections """
  188. for model in models:
  189. if model.layer.crs().authid() != model.crs:
  190. self.log_error(f"Mauvaise projection (attendu: {model.crs})", layername=model.layername)
  191. def _validate_structure(self, model, features):
  192. v = CerberusValidator(model.schema, purge_unknown=True, error_handler=CerberusErrorHandler, require_all=True)
  193. for feature in features:
  194. attributes = dict(zip([f.name() for f in feature.fields()], feature.attributes()))
  195. v.validate(attributes)
  196. for field, verrors in v.errors.items():
  197. for err in verrors:
  198. self.log_error(_translate_messages(err), layername=model.layername, field=field)
  199. def test_structure_arteres(self):
  200. """ Structure des données: Artères """
  201. self._validate_structure(Artere, self.arteres)
  202. def test_structure_cables(self):
  203. """ Structure des données: Cables """
  204. self._validate_structure(Cable, self.cables)
  205. def test_structure_equipements(self):
  206. """ Structure des données: Equipements """
  207. self._validate_structure(Equipement, self.equipements)
  208. def test_structure_noeuds(self):
  209. """ Structure des données: Noeuds """
  210. self._validate_structure(Noeud, self.noeuds)
  211. def test_structure_tranchees(self):
  212. """ Structure des données: Tranchées """
  213. self._validate_structure(Tranchee, self.tranchees)
  214. def test_structure_zapbos(self):
  215. """ Structure des données: Zapbos """
  216. self._validate_structure(Zapbo, self.zapbos)
  217. def test_geometry_validity(self):
  218. """ Contrôle de la validité des géométries """
  219. for model in models:
  220. for f in self.dataset[model]:
  221. if not f.geometry().isGeosValid():
  222. self.log_error("La géométrie de l'objet est invalide", layername=model.layername, field="geom")
  223. def test_geometry_type(self):
  224. for model in models:
  225. for f in self.dataset[model]:
  226. if QgsWkbTypes.singleType(f.geometry().wkbType()) != model.geom_type:
  227. self.log_error("Type de géométrie invalide (attendu: {})".format(QgsModel.GEOM_NAMES[model.geom_type]), layername=model.layername, field="geom")
  228. def test_bounding_box(self):
  229. for model in models:
  230. xmin, ymin, xmax, ymax = model.bounding_box
  231. for f in self.dataset[model]:
  232. bb = f.geometry().boundingBox()
  233. x1, y1, x2, y2 = (bb.xMinimum(), bb.yMinimum(), bb.xMaximum(), bb.yMaximum())
  234. if any(x < xmin or x > xmax for x in (x1, x2)) or \
  235. any(y < ymin or y > ymax for y in (y1, y2)):
  236. self.log_error("Hors de l'emprise autorisée", layername=model.layername, field="geom")
  237. def test_duplicates(self):
  238. """ Recherche de doublons """
  239. # TODO: séparer le chargement des données et le contrôle des doublons
  240. self.noeuds = {}
  241. for noeud in self.dataset[Noeud]:
  242. if not noeud.NO_NOM in self.noeuds:
  243. self.noeuds[noeud.NO_NOM] = noeud
  244. else:
  245. self.log_error("Doublons dans le champs: {}".format(noeud), layername=Noeud.layername, field="NO_NOM")
  246. self.equipements = {}
  247. for equipement in self.dataset[Equipement]:
  248. if not equipement.EQ_NOM in self.equipements:
  249. self.equipements[equipement.EQ_NOM] = equipement
  250. else:
  251. self.log_error("Doublons dans le champs: {}".format(equipement), layername=Equipement.layername, field="EQ_NOM")
  252. self.zapbos = {}
  253. for zapbo in self.dataset[Zapbo]:
  254. if not zapbo.ID_ZAPBO in self.zapbos:
  255. self.zapbos[zapbo.ID_ZAPBO] = zapbo
  256. else:
  257. self.log_error("Doublons dans le champs: {}".format(zapbo), layername=Zapbo.layername, field="ID_ZAPBO")
  258. def test_constraints(self):
  259. """ Contrôle des contraintes relationnelles """
  260. # rattachement les noeuds aux artères
  261. for artere in self.arteres:
  262. try:
  263. artere.noeud_a = self.noeuds[artere.AR_NOEUD_A]
  264. except KeyError:
  265. artere.noeud_a = None
  266. self.log_error(RelationError("Le noeud '{}' n'existe pas".format(artere.AR_NOEUD_A), layername=Artere.layername, field="AR_NOEUD_A"))
  267. try:
  268. artere.noeud_b = self.noeuds[artere.AR_NOEUD_B]
  269. except KeyError:
  270. artere.noeud_b = None
  271. self.log_error(RelationError("Le noeud '{}' n'existe pas".format(artere.AR_NOEUD_B), layername=Artere.layername, field="AR_NOEUD_A"))
  272. # rattachement des equipements aux cables
  273. for cable in self.cables:
  274. try:
  275. cable.equipement_a = self.equipements[cable.CA_EQ_A]
  276. except KeyError:
  277. cable.equipement_a = None
  278. self.log_error(RelationError("L'équipement '{}' n'existe pas".format(cable.CA_EQ_A), layername=Cable.layername, field="CA_EQ_A"))
  279. try:
  280. cable.equipement_b = self.equipements[cable.CA_EQ_B]
  281. except KeyError:
  282. cable.equipement_b = None
  283. self.log_error(RelationError("L'équipement '{}' n'existe pas".format(cable.CA_EQ_B), layername=Cable.layername, field="CA_EQ_B"))
  284. # rattachement des equipements aux noeuds
  285. for equipement in self.equipements.values():
  286. try:
  287. equipement.noeud = self.noeuds[equipement.EQ_NOM_NOE]
  288. except KeyError:
  289. equipement.noeud = None
  290. self.log_error(RelationError("Le noeud '{}' n'existe pas".format(equipement.EQ_NOM_NOE, equipement.EQ_NOM), layername=Equipement.layername, field="EQ_NOM_NOE"))
  291. # verifie que tous les equipements sont l'equipement B d'au moins un cable
  292. equipements_b = [cable.CA_EQ_B for cable in self.cables]
  293. for eq_id in self.equipements:
  294. if self.equipements[eq_id].EQ_TYPE == "BAI":
  295. continue
  296. if not eq_id in equipements_b:
  297. self.log_error(RelationError("L'equipement '{}' n'est l'équipement B d'aucun cable".format(eq_id), layername=Equipement.layername, field="EQ_NOM"))
  298. def test_graphic_duplicates(self):
  299. """ Recherche de doublons graphiques """
  300. # controle des doublons graphiques
  301. for i, tranchee in enumerate(self.tranchees):
  302. for other in self.tranchees[i+1:]:
  303. if tranchee.geom == other.geom:
  304. self.log_error(DuplicatedGeom("Une entité graphique est dupliquée".format(tranchee), layername=Tranchee.layername, field="geom"))
  305. for i, artere in enumerate(self.arteres):
  306. for other in self.arteres[i+1:]:
  307. if artere.geom == other.geom:
  308. self.log_error(DuplicatedGeom("Une entité graphique est dupliquée ('{}')".format(artere), layername=Artere.layername, field="geom"))
  309. for i, cable in enumerate(self.cables):
  310. for other in self.cables[i+1:]:
  311. if cable.geom == other.geom and cable.CA_EQ_A == other.CA_EQ_A and cable.CA_EQ_B == other.CA_EQ_B:
  312. self.log_error(DuplicatedGeom("Une entité graphique est dupliquée ('{}')".format(cable), layername=Cable.layername, field="geom"))
  313. ls_noeuds = list(self.noeuds.values())
  314. for i, noeud in enumerate(ls_noeuds):
  315. for other in ls_noeuds[i+1:]:
  316. if noeud.geom == other.geom:
  317. self.log_error(DuplicatedGeom("Une entité graphique est dupliquée ('{}')".format(noeud), layername=Noeud.layername, field="geom"))
  318. del ls_noeuds
  319. ls_zapbos = list(self.zapbos.values())
  320. for i, zapbo in enumerate(ls_zapbos):
  321. for other in ls_zapbos[i+1:]:
  322. if zapbo.geom == other.geom:
  323. self.log_error(DuplicatedGeom("Une entité graphique est dupliquée ('{}')".format(zapbo), layername=Zapbo.layername, field="geom"))
  324. del ls_zapbos
  325. def test_positions_noeuds(self):
  326. """ Contrôle de la position des noeuds """
  327. # Arteres: comparer la géométrie à celle des noeuds
  328. for artere in self.arteres:
  329. if not artere.noeud_a or not artere.noeud_b:
  330. continue
  331. if not any(((artere.points[0].distanceSquared(artere.noeud_a.points[0]) <= TOLERANCE and \
  332. artere.points[-1].distanceSquared(artere.noeud_b.points[0]) <= TOLERANCE),
  333. (artere.points[0].distanceSquared(artere.noeud_b.points[0]) <= TOLERANCE and \
  334. artere.points[-1].distanceSquared(artere.noeud_a.points[0]) <= TOLERANCE))):
  335. self.log_error(MissingItem("Pas de noeud aux coordonnées attendues ('{}')".format(artere), layername=Artere.layername, field="geom"))
  336. def test_positions_equipements(self):
  337. """ Contrôle de la position des équipements """
  338. # Cables: comparer la géométrie à celle des equipements (on utilise en fait la geom du noeud correspondant à l'équipement)
  339. for cable in self.cables:
  340. 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:
  341. continue
  342. if not any(((cable.points[0].distanceSquared(cable.equipement_a.noeud.points[0]) <= TOLERANCE and \
  343. cable.points[-1].distanceSquared(cable.equipement_b.noeud.points[0]) <= TOLERANCE),
  344. (cable.points[0].distanceSquared(cable.equipement_b.noeud.points[0]) <= TOLERANCE and \
  345. cable.points[-1].distanceSquared(cable.equipement_a.noeud.points[0]) <= TOLERANCE))):
  346. self.log_error(MissingItem("Pas d'equipement aux coordonnées attendues ('{}')".format(cable), layername=Cable.layername, field="geom"))
  347. def test_tranchee_artere(self):
  348. """ Chaque tranchée a au moins une artère """
  349. arteres_full_buffer = QgsGeometry().unaryUnion([a.geom for a in self.arteres]).buffer(TOLERANCE, 100)
  350. for tranchee in self.tranchees:
  351. if not arteres_full_buffer.contains(tranchee.geom):
  352. self.log_error(MissingItem("Tranchée ou portion de tranchée sans artère ('{}')".format(tranchee), layername=Tranchee.layername, field="*"))
  353. def test_cable_artere(self):
  354. """ Chaque cable a au moins une artère (sauf baguettes) """
  355. arteres_full_buffer = QgsGeometry().unaryUnion([a.geom for a in self.arteres]).buffer(TOLERANCE, 100)
  356. # Verifie que chaque cable a au moins une artère (sauf si commentaire contient 'baguette')
  357. for cable in self.cables:
  358. if "baguette" in cable.CA_COMMENT.lower() or not cable.is_geometry_valid():
  359. continue
  360. if not arteres_full_buffer.contains(cable.geom):
  361. self.log_error(MissingItem("Cable ou portion de cable sans artère ('{}')".format(cable), layername=Cable.layername, field="*"))
  362. def test_artere_cable(self):
  363. """ Chaque artère a au moins une cable (sauf cas spécifiques) """
  364. # Verifie que chaque artère a au moins un cable (sauf si commentaire contient un de ces mots 'racco client adductio attente bus 'sans cable'')
  365. cables_full_buffer = QgsGeometry().unaryUnion([c.geom for c in self.cables]).buffer(TOLERANCE, 100)
  366. for artere in self.arteres:
  367. if any(x in artere.AR_COMMENT.lower() for x in ['racco','client','adductio','attente','bus','sans cable']):
  368. continue
  369. if not cables_full_buffer.contains(artere.geom):
  370. self.log_error(MissingItem("Artère sans cable ('{}')".format(artere), layername=Artere.layername, field="*"))
  371. def test_dimensions(self):
  372. """ Contrôle des dimensions logiques """
  373. for artere in self.arteres:
  374. try:
  375. if not int(artere.AR_FOU_DIS) <= int(artere.AR_NB_FOUR):
  376. self.log_error(DimensionError("Le nombre de fourreaux disponibles doit être inférieur au nombre total ('{}')".format(artere), layername=Artere.layername, field="AR_FOU_DIS"))
  377. except (TypeError, ValueError):
  378. pass
  379. for cable in self.cables:
  380. try:
  381. if not int(cable.CA_NB_FO_U) <= int(cable.CA_NB_FO):
  382. self.log_error(DimensionError("Le nombre de fourreaux utilisés doit être inférieur au nombre total ('{}')".format(cable), layername=Cable.layername, field="CA_NB_FO_U"))
  383. if not int(cable.CA_NB_FO_D) <= int(cable.CA_NB_FO):
  384. self.log_error(DimensionError("Le nombre de fourreaux disponibles doit être inférieur au nombre total ('{}')".format(cable), layername=Cable.layername, field="CA_NB_FO_D"))
  385. except (TypeError, ValueError):
  386. pass
  387. def test_pbos(self):
  388. """ PBO / ZAPBO """
  389. # 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
  390. for equipement in self.equipements.values():
  391. if not equipement.EQ_TYPE == "PBO":
  392. continue
  393. #zapbos englobant l'equipement
  394. candidates = []
  395. for zapbo in self.zapbos.values():
  396. if zapbo.geom.contains(equipement.geom):
  397. candidates.append(zapbo)
  398. # le pbo doit être contenu dans une zapbo
  399. if not candidates:
  400. self.log_error(MissingItem("Le PBO n'est contenu dans aucune ZAPBO: {}".format(equipement), layername=Equipement.layername, field="geom"))
  401. continue
  402. # On se base sur le nom pour trouver la zapbo correspondante
  403. try:
  404. equipement.zapbo = next((z for z in candidates if equipement.EQ_NOM in z.ID_ZAPBO))
  405. except StopIteration:
  406. self.log_error(MissingItem("Le nom du PBO ne coincide avec le nom d'aucune des ZAPBO qui le contient: {}".format(equipement), layername=Equipement.layername, field="EQ_NOM"))
  407. break
  408. # TODO: revoir et déplacer le calcul du nombre de prises
  409. if not hasattr(equipement.zapbo, "nb_prises") or equipement.zapbo.nb_prises is None:
  410. equipement.zapbo.nb_prises = 0
  411. def test_pbo_dimension(self):
  412. """ Dimensionnement des PBO """
  413. for equipement in self.equipements.values():
  414. if not equipement.EQ_TYPE == "PBO":
  415. continue
  416. # Controle du dimensionnement des PBO
  417. if equipement.EQ_TYPE_PH == 'PBO 6' and not equipement.zapbo.nb_prises < 6:
  418. self.log_error(DimensionError("Le PBO 6 contient plus de 5 prises: {}".format(equipement), layername=Equipement.layername, field="*"))
  419. if equipement.EQ_TYPE_PH == 'PBO 12' and not equipement.zapbo.nb_prises >= 6 and equipement.zapbo.nb_prises <= 8:
  420. self.log_error(DimensionError("Le PBO 12 contient mois de 6 prises ou plus de 8 prises: {}".format(equipement), layername=Equipement.layername, field="*"))
  421. if equipement.zapbo.STATUT == "REC" and not equipement.EQ_STATUT == "REC":
  422. self.log_error(TechnicalValidationError("Le statut du PBO n'est pas cohérent avec le statut de sa ZAPBO: {}".format(equipement), layername=Equipement.layername, field="*"))
  423. if equipement.EQ_STATUT == "REC" and not equipement.zapbo.STATUT == "REC" and not equipement.zapbo.ID_ZAPBO[:4].lower() == "att_":
  424. self.log_error(TechnicalValidationError("Le statut du PBO n'est pas cohérent avec le statut de sa ZAPBO: {}".format(equipement), layername=Equipement.layername, field="*"))