xtgeo 4.8.0__cp313-cp313-win_amd64.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.cp313-win_amd64.pyd +0 -0
  5. xtgeo/_internal.cp313-win_amd64.pyd +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 +5 -0
  117. xtgeo-4.8.0.dist-info/licenses/LICENSE.md +165 -0
@@ -0,0 +1,1341 @@
1
+ from __future__ import annotations
2
+
3
+ import copy
4
+ import functools
5
+ import hashlib
6
+ from types import FunctionType
7
+ from typing import TYPE_CHECKING, Any, Literal
8
+
9
+ import numpy as np
10
+
11
+ import xtgeo
12
+ from xtgeo.common import XTGeoDialog, null_logger
13
+ from xtgeo.common.constants import UNDEF, UNDEF_INT, UNDEF_INT_LIMIT, UNDEF_LIMIT
14
+ from xtgeo.common.exceptions import InvalidFileFormatError
15
+ from xtgeo.common.types import Dimensions
16
+ from xtgeo.io._file import FileFormat, FileWrapper
17
+ from xtgeo.metadata.metadata import MetaDataCPProperty
18
+
19
+ from . import (
20
+ _gridprop_export,
21
+ _gridprop_lowlevel,
22
+ _gridprop_op1,
23
+ _gridprop_roxapi,
24
+ _gridprop_value_init,
25
+ )
26
+ from ._grid3d import _Grid3D
27
+ from ._gridprop_import_eclrun import (
28
+ import_gridprop_from_init,
29
+ import_gridprop_from_restart,
30
+ )
31
+ from ._gridprop_import_grdecl import import_bgrdecl_prop, import_grdecl_prop
32
+ from ._gridprop_import_roff import import_roff
33
+ from ._gridprop_import_xtgcpprop import import_xtgcpprop
34
+
35
+ xtg = XTGeoDialog()
36
+ logger = null_logger(__name__)
37
+
38
+ if TYPE_CHECKING:
39
+ from collections.abc import Callable
40
+ from typing import Union
41
+
42
+ import numpy.typing as npt
43
+
44
+ from xtgeo.common.types import FileLike
45
+ from xtgeo.xyz.polygons import Polygons
46
+
47
+ from ._gridprop_op1 import XYValueLists
48
+ from .grid import Grid
49
+
50
+ GridProperty_DType = Union[
51
+ type[np.uint8],
52
+ type[np.uint16],
53
+ type[np.int16],
54
+ type[np.int32],
55
+ type[np.int64],
56
+ type[np.float16],
57
+ type[np.float32],
58
+ type[np.float64],
59
+ ]
60
+ Roxar_DType = Union[type[np.uint8], type[np.uint16], type[np.float32]]
61
+
62
+ # --------------------------------------------------------------------------------------
63
+ # Comment on 'asmasked' vs 'activeonly:
64
+ #
65
+ # 'asmasked'=True will return a np.ma array, while 'asmasked' = False will
66
+ # return a np.ndarray
67
+ #
68
+ # The 'activeonly' will filter out masked entries, or use None or np.nan
69
+ # if 'activeonly' is False.
70
+ #
71
+ # Use word 'zerobased' for a bool regrading startcell basis is 1 or 0
72
+ #
73
+ # For functions with mask=... ,they should be replaced with asmasked=...
74
+ # --------------------------------------------------------------------------------------
75
+
76
+ # ======================================================================================
77
+ # Functions outside the class, for rapid access. Will be exposed as
78
+ # xxx = xtgeo.gridproperty_from_file.
79
+ # ======================================================================================
80
+
81
+
82
+ def _data_reader_factory(fformat: FileFormat) -> Callable:
83
+ if fformat in (FileFormat.ROFF_BINARY, FileFormat.ROFF_ASCII):
84
+ return import_roff
85
+ if fformat in (FileFormat.FINIT, FileFormat.INIT):
86
+ return import_gridprop_from_init
87
+ if fformat in (FileFormat.FUNRST, FileFormat.UNRST):
88
+ return functools.partial(import_gridprop_from_restart, fformat=fformat)
89
+ if fformat == FileFormat.GRDECL:
90
+ return import_grdecl_prop
91
+ if fformat == FileFormat.BGRDECL:
92
+ return import_bgrdecl_prop
93
+ if fformat == FileFormat.XTG:
94
+ return import_xtgcpprop
95
+
96
+ extensions = FileFormat.extensions_string(
97
+ [
98
+ FileFormat.ROFF_BINARY,
99
+ FileFormat.ROFF_ASCII,
100
+ FileFormat.INIT,
101
+ FileFormat.FINIT,
102
+ FileFormat.UNRST,
103
+ FileFormat.FUNRST,
104
+ FileFormat.GRDECL,
105
+ FileFormat.BGRDECL,
106
+ FileFormat.XTG,
107
+ ]
108
+ )
109
+ raise InvalidFileFormatError(
110
+ f"File format {fformat} is invalid for type GridProperty. "
111
+ f"Supported formats are {extensions}."
112
+ )
113
+
114
+
115
+ def gridproperty_from_file(
116
+ pfile: FileLike,
117
+ fformat: str | None = None,
118
+ **kwargs: dict[str, Any],
119
+ ) -> GridProperty:
120
+ """
121
+ Make a GridProperty instance directly from a file import.
122
+
123
+ Note that the the property may be linked to its geometrical grid
124
+ through the ``grid=`` option. Sometimes this is required, for instance
125
+ for most Eclipse input.
126
+
127
+ Args:
128
+ pfile: Name of file to be imported.
129
+ fformat: File format to be used (roff/init/unrst/grdecl).
130
+ Defaults to None and tries to infer from file extension.
131
+ name (str): Name of property to import
132
+ date (int or str): For restart files, date in YYYYMMDD format. Also
133
+ the YYYY-MM-DD form is allowed (string), and for Eclipse,
134
+ mnemonics like 'first', 'last' is also allowed.
135
+ grid (Grid, optional): Grid object for checks. Optional for
136
+ ROFF, required for Eclipse).
137
+ gridlink (bool): If True, and grid is not None, a link from the grid
138
+ instance to the property is made. If False, no such link is made.
139
+ Avoiding gridlink is recommended when running statistics of multiple
140
+ realisations of a property.
141
+ fracture (bool): Only applicable for DUAL POROSITY systems. If True
142
+ then the fracture property is read. If False then the matrix
143
+ property is read. Names will be appended with "M" or "F"
144
+ ijrange (list-like): A list of 4 numbers (i1, i2, j1, j2) for a subrange
145
+ of cells to read. Only applicable for xtgcpprop format.
146
+ zerobased (bool): Input if cells counts are zero- or one-based in
147
+ ijrange. Only applicable for xtgcpprop format.
148
+
149
+ Returns:
150
+ A GridProperty instance.
151
+
152
+ Examples::
153
+
154
+ import xtgeo
155
+ gprop = xtgeo.gridproperty_from_file("somefile.roff", fformat="roff")
156
+
157
+ # or
158
+
159
+ mygrid = xtgeo.grid_from_file("ECL.EGRID")
160
+ pressure_1 = xtgeo.gridproperty_from_file("ECL.UNRST", name="PRESSURE",
161
+ date="first", grid=mygrid)
162
+
163
+ """
164
+ return GridProperty._read_file(pfile, fformat, **kwargs)
165
+
166
+
167
+ def gridproperty_from_roxar(
168
+ project: Any, # project can be a path but also a magic variable in RMS
169
+ gname: str,
170
+ pname: str,
171
+ realisation: int = 0,
172
+ faciescodes: bool = False,
173
+ ) -> GridProperty:
174
+ """
175
+ Make a GridProperty instance directly inside RMS.
176
+
177
+ Args:
178
+ project: The Roxar project path or magical pre-defined variable in RMS
179
+ gname: Name of the grid model
180
+ pname: Name of the grid property
181
+ realisation: Realisation number (default 0; first)
182
+ faciescodes: If a Roxar property is of the special body_facies type
183
+ (e.g. result from a channel facies object modelling), the default
184
+ is to get the body code values. If faciescodes is True, the facies
185
+ code values will be read instead. For other roxar properties this
186
+ key is not relevant.
187
+
188
+ Returns:
189
+ A GridProperty instance.
190
+
191
+ Example::
192
+
193
+ import xtgeo
194
+ myporo = xtgeo.gridproperty_from_roxar(project, 'Geogrid', 'Poro')
195
+
196
+ """
197
+ return GridProperty._read_roxar(
198
+ project,
199
+ gname,
200
+ pname,
201
+ realisation=realisation,
202
+ faciescodes=faciescodes,
203
+ )
204
+
205
+
206
+ class GridProperty(_Grid3D):
207
+ """
208
+ Class for a single 3D grid property, e.g porosity or facies.
209
+
210
+ An GridProperty instance may or may not 'belong' to a grid (geometry) object.
211
+ E.g. for ROFF input, ncol, nrow, nlay are given in the import file and the grid
212
+ geometry file is not needed. For many Eclipse files, the grid geometry is needed
213
+ as this holds the active number indices (ACTNUM).
214
+
215
+ Normally the instance is created when importing a grid
216
+ property from file, but it can also be created directly, as e.g.::
217
+
218
+ poro = GridProperty(ncol=233, nrow=122, nlay=32)
219
+
220
+ The grid property values ``someinstance.values`` by themselves is a 3D masked
221
+ numpy usually as either float64 (double) or int32 (if discrete), and undefined
222
+ cells are displayed as masked. The internal array order is now C_CONTIGUOUS.
223
+ (i.e. not in Eclipse manner). A 1D view (C order) is achieved by the
224
+ values1d property, e.g.::
225
+
226
+ poronumpy = poro.values1d
227
+
228
+ .. versionchanged:: 2.6 Possible to make GridProperty instance directly from Grid
229
+ .. versionchanged:: 2.8 Possible to base it on existing GridProperty instance
230
+
231
+ """
232
+
233
+ def __init__(
234
+ self,
235
+ gridlike: Grid | GridProperty | None = None,
236
+ ncol: int | None = None,
237
+ nrow: int | None = None,
238
+ nlay: int | None = None,
239
+ name: str = "unknown",
240
+ discrete: bool = False,
241
+ date: str | None = None,
242
+ grid: Grid | None = None,
243
+ linkgeometry: bool = True,
244
+ fracture: bool = False,
245
+ codes: dict[int, str] | None = None,
246
+ dualporo: bool = False,
247
+ dualperm: bool = False,
248
+ roxar_dtype: Roxar_DType | None = None,
249
+ values: np.ndarray | float | int | None = None,
250
+ roxorigin: bool = False,
251
+ filesrc: str | None = None,
252
+ ) -> None:
253
+ """
254
+ Instantiating.
255
+
256
+ Args:
257
+ gridlike: Grid or GridProperty instance, or leave blank.
258
+ ncol: Number of columns (nx). Defaults to 4.
259
+ nrow: Number of rows (ny). Defaults to 3.
260
+ nlay: Number of layers (nz). Defaults to 5.
261
+ name: Name of property. Defaults to "unknown".
262
+ discrete: True or False. Defaults to False.
263
+ date: Date on YYYYMMDD form.
264
+ grid: Attached Grid object.
265
+ linkgeometry: If True, establish a link between GridProperty
266
+ and Grid. Defaults to True.
267
+ fracture: True if fracture option (relevant for flow simulator data).
268
+ Defaults to False.
269
+ codes: Codes in case a discrete property e.g. {1: "Sand", 4: "Shale"}.
270
+ dualporo: True if dual porosity system. Defaults to False.
271
+ dualperm: True if dual porosity and dual permeability system.
272
+ Defaults to False.
273
+ roxar_dtype: Specify Roxar datatype e.g. np.uint8.
274
+ values: Values to apply.
275
+ roxorigin: True if the object comes from Roxar API. Defaults to False.
276
+ filesrc: Where the file came from.
277
+
278
+ Raises:
279
+ RuntimeError: If something goes wrong (e.g. file not found).
280
+
281
+ Examples::
282
+
283
+ import xtgeo
284
+ myprop = xtgeo.gridproperty_from_file("emerald.roff", name="PORO")
285
+
286
+ # or
287
+
288
+ values = np.ma.ones((12, 17, 10), dtype=np.float64),
289
+ myprop = GridProperty(ncol=12, nrow=17, nlay=10,
290
+ values=values, discrete=False,
291
+ name="MyValue")
292
+
293
+ # or create properties from a Grid() instance
294
+
295
+ mygrid = xtgeo.grid_from_file("grid.roff")
296
+ myprop1 = xtgeo.GridProperty(mygrid, name="PORO")
297
+ myprop2 = xtgeo.GridProperty(mygrid, name="FACIES", discrete=True, values=1,
298
+ linkgeometry=True) # alternative 1
299
+ myprop2.geometry = mygrid # alternative 2 to link grid geometry to property
300
+
301
+ # from Grid instance:
302
+ grd = xtgeo.grid_from_file("somefile_grid_file")
303
+ myprop = GridProperty(grd, values=99, discrete=True) # based on grd
304
+
305
+ # or from existing GridProperty instance:
306
+ myprop2 = GridProperty(myprop, values=99, discrete=False) # based on myprop
307
+
308
+ """
309
+ super().__init__(ncol or 4, nrow or 3, nlay or 5)
310
+
311
+ # Instance attributes defaults:
312
+ self._name = name
313
+ self._date = date
314
+ self._isdiscrete = discrete
315
+ self._geometry = grid
316
+ self._fracture = fracture
317
+ self._codes = {} if codes is None else codes
318
+
319
+ # Not primary input:
320
+ self._dualporo = dualporo
321
+ self._dualperm = dualperm
322
+
323
+ self._filesrc = filesrc
324
+ self._roxorigin = roxorigin
325
+
326
+ if roxar_dtype is None:
327
+ self._roxar_dtype: Roxar_DType = np.uint8 if discrete else np.float32
328
+ else:
329
+ self.roxar_dtype = roxar_dtype
330
+
331
+ self._undef = UNDEF_INT if discrete else UNDEF
332
+
333
+ self._set_initial_dimensions(gridlike, (ncol, nrow, nlay))
334
+
335
+ self._values = _gridprop_value_init.gridproperty_non_dummy_values(
336
+ gridlike, self.dimensions, values, discrete
337
+ )
338
+
339
+ if isinstance(gridlike, xtgeo.grid3d.Grid):
340
+ if linkgeometry:
341
+ # Associate this grid property with a Grid instance. This is not default
342
+ # since sunch links may affect garbage collection
343
+ self.geometry = gridlike
344
+ gridlike.append_prop(self)
345
+
346
+ self._metadata: MetaDataCPProperty = MetaDataCPProperty()
347
+
348
+ def _set_initial_dimensions(
349
+ self,
350
+ gridlike: Grid | GridProperty | None,
351
+ input_dimensions: tuple[int | None, int | None, int | None],
352
+ ) -> None:
353
+ """
354
+ Sets the initial dimensions either from input, grid or default.
355
+
356
+ Args:
357
+ gridlike: Grid/GridProperty instance or leave blank.
358
+ input_dimensions: The (ncol, nrow, nlay) tuple describing the
359
+ dimensions.
360
+
361
+ If a gridlike is given, we use its dimensions, but make sure it matches
362
+ the input dimensions if given (not None). Otherwise, dimensions are either
363
+ set to the input dimensions or defaulted.
364
+
365
+ """
366
+ if gridlike is not None:
367
+ self._ncol = gridlike.ncol
368
+ self._nrow = gridlike.nrow
369
+ self._nlay = gridlike.nlay
370
+ self._check_dimensions_match(*input_dimensions)
371
+ else:
372
+ ncol, nrow, nlay = input_dimensions
373
+ if ncol is None:
374
+ self._ncol = 4
375
+ else:
376
+ self._ncol = ncol
377
+ if nrow is None:
378
+ self._nrow = 3
379
+ else:
380
+ self._nrow = nrow
381
+ if nlay is None:
382
+ self._nlay = 5
383
+ else:
384
+ self._nlay = nlay
385
+
386
+ def _check_dimensions_match(
387
+ self, ncol: int | None, nrow: int | None, nlay: int | None
388
+ ) -> None:
389
+ """
390
+ Checks that Grid/GridProperty dimensions match provided input dimensions.
391
+
392
+ Args:
393
+ input_dimensions: The (ncol, nrow, nlay) tuple describing the
394
+ dimensions.
395
+
396
+ Raises:
397
+ ValueError: If given dimensions are not None and do not
398
+ match dimensions of the GridProperty
399
+
400
+ """
401
+ if ncol is not None and self._ncol != ncol:
402
+ raise ValueError(
403
+ f"Mismatching column dimension given: {ncol} vs {self._ncol}"
404
+ )
405
+ if nrow is not None and self._nrow != nrow:
406
+ raise ValueError(f"Mismatching row dimension given: {nrow} vs {self._nrow}")
407
+ if nlay is not None and self._nlay != nlay:
408
+ raise ValueError(
409
+ f"Mismatching layer dimension given: {nlay} vs {self._nlay}"
410
+ )
411
+
412
+ def __del__(self) -> None:
413
+ logger.debug("DELETING property instance %s", self.name)
414
+
415
+ def __repr__(self) -> str:
416
+ return (
417
+ f"{self.__class__.__name__} (id={id(self)}) ncol={self._ncol!r}, "
418
+ f"nrow={self._nrow!r}, nlay={self._nlay!r}, filesrc={self._filesrc!r}"
419
+ )
420
+
421
+ def __str__(self) -> str:
422
+ return self.describe(flush=False)
423
+
424
+ # ==================================================================================
425
+ # Properties
426
+ # Some properties such as ncol, nrow, nlay are from _Grid3d
427
+ # ==================================================================================
428
+
429
+ @property
430
+ def metadata(self) -> MetaDataCPProperty:
431
+ """Get or set metadata object instance of type MetaDataCPProperty."""
432
+ return self._metadata
433
+
434
+ @metadata.setter
435
+ def metadata(self, metadata: MetaDataCPProperty) -> None:
436
+ if not isinstance(metadata, MetaDataCPProperty):
437
+ raise ValueError("Input metadata not an instance of MetaDataCPProperty")
438
+ # TODO: validate this?
439
+ self._metadata = metadata
440
+
441
+ @property
442
+ def name(self) -> str | None:
443
+ """Get or set the property name."""
444
+ return self._name
445
+
446
+ @name.setter
447
+ def name(self, name: str) -> None:
448
+ self._name = name
449
+
450
+ @property
451
+ def dimensions(self) -> Dimensions:
452
+ """Get the grid dimensions as a NamedTuple of 3 integers."""
453
+ return Dimensions(self.ncol, self.nrow, self.nlay)
454
+
455
+ @property
456
+ def nactive(self) -> int:
457
+ """Get the number of active cells."""
458
+ return len(self.actnum_indices)
459
+
460
+ @property
461
+ def geometry(self) -> Grid | None:
462
+ """Get or set the linked geometry, i.e. the Grid instance."""
463
+ return self._geometry
464
+
465
+ @geometry.setter
466
+ def geometry(self, grid: Grid | None) -> None:
467
+ if grid is None:
468
+ self._geometry = None
469
+ elif isinstance(grid, xtgeo.grid3d.Grid) and grid.dimensions == self.dimensions:
470
+ self._geometry = grid
471
+ else:
472
+ raise ValueError("Could not set geometry; wrong type or size")
473
+
474
+ @property
475
+ def actnum_indices(self) -> np.ndarray:
476
+ """
477
+ Get the 1D ndarray which holds the indices for active cells
478
+ given in 1D, C order.
479
+
480
+ """
481
+ gridprop = self.get_actnum()
482
+ actnumv = np.ravel(gridprop.values)
483
+ return np.flatnonzero(actnumv)
484
+
485
+ @property
486
+ def isdiscrete(self) -> bool:
487
+ """
488
+ Get or set whether this property is discrete.
489
+
490
+ This can also be used to convert from continuous to discrete
491
+ or from discrete to continuous::
492
+
493
+ myprop.isdiscrete = False
494
+
495
+ """
496
+ return self._isdiscrete
497
+
498
+ @isdiscrete.setter
499
+ def isdiscrete(self, flag: bool) -> None:
500
+ if not isinstance(flag, bool):
501
+ raise ValueError("Input to {__name__} must be a bool")
502
+
503
+ if flag is self._isdiscrete:
504
+ return
505
+
506
+ if flag is True and self._isdiscrete is False:
507
+ self.continuous_to_discrete()
508
+ else:
509
+ self.discrete_to_continuous()
510
+
511
+ @property
512
+ def dtype(self) -> GridProperty_DType:
513
+ """
514
+ Get or set the ``values`` numpy dtype.
515
+
516
+ When setting, note that the the dtype must correspond to the
517
+ `isdiscrete` property. Hence dtype cannot alter isdiscrete status
518
+
519
+ Example::
520
+
521
+ if myprop.isdiscrete:
522
+ myprop.dtype = np.uint16
523
+
524
+ """
525
+ return self._values.dtype
526
+
527
+ @dtype.setter
528
+ def dtype(self, dtype: GridProperty_DType) -> None:
529
+ allowed: list[GridProperty_DType] = (
530
+ [np.uint8, np.uint16, np.int16, np.int32, np.int64]
531
+ if self.isdiscrete
532
+ else [np.float16, np.float32, np.float64]
533
+ )
534
+ if dtype not in allowed:
535
+ raise ValueError(
536
+ f"{__name__}: Wrong input for dtype. Use one of {allowed}!"
537
+ )
538
+ # https://github.com/numpy/numpy/issues/24392
539
+ self.values = self.values.astype(dtype) # type: ignore
540
+
541
+ @property
542
+ def filesrc(self) -> str | None:
543
+ """Get or set the GridProperty file src (if any)."""
544
+ return self._filesrc
545
+
546
+ @filesrc.setter
547
+ def filesrc(self, src: str) -> None:
548
+ self._filesrc = src
549
+
550
+ @property
551
+ def roxar_dtype(self) -> Roxar_DType | None:
552
+ """Get or set the roxar dtype (if any)."""
553
+ return self._roxar_dtype
554
+
555
+ @roxar_dtype.setter
556
+ def roxar_dtype(self, dtype: Roxar_DType) -> None:
557
+ allowed = [np.uint8, np.uint16, np.float32]
558
+ if dtype not in allowed:
559
+ raise ValueError(
560
+ f"{__name__}: Wrong input for roxar_dtype. Use one of {allowed}!"
561
+ )
562
+ self._roxar_dtype = dtype
563
+
564
+ @property
565
+ def date(self) -> str | None:
566
+ """Get or set the property date as string in YYYYMMDD format."""
567
+ return self._date
568
+
569
+ @date.setter
570
+ def date(self, date: str | None) -> None:
571
+ self._date = date
572
+
573
+ @property
574
+ def codes(self) -> dict[int, str]:
575
+ """Get or set the property codes as a dictionary."""
576
+ return self._codes
577
+
578
+ @codes.setter
579
+ def codes(self, codes: dict[int, str]) -> None:
580
+ if not isinstance(codes, dict):
581
+ raise ValueError(
582
+ "The codes must be a python dictionary, current input "
583
+ f"is type: {type(codes)}"
584
+ )
585
+ self._codes = copy.deepcopy(codes)
586
+
587
+ @property
588
+ def ncodes(self) -> int:
589
+ """Get number of codes if discrete grid property."""
590
+ return len(self._codes)
591
+
592
+ @property
593
+ def values(self) -> np.ma.MaskedArray:
594
+ """Get or set the grid property as a masked 3D numpy array."""
595
+ return self._values
596
+
597
+ @values.setter
598
+ def values(self, values: np.ndarray) -> None:
599
+ values = self.ensure_correct_values(self.ncol, self.nrow, self.nlay, values)
600
+ self._values = values
601
+
602
+ @property
603
+ def ntotal(self) -> int:
604
+ """Get total number of cells (ncol * nrow * nlay)."""
605
+ return self.ncol * self.nrow * self.nlay
606
+
607
+ @property
608
+ def roxorigin(self) -> bool:
609
+ """Get boolean value of True if the property comes from ROXAPI."""
610
+ return self._roxorigin
611
+
612
+ @roxorigin.setter
613
+ def roxorigin(self, val: bool) -> None:
614
+ if not isinstance(val, bool):
615
+ raise ValueError("Input to roxorigin must be True or False")
616
+ self._roxorigin = val
617
+
618
+ @property
619
+ def values1d(self) -> np.ma.MaskedArray:
620
+ """Get a masked 1D array view of values."""
621
+ return self._values.reshape(-1)
622
+
623
+ @property
624
+ def undef(self) -> float | int:
625
+ """Get the actual undef value for floats or ints in numpy arrays."""
626
+ if self._isdiscrete:
627
+ return UNDEF_INT
628
+ return UNDEF
629
+
630
+ @property
631
+ def undef_limit(self) -> float | int:
632
+ """
633
+ Get the undef limit number, which is slightly less than the
634
+ undef value.
635
+
636
+ Hence for numerical precision, one can force undef values
637
+ to a given number, e.g.::
638
+
639
+ x[x<x.undef_limit] = 999
640
+
641
+ Undef limit values cannot be changed (read only).
642
+
643
+ """
644
+ if self._isdiscrete:
645
+ return UNDEF_INT_LIMIT
646
+ return UNDEF_LIMIT
647
+
648
+ # ==================================================================================
649
+ # Class and special methods
650
+ # ==================================================================================
651
+
652
+ def generate_hash(self) -> str:
653
+ """
654
+ Generates a sha256 hash id representing a GridProperty.
655
+
656
+ Returns:
657
+ A unique hash id string.
658
+
659
+ .. versionadded:: 2.10
660
+
661
+ """
662
+ mhash = hashlib.sha256()
663
+ gid = (
664
+ f"{self._filesrc}{self._ncol}{self._nrow}{self._nlay}"
665
+ f"{self._values.mean()}{self._values.min()}{self._values.max()}"
666
+ )
667
+ mhash.update(gid.encode())
668
+ return mhash.hexdigest()
669
+
670
+ @classmethod
671
+ def methods(cls) -> str:
672
+ """
673
+ A list of methods in the class as a string.
674
+
675
+ Returns:
676
+ The names of the methods in the class.
677
+
678
+ Example::
679
+ >>> print(GridProperty.methods())
680
+ METHODS for GridProperty():
681
+ ======================
682
+ __init__
683
+ _reset
684
+ _set_initial_dimensions
685
+ _check_dimensions_match
686
+ ...
687
+
688
+ """
689
+ mets = [x for x, y in cls.__dict__.items() if isinstance(y, FunctionType)]
690
+
691
+ txt = "METHODS for GridProperty():\n======================\n"
692
+ for met in mets:
693
+ txt += str(met) + "\n"
694
+
695
+ return txt
696
+
697
+ def ensure_correct_values(
698
+ self,
699
+ ncol: int,
700
+ nrow: int,
701
+ nlay: int,
702
+ invalues: npt.ArrayLike,
703
+ ) -> np.ma.MaskedArray:
704
+ """
705
+ Ensures that values is a 3D masked numpy (ncol, nrol, nlay).
706
+
707
+ Args:
708
+ ncol: Number of columns.
709
+ nrow: Number of rows.
710
+ nlay: Number of layers.
711
+ invalues: Values to process.
712
+
713
+ Returns:
714
+ The values as a masked numpy array.
715
+
716
+ """
717
+ currentmask = (
718
+ np.ma.getmaskarray(self._values)
719
+ if self._values is not None and isinstance(self._values, np.ma.MaskedArray)
720
+ else None
721
+ )
722
+
723
+ if isinstance(invalues, (int, float)):
724
+ vals = np.ma.zeros((ncol, nrow, nlay), order="C", dtype=self.dtype)
725
+ vals = np.ma.array(vals, mask=currentmask)
726
+ values = vals + invalues
727
+ invalues = values
728
+
729
+ if not isinstance(invalues, np.ma.MaskedArray):
730
+ values = np.ma.array(invalues, mask=currentmask, order="C")
731
+ else:
732
+ values = invalues # new mask is possible
733
+
734
+ if values.shape != (ncol, nrow, nlay):
735
+ try:
736
+ values = np.ma.reshape(values, (ncol, nrow, nlay), order="C")
737
+ except ValueError as emsg:
738
+ xtg.error(f"Cannot reshape array: {emsg}")
739
+ raise
740
+
741
+ # replace any undef or nan with mask
742
+ values = np.ma.masked_greater(values, self.undef_limit)
743
+ values = np.ma.masked_invalid(values)
744
+
745
+ if not values.flags.c_contiguous:
746
+ mask = np.ma.getmaskarray(values)
747
+ mask = np.asanyarray(mask, order="C")
748
+ values = np.asanyarray(values, order="C")
749
+ values = np.ma.array(values, mask=mask, order="C")
750
+
751
+ # the self._isdiscrete property shall win over numpy dtype
752
+ if "int" in str(values.dtype) and not self._isdiscrete:
753
+ values = values.astype(np.float64)
754
+
755
+ if "float" in str(values.dtype) and self._isdiscrete:
756
+ values = values.astype(np.int32)
757
+
758
+ return values
759
+
760
+ # ==================================================================================
761
+ # Import and export
762
+ # ==================================================================================
763
+
764
+ @classmethod
765
+ def _read_file(
766
+ cls,
767
+ filelike: FileLike,
768
+ fformat: str | None = None,
769
+ **kwargs: Any,
770
+ ) -> GridProperty:
771
+ pfile = FileWrapper(filelike)
772
+ fmt = pfile.fileformat(fformat)
773
+ kwargs = _data_reader_factory(fmt)(pfile, **kwargs)
774
+ kwargs["filesrc"] = pfile.file
775
+ return cls(**kwargs)
776
+
777
+ def to_file(
778
+ self,
779
+ pfile: FileLike,
780
+ fformat: Literal["roff", "roffasc", "grdecl", "bgrdecl", "xtgcpprop"] = "roff",
781
+ name: str | None = None,
782
+ append: bool = False,
783
+ dtype: type[np.float32] | type[np.float64] | type[np.int32] | None = None,
784
+ fmt: str | None = None,
785
+ ) -> None:
786
+ """
787
+ Export the grid property to file.
788
+
789
+ Args:
790
+ pfile: File name or pathlib.Path to export to.
791
+ fformat: The file format to be used. Default is
792
+ roff binary, else roff_ascii/grdecl/bgrdecl.
793
+ name: If provided, will explicitly give property name;
794
+ else the existing name of the instance will used.
795
+ append: Append to existing file, only for (b)grdecl formats.
796
+ dtype: The values data type. This is valid only for grdecl or bgrdecl
797
+ formats, where the default is None which means 'float32' for
798
+ floating point numbers and 'int32' for discrete properties.
799
+ Other choices are 'float64' which are 'DOUB' entries in
800
+ Eclipse formats.
801
+ fmt: Format for ascii grdecl format. Default is None. If specified,
802
+ the user is responsible for a valid format specifier, e.g. "%8.4f".
803
+
804
+ Example::
805
+
806
+ # This example demonstrates that file formats can be mixed
807
+ import xtgeo
808
+ rgrid = xtgeo.grid_from_file("reek.roff")
809
+ poro = GridProperty("reek_poro.grdecl", grid=rgrid, name='PORO')
810
+
811
+ poro.values += 0.05
812
+
813
+ poro.to_file("reek_export_poro.bgrdecl", format="bgrdecl")
814
+
815
+ .. versionadded:: 2.13 Key `fmt` was added and default format for float output
816
+ to grdecl is now "%e" if `fmt=None`
817
+
818
+ """
819
+ _gridprop_export.to_file(
820
+ self,
821
+ pfile,
822
+ fformat=fformat,
823
+ name=name,
824
+ append=append,
825
+ dtype=dtype,
826
+ fmt=fmt,
827
+ )
828
+
829
+ @classmethod
830
+ def _read_roxar(
831
+ cls,
832
+ projectname: str,
833
+ gridname: str,
834
+ propertyname: str,
835
+ realisation: int = 0,
836
+ faciescodes: bool = False,
837
+ ) -> GridProperty:
838
+ return cls(
839
+ **_gridprop_roxapi.import_prop_roxapi(
840
+ projectname, gridname, propertyname, realisation, faciescodes
841
+ )
842
+ )
843
+
844
+ def to_roxar(
845
+ self,
846
+ projectname: str,
847
+ gridname: str,
848
+ propertyname: str,
849
+ realisation: int = 0,
850
+ casting: (
851
+ Literal["no", "equiv", "safe", "same_kind", "unsafe"] | None
852
+ ) = "unsafe",
853
+ ) -> None:
854
+ """
855
+ Store a grid model property into a RMS project.
856
+
857
+ Note:
858
+ When project is file path (direct access, outside RMS) then
859
+ ``to_roxar()`` will implicitly do a project save. Otherwise, the project
860
+ will not be saved until the user do an explicit project save action.
861
+
862
+ Note:
863
+ Beware values casting, see ``casting`` key.
864
+ Default is "unsafe" which may create issues if your property has
865
+ values that is outside the valid range. I.e. for float values XTGeo
866
+ normally use `float64` (8 byte) while roxar use `float32` (4 byte).
867
+ With extreme values, e.g. 10e40, such values will be truncated if
868
+ "unsafe" casting. More common is casting issues with discrete as
869
+ Roxar (RMS) often use `uint8` which only allow values in range 1..256.
870
+
871
+ Args:
872
+ projectname: Inside RMS use the magic 'project' string. Otherwise
873
+ use a path to an RMS project, or a project reference.
874
+ gridname: Name of grid model.
875
+ propertyname: Name of grid property.
876
+ realisation: Realisation number. Default is 0 (the first).
877
+ casting: This refers to numpy `astype(... casting=...)` settings.
878
+
879
+ .. versionchanged:: 2.10 Key `saveproject` has been removed and will
880
+ have no effect
881
+ .. versionadded:: 2.12 Key `casting` was added
882
+
883
+ """
884
+ _gridprop_roxapi.export_prop_roxapi(
885
+ self,
886
+ projectname,
887
+ gridname,
888
+ propertyname,
889
+ realisation=realisation,
890
+ casting=casting,
891
+ )
892
+
893
+ # ==================================================================================
894
+ # Various public methods
895
+ # ==================================================================================
896
+
897
+ def describe(self, flush: bool = True) -> str:
898
+ """
899
+ Describe a GridProperty instance by printing its properties
900
+ to stdout
901
+
902
+ Args:
903
+ flush: Print to stdout. True by default.
904
+
905
+ Returns:
906
+ A string description of the grid property instance.
907
+
908
+ """
909
+ from xtgeo.common import XTGDescription
910
+
911
+ dsc = XTGDescription()
912
+ dsc.title("Description of GridProperty instance")
913
+ dsc.txt("Object ID", id(self))
914
+ dsc.txt("Name", self.name)
915
+ dsc.txt("Date", self.date)
916
+ dsc.txt("File source", self._filesrc)
917
+ dsc.txt("Discrete status", self._isdiscrete)
918
+ dsc.txt("Codes", self._codes)
919
+ dsc.txt("Shape: NCOL, NROW, NLAY", self.ncol, self.nrow, self.nlay)
920
+ np.set_printoptions(threshold=16)
921
+ dsc.txt("Values", self._values.reshape(-1), self._values.dtype)
922
+ np.set_printoptions(threshold=1000)
923
+ dsc.txt(
924
+ "Values, mean, stdev, minimum, maximum",
925
+ self.values.mean(),
926
+ self.values.std(),
927
+ self.values.min(),
928
+ self.values.max(),
929
+ )
930
+ itemsize = self.values.itemsize
931
+ msize = float(self.values.size * itemsize) / (1024 * 1024 * 1024)
932
+ dsc.txt("Roxar datatype", self.roxar_dtype)
933
+ dsc.txt("Minimum memory usage of array (GB)", msize)
934
+
935
+ if flush:
936
+ dsc.flush()
937
+ return ""
938
+
939
+ return dsc.astext()
940
+
941
+ def get_npvalues3d(self, fill_value: npt.ArrayLike | None = None) -> np.ndarray:
942
+ """
943
+ Get a pure numpy copy (not masked) of the values in 3D shape.
944
+
945
+ Note that Numpy dtype will be reset; int32 if discrete or float64 if
946
+ continuous. The reason for this is to avoid inconsistensies regarding
947
+ UNDEF values.
948
+
949
+ If fill_value is not None, than the returning dtype is always `np.float64`.
950
+
951
+ Args:
952
+ fill_value: Value of masked entries. Default is None which
953
+ means the XTGeo UNDEF value (a high number). This UNDEF
954
+ value is different for a continuous or discrete property.
955
+
956
+ Returns:
957
+ Non-masked array copy of 3D-shaped values
958
+
959
+ """
960
+ if fill_value is None:
961
+ if self._isdiscrete:
962
+ fvalue: npt.ArrayLike = UNDEF_INT
963
+ dtype: type[np.int32] | type[np.float64] = np.int32
964
+ else:
965
+ fvalue = UNDEF
966
+ dtype = np.float64
967
+ else:
968
+ fvalue = fill_value
969
+ dtype = np.float64
970
+
971
+ val = self.values.copy().astype(dtype)
972
+ npv3d = np.ma.filled(val, fill_value=fvalue)
973
+ del val
974
+
975
+ return npv3d
976
+
977
+ def get_actnum(
978
+ self,
979
+ name: str = "ACTNUM",
980
+ asmasked: bool = False,
981
+ ) -> GridProperty:
982
+ """
983
+ Return an ACTNUM GridProperty object.
984
+
985
+ Note that this method is similar to, but not identical to,
986
+ the job with same name in Grid(). Here, the maskedarray of the values
987
+ is applied to deduce the ACTNUM array.
988
+
989
+ Args:
990
+ name: Name of property in the XTGeo GridProperty object.
991
+ Default is "ACTNUM".
992
+ asmasked: Default is False, so that actnum is returned with all cells
993
+ shown. Use asmasked=True to make 0 entries masked.
994
+
995
+ Returns:
996
+ The ACTNUM GridProperty object.
997
+
998
+ Example::
999
+
1000
+ act = mygrid.get_actnum()
1001
+ print('{}% cells are active'.format(act.values.mean() * 100))
1002
+
1003
+ """
1004
+ act = GridProperty(
1005
+ ncol=self._ncol, nrow=self._nrow, nlay=self._nlay, name=name, discrete=True
1006
+ )
1007
+
1008
+ orig = self.values
1009
+ vact = np.ma.ones(self.values.shape)
1010
+ vact[orig.mask] = 0
1011
+
1012
+ if asmasked:
1013
+ vact = np.ma.masked_equal(vact, 0)
1014
+
1015
+ act.values = vact.astype(np.int32)
1016
+ act.isdiscrete = True
1017
+ act.codes = {0: "0", 1: "1"}
1018
+
1019
+ return act
1020
+
1021
+ def get_active_npvalues1d(self) -> np.ma.MaskedArray:
1022
+ """
1023
+ Get the active cells as a 1D numpy masked array.
1024
+
1025
+ Returns:
1026
+ The grid property as a 1D numpy masked array, active cells only.
1027
+
1028
+ """
1029
+ return self.get_npvalues1d(activeonly=True)
1030
+
1031
+ def get_npvalues1d(
1032
+ self,
1033
+ activeonly: bool = False,
1034
+ fill_value: npt.ArrayLike = np.nan,
1035
+ order: Literal["C", "F"] = "C",
1036
+ ) -> np.ma.MaskedArray:
1037
+ """
1038
+ Return the grid property as a 1D numpy array (copy) for active or all
1039
+ cells, but inactive have a fill value.
1040
+
1041
+ Args:
1042
+ activeonly: If True, then only return active cells.
1043
+ Default is False.
1044
+ fill_value: Fill value for inactive cells. Default is `np.nan`.
1045
+ order: Array internal order. Default is "C", alternative is "F".
1046
+
1047
+ Returns:
1048
+ The grid property as a 1D numpy masked array.
1049
+
1050
+ .. versionadded:: 2.3
1051
+ .. versionchanged:: 2.8 Added `fill_value` and `order`
1052
+
1053
+ """
1054
+ vact = self.values1d.copy()
1055
+
1056
+ if order == "F":
1057
+ vact = _gridprop_lowlevel.c2f_order(self, vact)
1058
+
1059
+ if activeonly:
1060
+ return vact.compressed() # safer than vact[~vact.mask] if no masked
1061
+
1062
+ return vact.filled(fill_value)
1063
+
1064
+ def copy(self, newname: str | None = None) -> GridProperty:
1065
+ """
1066
+ Copy a GridProperty object to another instance.
1067
+
1068
+ Args:
1069
+ newname: Give the copied instance a new name.
1070
+
1071
+ Returns:
1072
+ A copy of the GridProperty instance.
1073
+
1074
+ ::
1075
+
1076
+ >>> import xtgeo
1077
+ >>> myporo = xtgeo.gridproperty_from_file(
1078
+ ... reek_dir + '/reek_sim_poro.roff',
1079
+ ... name="PORO"
1080
+ ... )
1081
+ >>> mycopy = myporo.copy(newname='XPROP')
1082
+ >>> print(mycopy.name)
1083
+ XPROP
1084
+
1085
+ """
1086
+ if newname is None:
1087
+ newname = self.name
1088
+ assert newname is not None
1089
+
1090
+ xprop = GridProperty(
1091
+ ncol=self._ncol,
1092
+ nrow=self._nrow,
1093
+ nlay=self._nlay,
1094
+ values=self._values.copy(),
1095
+ name=newname,
1096
+ )
1097
+
1098
+ xprop.geometry = self._geometry
1099
+ xprop.isdiscrete = self._isdiscrete
1100
+ xprop.codes = self._codes
1101
+ xprop.date = self._date
1102
+ xprop.roxorigin = self._roxorigin
1103
+ xprop.roxar_dtype = self.roxar_dtype
1104
+
1105
+ xprop.filesrc = self._filesrc
1106
+
1107
+ return xprop
1108
+
1109
+ def mask_undef(self) -> None:
1110
+ """Make UNDEF values masked."""
1111
+ if self._isdiscrete:
1112
+ self._values = np.ma.masked_greater(self._values, UNDEF_INT_LIMIT)
1113
+ else:
1114
+ self._values = np.ma.masked_greater(self._values, UNDEF_LIMIT)
1115
+
1116
+ def crop(
1117
+ self, spec: tuple[tuple[int, int], tuple[int, int], tuple[int, int]]
1118
+ ) -> None:
1119
+ """
1120
+ Crop a property between grid coordinates.
1121
+
1122
+ Args:
1123
+ spec: Provide a tuple of i, j, k lower and upper bounds
1124
+ to crop between, e.g. ((1, 3), (2, 4), (1, 5)) would
1125
+ crop a grid property such that only values from 1:3 in
1126
+ the i plane, 2:4 in the j plane, and 1:5 in the k plane
1127
+ would be present.
1128
+
1129
+ """
1130
+ (ic1, ic2), (jc1, jc2), (kc1, kc2) = spec
1131
+
1132
+ # Compute size of new cropped grid
1133
+ self._ncol = ic2 - ic1 + 1
1134
+ self._nrow = jc2 - jc1 + 1
1135
+ self._nlay = kc2 - kc1 + 1
1136
+
1137
+ newvalues = self.values.copy()
1138
+
1139
+ self.values = newvalues[ic1 - 1 : ic2, jc1 - 1 : jc2, kc1 - 1 : kc2]
1140
+
1141
+ def get_xy_value_lists(
1142
+ self, grid: Grid | None = None, activeonly: bool = True
1143
+ ) -> XYValueLists:
1144
+ """
1145
+ Get lists of xy coords and values for Webportal format.
1146
+
1147
+ The coordinates are on the form (two cells)::
1148
+
1149
+ [[[(x1,y1), (x2,y2), (x3,y3), (x4,y4)],
1150
+ [(x5,y5), (x6,y6), (x7,y7), (x8,y8)]]]
1151
+
1152
+ Args:
1153
+ grid: The XTGeo Grid object for the property. Defaults to None.
1154
+ activeonly: If True (default), active cells only,
1155
+ otherwise cell geometries will be listed and property will
1156
+ have value -999 in undefined cells.
1157
+
1158
+ Returns:
1159
+ A tuple of two lists, one being the xr coords, the other
1160
+ the values at those coords.
1161
+
1162
+
1163
+ Example::
1164
+
1165
+ import xtgeo
1166
+ grid = xtgeo.grid_from_file("../xtgeo-testdata/3dgrids/bri/b_grid.roff")
1167
+ prop = xtgeogridproperty_from_file(
1168
+ "../xtgeo-testdata/3dgrids/bri/b_poro.roff", grid=grid, name="PORO"
1169
+ )
1170
+
1171
+ clist, valuelist = prop.get_xy_value_lists(
1172
+ grid=grid, activeonly=False
1173
+ )
1174
+
1175
+ """
1176
+ clist, vlist = _gridprop_op1.get_xy_value_lists(
1177
+ self, grid=grid, mask=activeonly
1178
+ )
1179
+ return clist, vlist
1180
+
1181
+ def get_values_by_ijk(
1182
+ self, iarr: np.ndarray, jarr: np.ndarray, karr: np.ndarray, base: int = 1
1183
+ ) -> np.ma.MaskedArray | None:
1184
+ """
1185
+ Get a 1D ndarray of values by I J K arrays.
1186
+
1187
+ This could for instance be a well path where I J K
1188
+ exists as well logs.
1189
+
1190
+ Note that the input arrays have 1 as base as default
1191
+
1192
+ Args:
1193
+ iarr: Numpy array of I
1194
+ jarr: Numpy array of J
1195
+ karr: Numpy array of K
1196
+ base: Should be 1 or 0, dependent on what
1197
+ number base the input arrays has.
1198
+
1199
+ Returns:
1200
+ A 1D numpy array of property values,
1201
+ with NaN if undefined. Returns None
1202
+ on IndexErrors.
1203
+
1204
+ """
1205
+ res = np.zeros(iarr.shape, dtype="float64")
1206
+ res = np.ma.masked_equal(res, 0) # mask all
1207
+
1208
+ # get indices where defined (note the , after valids)
1209
+ (valids,) = np.where(~np.isnan(iarr))
1210
+
1211
+ iarr = iarr[~np.isnan(iarr)]
1212
+ jarr = jarr[~np.isnan(jarr)]
1213
+ karr = karr[~np.isnan(karr)]
1214
+
1215
+ try:
1216
+ res[valids] = self.values[
1217
+ iarr.astype("int") - base,
1218
+ jarr.astype("int") - base,
1219
+ karr.astype("int") - base,
1220
+ ]
1221
+ return np.ma.filled(res, fill_value=np.nan)
1222
+ except IndexError as ier:
1223
+ xtg.warn(f"Error {ier}, return None")
1224
+ return None
1225
+ except: # noqa
1226
+ xtg.warn("Unexpected error")
1227
+ raise
1228
+
1229
+ def discrete_to_continuous(self) -> None:
1230
+ """Convert from discrete to continuous values."""
1231
+ if not self.isdiscrete:
1232
+ logger.debug("No need to convert, already continuous")
1233
+ return
1234
+
1235
+ logger.debug("Converting to continuous ...")
1236
+ val = self._values.copy()
1237
+ val = val.astype("float64")
1238
+ self._values = val
1239
+ self._isdiscrete = False
1240
+ self._codes = {}
1241
+ self.roxar_dtype = np.float32
1242
+
1243
+ def continuous_to_discrete(self) -> None:
1244
+ """Convert from continuous to discrete values."""
1245
+ if self.isdiscrete:
1246
+ logger.debug("No need to convert, already discrete")
1247
+ return
1248
+
1249
+ logger.debug("Converting to discrete ...")
1250
+ val = self._values.copy()
1251
+ val = val.astype(np.int32)
1252
+ self._values = val
1253
+ self._isdiscrete = True
1254
+
1255
+ # make the code list
1256
+ uniq = np.unique(val).tolist()
1257
+ codes = dict(zip(uniq, uniq))
1258
+ codes = {k: str(v) for k, v in codes.items()} # val as strings
1259
+ self._codes = codes
1260
+ self.roxar_dtype = np.uint16
1261
+
1262
+ # ==================================================================================
1263
+ # Operations restricted to inside/outside polygons
1264
+ # ==================================================================================
1265
+
1266
+ def operation_polygons(
1267
+ self,
1268
+ poly: Polygons,
1269
+ value: float | int,
1270
+ opname: Literal["add", "sub", "mul", "div", "set"] = "add",
1271
+ inside: bool = True,
1272
+ ) -> None:
1273
+ """
1274
+ A generic function for doing 3D grid property operations
1275
+ restricted to inside or outside polygon(s).
1276
+
1277
+ This method requires that the property geometry is known
1278
+ (prop.geometry is set to a grid instance).
1279
+
1280
+ Args:
1281
+ poly: A XTGeo Polygons instance.
1282
+ value: Value to add, subtract etc.
1283
+ opname: Name of operation... "add", "sub", etc.
1284
+ Defaults to "add".
1285
+ inside: If True do operation inside polygons; else outside.
1286
+ Defaults to True.
1287
+
1288
+ """
1289
+ if self.geometry is None:
1290
+ msg = """
1291
+ You need to link the property to a grid geometry:"
1292
+
1293
+ myprop.geometry = mygrid
1294
+
1295
+ """
1296
+ xtg.warnuser(msg)
1297
+ raise ValueError("The geometry attribute is not set")
1298
+
1299
+ _gridprop_op1.operation_polygons(
1300
+ self, poly, value, opname=opname, inside=inside
1301
+ )
1302
+
1303
+ def add_inside(self, poly: Polygons, value: float | int) -> None:
1304
+ """Add a value (scalar) inside polygons."""
1305
+ self.operation_polygons(poly, value, opname="add", inside=True)
1306
+
1307
+ def add_outside(self, poly: Polygons, value: float | int) -> None:
1308
+ """Add a value (scalar) outside polygons."""
1309
+ self.operation_polygons(poly, value, opname="add", inside=False)
1310
+
1311
+ def sub_inside(self, poly: Polygons, value: float | int) -> None:
1312
+ """Subtract a value (scalar) inside polygons."""
1313
+ self.operation_polygons(poly, value, opname="sub", inside=True)
1314
+
1315
+ def sub_outside(self, poly: Polygons, value: float | int) -> None:
1316
+ """Subtract a value (scalar) outside polygons."""
1317
+ self.operation_polygons(poly, value, opname="sub", inside=False)
1318
+
1319
+ def mul_inside(self, poly: Polygons, value: float | int) -> None:
1320
+ """Multiply a value (scalar) inside polygons."""
1321
+ self.operation_polygons(poly, value, opname="mul", inside=True)
1322
+
1323
+ def mul_outside(self, poly: Polygons, value: float | int) -> None:
1324
+ """Multiply a value (scalar) outside polygons."""
1325
+ self.operation_polygons(poly, value, opname="mul", inside=False)
1326
+
1327
+ def div_inside(self, poly: Polygons, value: float | int) -> None:
1328
+ """Divide a value (scalar) inside polygons."""
1329
+ self.operation_polygons(poly, value, opname="div", inside=True)
1330
+
1331
+ def div_outside(self, poly: Polygons, value: float | int) -> None:
1332
+ """Divide a value (scalar) outside polygons."""
1333
+ self.operation_polygons(poly, value, opname="div", inside=False)
1334
+
1335
+ def set_inside(self, poly: Polygons, value: float | int) -> None:
1336
+ """Set a value (scalar) inside polygons."""
1337
+ self.operation_polygons(poly, value, opname="set", inside=True)
1338
+
1339
+ def set_outside(self, poly: Polygons, value: float | int) -> None:
1340
+ """Set a value (scalar) outside polygons."""
1341
+ self.operation_polygons(poly, value, opname="set", inside=False)