xtgeo 4.8.0__cp313-cp313-macosx_11_0_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of xtgeo might be problematic. Click here for more details.

Files changed (117) hide show
  1. cxtgeo.py +582 -0
  2. cxtgeoPYTHON_wrap.c +20938 -0
  3. xtgeo/__init__.py +246 -0
  4. xtgeo/_cxtgeo.cpython-313-darwin.so +0 -0
  5. xtgeo/_internal.cpython-313-darwin.so +0 -0
  6. xtgeo/common/__init__.py +19 -0
  7. xtgeo/common/_angles.py +29 -0
  8. xtgeo/common/_xyz_enum.py +50 -0
  9. xtgeo/common/calc.py +396 -0
  10. xtgeo/common/constants.py +30 -0
  11. xtgeo/common/exceptions.py +42 -0
  12. xtgeo/common/log.py +93 -0
  13. xtgeo/common/sys.py +166 -0
  14. xtgeo/common/types.py +18 -0
  15. xtgeo/common/version.py +21 -0
  16. xtgeo/common/xtgeo_dialog.py +604 -0
  17. xtgeo/cube/__init__.py +9 -0
  18. xtgeo/cube/_cube_export.py +214 -0
  19. xtgeo/cube/_cube_import.py +532 -0
  20. xtgeo/cube/_cube_roxapi.py +180 -0
  21. xtgeo/cube/_cube_utils.py +287 -0
  22. xtgeo/cube/_cube_window_attributes.py +340 -0
  23. xtgeo/cube/cube1.py +1023 -0
  24. xtgeo/grid3d/__init__.py +15 -0
  25. xtgeo/grid3d/_ecl_grid.py +774 -0
  26. xtgeo/grid3d/_ecl_inte_head.py +148 -0
  27. xtgeo/grid3d/_ecl_logi_head.py +71 -0
  28. xtgeo/grid3d/_ecl_output_file.py +81 -0
  29. xtgeo/grid3d/_egrid.py +1004 -0
  30. xtgeo/grid3d/_find_gridprop_in_eclrun.py +625 -0
  31. xtgeo/grid3d/_grdecl_format.py +266 -0
  32. xtgeo/grid3d/_grdecl_grid.py +388 -0
  33. xtgeo/grid3d/_grid3d.py +29 -0
  34. xtgeo/grid3d/_grid3d_fence.py +181 -0
  35. xtgeo/grid3d/_grid3d_utils.py +228 -0
  36. xtgeo/grid3d/_grid_boundary.py +76 -0
  37. xtgeo/grid3d/_grid_etc1.py +1566 -0
  38. xtgeo/grid3d/_grid_export.py +221 -0
  39. xtgeo/grid3d/_grid_hybrid.py +66 -0
  40. xtgeo/grid3d/_grid_import.py +79 -0
  41. xtgeo/grid3d/_grid_import_ecl.py +101 -0
  42. xtgeo/grid3d/_grid_import_roff.py +135 -0
  43. xtgeo/grid3d/_grid_import_xtgcpgeom.py +375 -0
  44. xtgeo/grid3d/_grid_refine.py +125 -0
  45. xtgeo/grid3d/_grid_roxapi.py +292 -0
  46. xtgeo/grid3d/_grid_wellzone.py +165 -0
  47. xtgeo/grid3d/_gridprop_export.py +178 -0
  48. xtgeo/grid3d/_gridprop_import_eclrun.py +164 -0
  49. xtgeo/grid3d/_gridprop_import_grdecl.py +130 -0
  50. xtgeo/grid3d/_gridprop_import_roff.py +52 -0
  51. xtgeo/grid3d/_gridprop_import_xtgcpprop.py +168 -0
  52. xtgeo/grid3d/_gridprop_lowlevel.py +171 -0
  53. xtgeo/grid3d/_gridprop_op1.py +174 -0
  54. xtgeo/grid3d/_gridprop_roxapi.py +239 -0
  55. xtgeo/grid3d/_gridprop_value_init.py +140 -0
  56. xtgeo/grid3d/_gridprops_import_eclrun.py +344 -0
  57. xtgeo/grid3d/_gridprops_import_roff.py +83 -0
  58. xtgeo/grid3d/_roff_grid.py +469 -0
  59. xtgeo/grid3d/_roff_parameter.py +303 -0
  60. xtgeo/grid3d/grid.py +2537 -0
  61. xtgeo/grid3d/grid_properties.py +699 -0
  62. xtgeo/grid3d/grid_property.py +1341 -0
  63. xtgeo/grid3d/types.py +15 -0
  64. xtgeo/io/__init__.py +1 -0
  65. xtgeo/io/_file.py +592 -0
  66. xtgeo/metadata/__init__.py +17 -0
  67. xtgeo/metadata/metadata.py +431 -0
  68. xtgeo/roxutils/__init__.py +7 -0
  69. xtgeo/roxutils/_roxar_loader.py +54 -0
  70. xtgeo/roxutils/_roxutils_etc.py +122 -0
  71. xtgeo/roxutils/roxutils.py +207 -0
  72. xtgeo/surface/__init__.py +18 -0
  73. xtgeo/surface/_regsurf_boundary.py +26 -0
  74. xtgeo/surface/_regsurf_cube.py +210 -0
  75. xtgeo/surface/_regsurf_cube_window.py +391 -0
  76. xtgeo/surface/_regsurf_cube_window_v2.py +297 -0
  77. xtgeo/surface/_regsurf_cube_window_v3.py +360 -0
  78. xtgeo/surface/_regsurf_export.py +388 -0
  79. xtgeo/surface/_regsurf_grid3d.py +271 -0
  80. xtgeo/surface/_regsurf_gridding.py +347 -0
  81. xtgeo/surface/_regsurf_ijxyz_parser.py +278 -0
  82. xtgeo/surface/_regsurf_import.py +347 -0
  83. xtgeo/surface/_regsurf_lowlevel.py +122 -0
  84. xtgeo/surface/_regsurf_oper.py +631 -0
  85. xtgeo/surface/_regsurf_roxapi.py +241 -0
  86. xtgeo/surface/_regsurf_utils.py +81 -0
  87. xtgeo/surface/_surfs_import.py +43 -0
  88. xtgeo/surface/_zmap_parser.py +138 -0
  89. xtgeo/surface/regular_surface.py +2967 -0
  90. xtgeo/surface/surfaces.py +276 -0
  91. xtgeo/well/__init__.py +24 -0
  92. xtgeo/well/_blockedwell_roxapi.py +221 -0
  93. xtgeo/well/_blockedwells_roxapi.py +68 -0
  94. xtgeo/well/_well_aux.py +30 -0
  95. xtgeo/well/_well_io.py +327 -0
  96. xtgeo/well/_well_oper.py +574 -0
  97. xtgeo/well/_well_roxapi.py +304 -0
  98. xtgeo/well/_wellmarkers.py +486 -0
  99. xtgeo/well/_wells_utils.py +158 -0
  100. xtgeo/well/blocked_well.py +216 -0
  101. xtgeo/well/blocked_wells.py +122 -0
  102. xtgeo/well/well1.py +1514 -0
  103. xtgeo/well/wells.py +211 -0
  104. xtgeo/xyz/__init__.py +6 -0
  105. xtgeo/xyz/_polygons_oper.py +272 -0
  106. xtgeo/xyz/_xyz.py +741 -0
  107. xtgeo/xyz/_xyz_data.py +646 -0
  108. xtgeo/xyz/_xyz_io.py +490 -0
  109. xtgeo/xyz/_xyz_lowlevel.py +42 -0
  110. xtgeo/xyz/_xyz_oper.py +613 -0
  111. xtgeo/xyz/_xyz_roxapi.py +766 -0
  112. xtgeo/xyz/points.py +681 -0
  113. xtgeo/xyz/polygons.py +811 -0
  114. xtgeo-4.8.0.dist-info/METADATA +145 -0
  115. xtgeo-4.8.0.dist-info/RECORD +117 -0
  116. xtgeo-4.8.0.dist-info/WHEEL +6 -0
  117. xtgeo-4.8.0.dist-info/licenses/LICENSE.md +165 -0
xtgeo/xyz/polygons.py ADDED
@@ -0,0 +1,811 @@
1
+ """XTGeo xyz.polygons module, which contains the Polygons class."""
2
+
3
+ # For polygons, the order of the points sequence is important. In
4
+ # addition, a Polygons dataframe _must_ have a INT column called 'POLY_ID'
5
+ # which identifies each polygon piece.
6
+ from __future__ import annotations
7
+
8
+ import warnings
9
+ from copy import deepcopy
10
+ from typing import TYPE_CHECKING, Any
11
+
12
+ import numpy as np
13
+ import pandas as pd
14
+ import shapely.geometry as sg
15
+
16
+ from xtgeo.common._xyz_enum import _AttrName, _XYZType
17
+ from xtgeo.common.exceptions import InvalidFileFormatError
18
+ from xtgeo.common.log import null_logger
19
+ from xtgeo.common.sys import inherit_docstring
20
+ from xtgeo.io._file import FileFormat, FileWrapper
21
+ from xtgeo.xyz import _xyz_io, _xyz_roxapi
22
+
23
+ from . import _polygons_oper, _xyz_oper
24
+ from ._xyz import XYZ
25
+ from ._xyz_io import _convert_idbased_xyz
26
+
27
+ if TYPE_CHECKING:
28
+ import io
29
+ import pathlib
30
+
31
+ from xtgeo.well.well1 import Well
32
+
33
+ logger = null_logger(__name__)
34
+
35
+
36
+ def _data_reader_factory(file_format: FileFormat):
37
+ if file_format == FileFormat.XYZ:
38
+ return _xyz_io.import_xyz
39
+ if file_format == FileFormat.ZMAP_ASCII:
40
+ return _xyz_io.import_zmap
41
+
42
+ extensions = FileFormat.extensions_string([FileFormat.XYZ, FileFormat.ZMAP_ASCII])
43
+ raise InvalidFileFormatError(
44
+ f"File format {file_format} is invalid for type Polygons. "
45
+ f"Supported formats are {extensions}."
46
+ )
47
+
48
+
49
+ def _file_importer(
50
+ pfile: str | pathlib.Path | io.BytesIO,
51
+ fformat: str | None = None,
52
+ ):
53
+ """General function for polygons_from_file"""
54
+ pfile = FileWrapper(pfile)
55
+ fmt = pfile.fileformat(fformat)
56
+ kwargs = _data_reader_factory(fmt)(pfile)
57
+
58
+ if "POLY_ID" not in kwargs["values"].columns:
59
+ kwargs["values"]["POLY_ID"] = (
60
+ kwargs["values"].isnull().all(axis=1).cumsum().dropna()
61
+ )
62
+ kwargs["values"].dropna(axis=0, inplace=True)
63
+ kwargs["values"].reset_index(inplace=True, drop=True)
64
+ kwargs["name"] = "poly"
65
+ return kwargs
66
+
67
+
68
+ def _roxar_importer(
69
+ project: str | Any,
70
+ name: str,
71
+ category: str,
72
+ stype: str = "horizons",
73
+ realisation: int = 0,
74
+ attributes: bool | list[str] = False,
75
+ ): # pragma: no cover
76
+ kwargs = _xyz_roxapi.load_xyz_from_rms(
77
+ project, name, category, stype, realisation, attributes, _XYZType.POLYGONS.value
78
+ )
79
+
80
+ kwargs["name"] = name if name else "poly"
81
+ return kwargs
82
+
83
+
84
+ def _wells_importer(
85
+ wells: list[Well],
86
+ zone: int | None = None,
87
+ resample: int | None = 1,
88
+ ):
89
+ """Get line segments from a list of wells and a single zone number.
90
+
91
+ A future extension is that zone could be a list of zone numbers and/or mechanisms
92
+ to retrieve well segments by other measures, e.g. >= depth.
93
+ """
94
+
95
+ dflist = []
96
+ maxid = 0
97
+ for well in wells:
98
+ wp = well.get_zone_interval(zone, resample=resample)
99
+ if wp is not None:
100
+ wp["WellName"] = well.name
101
+ # as well segments may have overlapping POLY_ID:
102
+ wp["POLY_ID"] += maxid
103
+ maxid = wp["POLY_ID"].max() + 1
104
+ dflist.append(wp)
105
+
106
+ if not dflist:
107
+ return {}
108
+ dfr = pd.concat(dflist, ignore_index=True)
109
+ dfr.reset_index(inplace=True, drop=True)
110
+ return {
111
+ "values": dfr,
112
+ "attributes": {"WellName": "str"},
113
+ }
114
+
115
+
116
+ def polygons_from_file(pfile: str | pathlib.Path, fformat: str | None = "guess"):
117
+ """Make an instance of a Polygons object directly from file import.
118
+
119
+ Supported formats are:
120
+
121
+ * 'xyz' or 'pol': Simple XYZ format
122
+ * 'zmap': ZMAP line format as exported from RMS (e.g. fault lines)
123
+ * 'guess': Try to choose file format based on extension
124
+
125
+ Args:
126
+ pfile (str): Name of file
127
+ fformat (str): See :meth:`Polygons.from_file`
128
+
129
+ Example::
130
+
131
+ import xtgeo
132
+ mypoly = xtgeo.polygons_from_file('somefile.xyz')
133
+ """
134
+ return Polygons(**_file_importer(pfile, fformat=fformat))
135
+
136
+
137
+ def polygons_from_roxar(
138
+ project: str | Any,
139
+ name: str,
140
+ category: str,
141
+ stype: str | None = "horizons",
142
+ realisation: int | None = 0,
143
+ attributes: bool | list[str] = False,
144
+ ): # pragma: no cover
145
+ """Load a Polygons instance from Roxar RMS project.
146
+
147
+ Note also that horizon/zone/faults name and category must exists
148
+ in advance, otherwise an Exception will be raised.
149
+
150
+ Args:
151
+ project: Name of project (as folder) if outside RMS, or just use the magic
152
+ `project` word if within RMS.
153
+ name: Name of polygons item
154
+ category: For horizons/zones/faults: for example 'DL_depth'
155
+ or use a folder notation on clipboard/general2d_data.
156
+ stype: RMS folder type, 'horizons' (default), 'zones', 'clipboard',
157
+ 'faults', 'general2d_data'
158
+ realisation: Realisation number, default is 0
159
+ attributes: Polygons can store an attrubute (e.g. a fault name) per polygon,
160
+ i.e. per "POLY_ID")
161
+
162
+ Example::
163
+
164
+ import xtgeo
165
+ mysurf = xtgeo.polygons_from_roxar(project, 'TopAare', 'DepthPolys')
166
+
167
+ .. versionadded:: 2.19 general2d_data support is added
168
+ .. versionadded:: 3.x support for polygon attributes (other than POLY_ID)
169
+ """
170
+
171
+ stype = "horizons" if stype is None else stype
172
+ realisation = realisation if realisation else 0
173
+
174
+ return Polygons(
175
+ **_roxar_importer(
176
+ project,
177
+ name,
178
+ category,
179
+ stype,
180
+ realisation,
181
+ attributes,
182
+ )
183
+ )
184
+
185
+
186
+ def polygons_from_wells(
187
+ wells: list[Well],
188
+ zone: int | None = 1,
189
+ resample: int | None = 1,
190
+ ):
191
+ """Get polygons from wells and a single zone number.
192
+
193
+ Args:
194
+ wells: List of XTGeo well objects, a single XTGeo well or a list of well files.
195
+ If a list of well files, the routine will try to load well based on file
196
+ signature and/or extension, but only default settings are applied. Hence
197
+ this is less flexible and more fragile.
198
+ zone: The zone number to extract the linepiece from
199
+ resample: If given, resample every N'th sample to make
200
+ polylines smaller in terms of bits and bytes.
201
+ 1 = No resampling, which means just use well sampling (which can be rather
202
+ dense; typically 15 cm).
203
+
204
+
205
+ Returns:
206
+ None if empty data, otherwise a Polygons() instance.
207
+
208
+ Example::
209
+
210
+ wells = ["w1.w", "w2.w"]
211
+ points = xtgeo.polygons_from_wells(wells, zone=2)
212
+ """
213
+ return Polygons(**_wells_importer(wells, zone, resample))
214
+
215
+
216
+ def _generate_docstring_polygons(
217
+ xname, yname, zname, pname, hname, dhname, tname, dtname
218
+ ):
219
+ return f"""
220
+ Class for a Polygons object (connected points) in the XTGeo framework.
221
+
222
+ The term Polygons is here used in a wider context, as it includes
223
+ polylines that do not connect into closed polygons. A Polygons
224
+ instance may contain several pieces of polylines/polygons, which are
225
+ identified by POLY_ID.
226
+
227
+ The polygons are stored in Python as a Pandas dataframe, which
228
+ allow for flexible manipulation and fast execution.
229
+
230
+ A Polygons instance will have 4 mandatory columns; here by default names:
231
+
232
+ * {xname} - for X UTM coordinate (Easting)
233
+ * {yname} - For Y UTM coordinate (Northing)
234
+ * {zname} - For depth or property from mean SeaLevel; Depth positive down
235
+ * {pname} - for polygon ID as there may be several polylines segments
236
+
237
+ Each Polygons instance can also a name (through the name attribute).
238
+ Default is 'poly'. E.g. if a well fence, it is logical to name the
239
+ instance to be the same as the well name.
240
+
241
+ Args:
242
+ values: Provide input values on various forms (list-like or dataframe).
243
+ xname: Name of first (X) mandatory column.
244
+ yname: Name of second (Y) mandatory column.
245
+ zname: Name of third (Z) mandatory column.
246
+ pname: Name of forth (P) mandatory enumerating column.
247
+ hname: Name of cumulative horizontal length, defaults to "{hname}" if
248
+ in dataframe otherwise None.
249
+ dhname: Name of delta horizontal length, defaults to "{dhname}" if in
250
+ dataframe otherwise None.
251
+ tname: Name of cumulative total length, defaults to "{tname}" if in
252
+ dataframe otherwise None.
253
+ dtname: Name of delta total length, defaults to "{dtname}" if in
254
+ dataframe otherwise None.
255
+ attributes: A dictionary for attribute columns as 'name: type', e.g.
256
+ {{"WellName": "str", "IX": "int"}}. This is applied when values are input
257
+ and is to name and type the extra attribute columns in a polygons set.
258
+
259
+ Note:
260
+ Most export/import file formats do not support additional attributes; only the
261
+ three first columns (X, Y, Z) are fully supported.
262
+ """
263
+
264
+
265
+ class Polygons(XYZ):
266
+ __doc__ = _generate_docstring_polygons(
267
+ _AttrName.XNAME.value,
268
+ _AttrName.YNAME.value,
269
+ _AttrName.ZNAME.value,
270
+ _AttrName.PNAME.value,
271
+ _AttrName.HNAME.value,
272
+ _AttrName.DHNAME.value,
273
+ _AttrName.TNAME.value,
274
+ _AttrName.DTNAME.value,
275
+ )
276
+
277
+ def __init__(
278
+ self,
279
+ values: list | np.ndarray | pd.DataFrame = None,
280
+ xname: str = _AttrName.XNAME.value,
281
+ yname: str = _AttrName.YNAME.value,
282
+ zname: str = _AttrName.ZNAME.value,
283
+ pname: str = _AttrName.PNAME.value,
284
+ hname: str = _AttrName.R_HLEN_NAME.value,
285
+ dhname: str = _AttrName.DHNAME.value,
286
+ tname: str = _AttrName.TNAME.value,
287
+ dtname: str = _AttrName.DTNAME.value,
288
+ name: str = "poly",
289
+ attributes: dict | None = None,
290
+ # from legacy initialization, remove in 4.0, undocumented by purpose:
291
+ fformat: str = "guess",
292
+ filesrc: str = None,
293
+ ):
294
+ self._xyztype: str = _XYZType.POLYGONS.value
295
+
296
+ super().__init__(self._xyztype, xname, yname, zname)
297
+ self._pname = pname
298
+
299
+ if values is None:
300
+ values = []
301
+
302
+ self._attrs = attributes if attributes is not None else {}
303
+ self._filesrc = filesrc
304
+
305
+ # additional optional state properties for Polygons
306
+ self._hname = hname
307
+ self._dhname = dhname
308
+ self._tname = tname
309
+ self._dtname = dtname
310
+ self._name = name
311
+
312
+ if not isinstance(values, pd.DataFrame):
313
+ self._df = _xyz_io._from_list_like(
314
+ values, self._zname, attributes, self._xyztype
315
+ )
316
+ else:
317
+ self._df = values
318
+ self._dataframe_consistency_check()
319
+
320
+ @property
321
+ def name(self):
322
+ """Returns or sets the name of the instance."""
323
+ return self._name
324
+
325
+ @name.setter
326
+ def name(self, newname):
327
+ self._name = newname
328
+
329
+ @property
330
+ def pname(self):
331
+ return self._pname
332
+
333
+ @pname.setter
334
+ def pname(self, name):
335
+ super()._check_name_and_replace(self._pname, name)
336
+ self._pname = name
337
+
338
+ @property
339
+ def hname(self):
340
+ """Returns or set the name of the cumulative horizontal length.
341
+
342
+ If the column does not exist, None is returned. Default name is H_CUMLEN.
343
+
344
+ .. versionadded:: 2.1
345
+ """
346
+ return self._hname
347
+
348
+ @hname.setter
349
+ def hname(self, name):
350
+ super()._check_name_and_replace(self._hname, name)
351
+ self._hname = name
352
+
353
+ @property
354
+ def dhname(self):
355
+ """Returns or set the name of the delta horizontal length column if it exists.
356
+
357
+ If the column does not exist, None is returned. Default name is H_DELTALEN.
358
+
359
+ .. versionadded:: 2.1
360
+ """
361
+ return self._dhname
362
+
363
+ @dhname.setter
364
+ def dhname(self, name):
365
+ super()._check_name_and_replace(self._dhname, name)
366
+ self._dhname = name
367
+
368
+ @property
369
+ def tname(self):
370
+ """Returns or set the name of the cumulative total length column if it exists.
371
+
372
+ .. versionadded:: 2.1
373
+ """
374
+ return self._tname
375
+
376
+ @tname.setter
377
+ def tname(self, name):
378
+ super()._check_name_and_replace(self._tname, name)
379
+ self._tname = name
380
+
381
+ @property
382
+ def dtname(self):
383
+ """Returns or set the name of the delta total length column if it exists.
384
+
385
+ .. versionadded:: 2.1
386
+ """
387
+ return self._dtname
388
+
389
+ @dtname.setter
390
+ def dtname(self, name):
391
+ super()._check_name_and_replace(self._dtname, name)
392
+ self._dtname = name
393
+
394
+ @property
395
+ def dataframe(self) -> pd.DataFrame:
396
+ """Returns or set the Pandas dataframe object."""
397
+ warnings.warn(
398
+ "Direct access to the dataframe property in Polygons class will be "
399
+ "deprecated in xtgeo 5.0. Use `get_dataframe()` instead.",
400
+ PendingDeprecationWarning,
401
+ )
402
+ return self._df
403
+
404
+ @dataframe.setter
405
+ def dataframe(self, df):
406
+ warnings.warn(
407
+ "Direct access to the dataframe property in Polygons class will be "
408
+ "deprecated in xtgeo 5.0. Use `set_dataframe()` instead.",
409
+ PendingDeprecationWarning,
410
+ )
411
+ self.set_dataframe(df)
412
+
413
+ def get_dataframe(self, copy: bool = True) -> pd.DataFrame:
414
+ """Returns the Pandas dataframe object.
415
+
416
+ Args:
417
+ copy: If True, return a deep copy of the dataframe
418
+
419
+
420
+ .. versionchanged: 3.7 Add keyword `copy` defaulted to True
421
+ """
422
+ return self._df.copy() if copy else self._df
423
+
424
+ def set_dataframe(self, df):
425
+ self._df = df.apply(deepcopy)
426
+ self._name_to_none_if_missing()
427
+
428
+ def _name_to_none_if_missing(self):
429
+ if self._dtname not in self._df.columns:
430
+ self._dtname = None
431
+ if self._dhname not in self._df.columns:
432
+ self._dhname = None
433
+ if self._tname not in self._df.columns:
434
+ self._tname = None
435
+ if self._hname not in self._df.columns:
436
+ self._hname = None
437
+
438
+ # ----------------------------------------------------------------------------------
439
+ # Class methods
440
+ # ----------------------------------------------------------------------------------
441
+
442
+ @classmethod
443
+ def boundary_from_points(
444
+ cls,
445
+ points,
446
+ alpha_factor: float | None = 1.0,
447
+ alpha: float | None = None,
448
+ convex: bool = False,
449
+ ):
450
+ """Instantiate polygons from detecting the boundary around points.
451
+
452
+ .. image:: images/boundary_polygons.png
453
+ :width: 600
454
+ :align: center
455
+
456
+ |
457
+
458
+ Args:
459
+ points: The XTGeo Points instance to estimate boundary/boundaries around.
460
+ alpha_factor: The alpha factor is a multiplier to alpha. Normally it will
461
+ be around 1, but can be increased to get a looser boundary. Dependent
462
+ on the points topology, it can also be decreased to some extent.
463
+ alpha: The alpha factor for determine the 'precision' in how to delineate
464
+ the polygon. A large value will produce a smoother polygon. The default
465
+ is to detect the value from the data, but note that this default may be
466
+ far from optimal for you needs. Usually use the ``alpha_factor`` to tune
467
+ the best value. The actual alpha applied in the concave hull algorithm
468
+ is alpha_factor multiplied with alpha.
469
+ convex: If True, then compute a maximum boundary (convex), and note that
470
+ alpha_factor and alpha are not applied in ths case. Default is False.
471
+
472
+ Returns:
473
+ A Polygons instance.
474
+
475
+ .. versionadded: 3.1.0
476
+ """
477
+
478
+ return cls(
479
+ _polygons_oper.boundary_from_points(points, alpha_factor, alpha, convex)
480
+ )
481
+
482
+ # ----------------------------------------------------------------------------------
483
+ # Instance methods
484
+ # ----------------------------------------------------------------------------------
485
+ @inherit_docstring(inherit_from=XYZ.protected_columns)
486
+ def protected_columns(self):
487
+ return super().protected_columns() + [self.pname]
488
+
489
+ def to_file(
490
+ self,
491
+ pfile,
492
+ fformat="xyz",
493
+ ):
494
+ """Export Polygons to file.
495
+
496
+ Args:
497
+ pfile (str): Name of file
498
+ fformat (str): File format xyz/poi/pol
499
+
500
+ Returns:
501
+ Number of polygon points exported
502
+ """
503
+
504
+ return _xyz_io.to_file(self, pfile, fformat=fformat, ispolygons=True)
505
+
506
+ def to_roxar(
507
+ self,
508
+ project,
509
+ name,
510
+ category,
511
+ stype="horizons",
512
+ realisation=0,
513
+ attributes=False,
514
+ ): # pragma: no cover
515
+ """Export (store) a Polygons item to a Roxar RMS project.
516
+
517
+ The export to the RMS project can be done either within the project
518
+ or outside the project.
519
+
520
+ Note also that horizon/zone name and category must exists in advance,
521
+ otherwise an Exception will be raised.
522
+
523
+ Note:
524
+ When project is file path (direct access, outside RMS) then
525
+ ``to_roxar()`` will implicitly do a project save. Otherwise, the project
526
+ will not be saved until the user do an explicit project save action.
527
+
528
+ Args:
529
+ project (str or special): Name of project (as folder) if
530
+ outside RMS, og just use the magic project word if within RMS.
531
+ name (str): Name of polygons item
532
+ category (str): For horizons/zones/faults: for example 'DL_depth' and use
533
+ a folder notation for clipboard/general2d_data
534
+ stype (str): RMS folder type, 'horizons' (default), 'zones'
535
+ or 'faults' or 'clipboard' (in prep: well picks)
536
+ realisation (int): Realisation number, default is 0
537
+ attributes (bool): If True, attributes will be preserved (from RMS 13)
538
+
539
+ Raises:
540
+ ValueError: Various types of invalid inputs.
541
+ NotImplementedError: Not supported in this ROXAPI version
542
+
543
+ Note:
544
+ Setting (storing) polygons with attributes is not supported in RMSAPI.
545
+
546
+ .. versionadded:: 2.19 general2d_data support is added
547
+ .. versionadded:: 4.X Added attributes
548
+ """
549
+
550
+ _xyz_roxapi.save_xyz_to_rms(
551
+ self,
552
+ project,
553
+ name,
554
+ category,
555
+ stype,
556
+ None,
557
+ realisation,
558
+ attributes,
559
+ )
560
+
561
+ def copy(self):
562
+ """Returns a deep copy of an instance"""
563
+ mycopy = self.__class__()
564
+ mycopy._xyztype = self._xyztype
565
+ mycopy._df = self._df.apply(deepcopy) # df.copy() is not fully deep!
566
+ mycopy._xname = self._xname
567
+ mycopy._yname = self._yname
568
+ mycopy._zname = self._zname
569
+ mycopy._pname = self._pname
570
+ mycopy._hname = self._hname
571
+ mycopy._dhname = self._dhname
572
+ mycopy._tname = self._tname
573
+ mycopy._dtname = self._dtname
574
+
575
+ if self._attrs:
576
+ mycopy._attrs = dict(self._attrs.items())
577
+
578
+ return mycopy
579
+
580
+ def get_xyz_dataframe(self):
581
+ """Get a dataframe copy from the Polygons points with no ID column.
582
+
583
+ Convert from POLY_ID based to XYZ, where a new polygon is marked with a 999
584
+ value as flag.
585
+ """
586
+ return _convert_idbased_xyz(self, self.get_dataframe())
587
+
588
+ def get_shapely_objects(self):
589
+ """Returns a list of Shapely LineString objects, one per POLY_ID.
590
+
591
+ .. versionadded:: 2.1
592
+ """
593
+ spolys = []
594
+ idgroups = self.get_dataframe(copy=False).groupby(self.pname)
595
+
596
+ for _idx, grp in idgroups:
597
+ pxcor = grp[self.xname].values
598
+ pycor = grp[self.yname].values
599
+ pzcor = grp[self.zname].values
600
+ spoly = sg.LineString(np.stack([pxcor, pycor, pzcor], axis=1))
601
+ spolys.append(spoly)
602
+
603
+ return spolys
604
+
605
+ @inherit_docstring(inherit_from=XYZ.get_boundary)
606
+ def get_boundary(self):
607
+ return super().get_boundary()
608
+
609
+ def simplify(
610
+ self, tolerance: float | None = 0.1, preserve_topology: bool | None = True
611
+ ) -> bool:
612
+ """Simply a polygon, i.e. remove unneccesary points.
613
+
614
+ This is based on `Shapely's simplify() method
615
+ <https://shapely.readthedocs.io/en/latest/manual.html#object.simplify>`_
616
+
617
+ Args:
618
+ tolerance: Cf. Shapely's documentation
619
+ preserve_topology: Default is True, if False a faster algorithm is applied
620
+
621
+ Returns:
622
+ True if simplification is achieved. The polygons instance is
623
+ updated in-place.
624
+
625
+ .. versionadded: 3.1
626
+
627
+
628
+ """
629
+
630
+ return _polygons_oper.simplify_polygons(self, tolerance, preserve_topology)
631
+
632
+ def filter_byid(self, polyid=None):
633
+ """Remove all line segments not in polyid.
634
+
635
+ The instance is updated in-place.
636
+
637
+ Args:
638
+ polyid (int or list of int): Which ID(s) to keep, None means use first.
639
+
640
+ Example::
641
+
642
+ mypoly.filter_byid(polyid=[2, 4]) # keep POLY_ID 2 and 4
643
+
644
+ .. versionadded:: 2.1
645
+ """
646
+ dataframe = self.get_dataframe()
647
+ if polyid is None:
648
+ polyid = int(dataframe[self.pname].iloc[0])
649
+
650
+ if not isinstance(polyid, list):
651
+ polyid = [polyid]
652
+
653
+ dflist = []
654
+ for pid in polyid:
655
+ dflist.append(dataframe[dataframe[self.pname] == pid])
656
+
657
+ dataframe = pd.concat(dflist)
658
+ self.set_dataframe(dataframe)
659
+
660
+ def tlen(self, tname="T_CUMLEN", dtname="T_DELTALEN", atindex=0):
661
+ """Compute and add or replace columns for cum. total 3D length and delta length.
662
+
663
+ The instance is updated in-place.
664
+
665
+ Args:
666
+ tname (str): Name of cumulative total length. Default is T_CUMLEN.
667
+ dtname (str): Name of delta length column. Default is T_DELTALEN.
668
+ atindex (int): Which index which shall be 0.0 for cumulative length.
669
+
670
+ .. versionadded:: 2.1
671
+ """
672
+ _xyz_oper.tlen(self, tname=tname, dtname=dtname, atindex=atindex)
673
+
674
+ def hlen(self, hname="H_CUMLEN", dhname="H_DELTALEN", atindex=0):
675
+ """Compute and add/replace columns for cum. horizontal length and delta length.
676
+
677
+ The instance is updated in-place.
678
+
679
+ Args:
680
+ hname (str): Name of cumulative horizontal length. Default is H_CUMLEN.
681
+ dhname (str): Name of delta length column. Default is H_DELTALEN.
682
+ atindex (int): Which index which shall be 0.0 for cumulative length.
683
+
684
+ .. versionadded:: 2.1
685
+ """
686
+ _xyz_oper.hlen(self, hname=hname, dhname=dhname, atindex=atindex)
687
+
688
+ def extend(self, distance, nsamples=1, mode2d=True):
689
+ """Extend polyline by `distance` at both ends, nsmaples times.
690
+
691
+ The instance is updated in-place.
692
+
693
+ Args:
694
+ distance (float): The horizontal distance (sampling) to extend
695
+ nsamples (int): Number of samples to extend.
696
+ mode2d (bool): XY extension (only True is supported)
697
+
698
+ .. versionadded:: 2.1
699
+ """
700
+ _xyz_oper.extend(self, distance, nsamples, mode2d)
701
+
702
+ def rescale(self, distance, addlen=False, kind="simple", mode2d=True):
703
+ """Rescale (resample) by using a new increment.
704
+
705
+ The increment (distance) may be a horizontal or a True 3D
706
+ distance dependent on mode2d.
707
+
708
+ The instance is updated in-place.
709
+
710
+ If the distance is larger than the total input poly-line length,
711
+ nothing is done. Note that the result distance may differ from the
712
+ requested distance caused to rounding to fit original length.
713
+
714
+ Hence actual distance is input distance +- 50%.
715
+
716
+ Args:
717
+ distance (float): New distance between points
718
+ addlen (str): If True, total and horizontal cum. and delta length
719
+ columns will be added.
720
+ kind (str): What kind of rescaling: slinear/cubic/simple
721
+ mode2d (bool): The distance may be a 2D (XY) ora 3D (XYZ) mode.
722
+
723
+ .. versionchanged:: 2.1 a new algorithm
724
+
725
+ """
726
+ _xyz_oper.rescale_polygons(
727
+ self, distance=distance, addlen=addlen, kind=kind, mode2d=mode2d
728
+ )
729
+
730
+ def get_fence(
731
+ self, distance=20, atleast=5, nextend=2, name=None, asnumpy=True, polyid=None
732
+ ):
733
+ """Extracts a fence with constant horizontal sampling.
734
+
735
+ Additonal H_CUMLEN and H_DELTALEN vectors will be added, suitable for
736
+ X sections.
737
+
738
+ Args:
739
+ distance (float): New horizontal distance between points
740
+ atleast (int): Minimum number of points. If the true length/atleast is
741
+ less than distance, than distance will be be reset to
742
+ length/atleast. Values below 3 are not permitted
743
+ nextend (int): Number of samples to extend at each end. Note that
744
+ in case of internal resetting of distance (due to 'atleast'), then
745
+ nextend internally will be modified in order to fulfill the
746
+ initial intention. Hence keep distance*nextend as target.
747
+ name (str): Name of polygon (if asnumpy=False)
748
+ asnumpy (bool): Return a [:, 5] numpy array with
749
+ columns X.., Y.., Z.., HLEN, dH
750
+ polyid (int): Which POLY_ID to use. Default (if None) is to use the
751
+ first found.
752
+
753
+ Returns:
754
+ A numpy array (if asnumpy=True) or a new Polygons() object
755
+
756
+ .. versionadded:: 2.1
757
+ """
758
+ logger.info("Getting fence within a Polygons instance...")
759
+ return _xyz_oper.get_fence(
760
+ self,
761
+ distance=distance,
762
+ atleast=atleast,
763
+ nextend=nextend,
764
+ name=name,
765
+ asnumpy=asnumpy,
766
+ polyid=polyid,
767
+ )
768
+
769
+ # ==================================================================================
770
+ # Plotting
771
+ # ==================================================================================
772
+
773
+ def quickplot(
774
+ self,
775
+ filename=None,
776
+ others=None,
777
+ title="QuickPlot for Polygons",
778
+ subtitle=None,
779
+ infotext=None,
780
+ linewidth=1.0,
781
+ color="r",
782
+ ):
783
+ """Simple plotting of polygons using matplotlib.
784
+
785
+ Args:
786
+ filename (str): Name of plot file; None will plot to screen.
787
+ others (list of Polygons): List of other polygon instances to plot
788
+ title (str): Title of plot
789
+ subtitle (str): Subtitle of plot
790
+ infotext (str): Additonal info on plot.
791
+ linewidth (float): Width of line.
792
+ color (str): Name of color (may use matplotib shortcuts, e.g. 'r' for 'red')
793
+ """
794
+ import xtgeoviz.plot
795
+
796
+ mymap = xtgeoviz.plot.Map()
797
+ mymap.canvas(title=title, subtitle=subtitle, infotext=infotext)
798
+
799
+ if others:
800
+ for other in others:
801
+ lwid = linewidth / 2.0
802
+ mymap.plot_polygons(
803
+ other, idname=other.pname, linewidth=lwid, color="black"
804
+ )
805
+
806
+ mymap.plot_polygons(self, idname=self.pname, linewidth=linewidth, color=color)
807
+
808
+ if filename is None:
809
+ mymap.show()
810
+ else:
811
+ mymap.savefig(filename)