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
xtgeo/grid3d/grid.py ADDED
@@ -0,0 +1,2537 @@
1
+ """Module/class for 3D grids (corner point geometry) with XTGeo."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import TYPE_CHECKING, Any, Literal, NoReturn
7
+
8
+ import numpy as np
9
+ import numpy.ma as ma
10
+
11
+ import xtgeo
12
+ from xtgeo.common import XTGDescription, null_logger
13
+ from xtgeo.common.exceptions import InvalidFileFormatError
14
+ from xtgeo.common.sys import generic_hash
15
+ from xtgeo.common.types import Dimensions
16
+ from xtgeo.io._file import FileFormat, FileWrapper
17
+
18
+ from . import (
19
+ _grid3d_fence,
20
+ _grid_boundary,
21
+ _grid_etc1,
22
+ _grid_export,
23
+ _grid_hybrid,
24
+ _grid_import,
25
+ _grid_import_ecl,
26
+ _grid_refine,
27
+ _grid_roxapi,
28
+ _grid_wellzone,
29
+ _gridprop_lowlevel,
30
+ )
31
+ from ._grid3d import _Grid3D
32
+ from .grid_properties import GridProperties
33
+
34
+ if TYPE_CHECKING:
35
+ import pathlib
36
+ from collections.abc import Callable, Hashable
37
+
38
+ import pandas as pd
39
+
40
+ from xtgeo import Polygons, Well
41
+ from xtgeo.common.types import FileLike
42
+ from xtgeo.xyz.points import Points
43
+
44
+ from ._ecl_grid import Units
45
+ from .grid_property import GridProperty
46
+ from .types import METRIC
47
+
48
+ xtg = xtgeo.common.XTGeoDialog()
49
+ logger = null_logger(__name__)
50
+
51
+ # --------------------------------------------------------------------------------------
52
+ # Comment on "asmasked" vs "activeonly:
53
+ #
54
+ # "asmasked"=True will return a np.ma array, while "asmasked" = False will
55
+ # return a np.ndarray
56
+ #
57
+ # The "activeonly" will filter out masked entries, or use None or np.nan
58
+ # if "activeonly" is False.
59
+ #
60
+ # Use word "zerobased" for a bool regarding if startcell basis is 1 or 0
61
+ #
62
+ # For functions with mask=... ,they should be replaced with asmasked=...
63
+ # --------------------------------------------------------------------------------------
64
+
65
+
66
+ # METHODS as wrappers to class init + import
67
+ def _handle_import(
68
+ grid_constructor: Callable[..., Grid],
69
+ gfile: FileLike | FileWrapper,
70
+ fformat: str | None = None,
71
+ **kwargs: dict,
72
+ ) -> Grid:
73
+ """Handles the import given a constructor.
74
+
75
+ For backwards compatability we need to call different constructors
76
+ with grid __init__ parameters (As returned by _grid_import.from_file).
77
+ These are generally either the _reset method of an instance or Grid().
78
+
79
+ This function takes such a constructor, remaining arguments are interpreted
80
+ as they are in _grid_import.from_file and calls the constructor with the
81
+ resulting arguments.
82
+
83
+ """
84
+ gfile = FileWrapper(gfile, mode="rb")
85
+ if fformat == "eclipserun":
86
+ ecl_grid = grid_constructor(
87
+ **_grid_import.from_file(
88
+ FileWrapper(gfile.name + ".EGRID", mode="rb"), fformat=FileFormat.EGRID
89
+ )
90
+ )
91
+ _grid_import_ecl.import_ecl_run(gfile.name, ecl_grid=ecl_grid, **kwargs)
92
+ return ecl_grid
93
+
94
+ fmt = gfile.fileformat(fformat)
95
+ return grid_constructor(**_grid_import.from_file(gfile, fmt, **kwargs))
96
+
97
+
98
+ def grid_from_file(
99
+ gfile: FileLike | FileWrapper,
100
+ fformat: str | None = None,
101
+ **kwargs: dict[str, Any],
102
+ ) -> Grid:
103
+ """Read a grid (cornerpoint) from filelike and an returns a Grid() instance.
104
+
105
+ Args:
106
+ gfile: File name to be imported. If fformat="eclipse_run"
107
+ then a fileroot name shall be input here, see example below.
108
+ fformat: File format egrid/roff/grdecl/bgrdecl/eclipserun/xtgcpgeom
109
+ (None is default and means "guess")
110
+ initprops (str list): Optional, and only applicable for file format
111
+ "eclipserun". Provide a list the names of the properties here. A
112
+ special value "all" can be get all properties found in the INIT file
113
+ restartprops (str list): Optional, see initprops
114
+ restartdates (int list): Optional, required if restartprops
115
+ ijkrange (list-like): Optional, only applicable for hdf files, see
116
+ :meth:`Grid.from_hdf`.
117
+ zerobased (bool): Optional, only applicable for hdf files, see
118
+ :meth:`Grid.from_hdf`.
119
+ mmap (bool): Optional, only applicable for xtgf files, see
120
+ :meth:`Grid.from_xtgf`.
121
+
122
+ Example::
123
+
124
+ >>> import xtgeo
125
+ >>> mygrid = xtgeo.grid_from_file(reek_dir + "/REEK.EGRID")
126
+
127
+ Example using "eclipserun"::
128
+
129
+ >>> mycase = "REEK" # meaning REEK.EGRID, REEK.INIT, REEK.UNRST
130
+ >>> xg = xtgeo.grid_from_file(
131
+ ... reek_dir + "/" + mycase,
132
+ ... fformat="eclipserun",
133
+ ... initprops="all",
134
+ ... )
135
+ Grid ... filesrc='.../REEK.EGRID'
136
+
137
+ Raises:
138
+ OSError: if file is not found etc
139
+
140
+ """
141
+ return _handle_import(Grid, gfile, fformat, **kwargs)
142
+
143
+
144
+ def grid_from_roxar(
145
+ project: str,
146
+ gname: str,
147
+ realisation: int = 0,
148
+ info: bool = False,
149
+ ) -> Grid:
150
+ """Read a 3D grid inside a RMS project and return a Grid() instance.
151
+
152
+ Args:
153
+ project (str or special): The RMS project or the project variable
154
+ from inside RMS.
155
+ gname (str): Name of Grid Model in RMS.
156
+ realisation (int): Realisation number.
157
+ dimensions_only (bool): If True, only the ncol, nrow, nlay will
158
+ read. The actual grid geometry will remain empty (None). This will
159
+ be much faster of only grid size info is needed, e.g.
160
+ for initalising a grid property.
161
+ info (bool): If true, only grid info
162
+
163
+ Example::
164
+
165
+ # inside RMS
166
+ import xtgeo
167
+ mygrid = xtgeo.grid_from_roxar(project, "REEK_SIM")
168
+
169
+ """
170
+ return Grid(**_grid_roxapi.load_grid_from_rms(project, gname, realisation, info))
171
+
172
+
173
+ def create_box_grid(
174
+ dimension: Dimensions,
175
+ origin: tuple[float, float, float] = (0.0, 0.0, 0.0),
176
+ oricenter: bool = False,
177
+ increment: tuple[float, float, float] = (1.0, 1.0, 1.0),
178
+ rotation: float = 0.0,
179
+ flip: Literal[1, -1] = 1,
180
+ ) -> Grid:
181
+ """Create a rectangular 'shoebox' grid from spec.
182
+
183
+ Args:
184
+ dimension (NamedTuple of int): A tuple of (NCOL, NROW, NLAY)
185
+ origin (tuple of float): Startpoint of grid (x, y, z)
186
+ oricenter (bool): If False, startpoint is node, if True, use cell center
187
+ increment (tuple of float): Grid increments (xinc, yinc, zinc)
188
+ rotation (float): Rotation in degrees, anticlock from X axis.
189
+ flip (int): If +1, grid origin is lower left and left-handed;
190
+ if -1, origin is upper left and right-handed (row flip).
191
+
192
+ Returns:
193
+ Instance is updated (previous instance content will be erased)
194
+
195
+ .. versionadded:: 2.1
196
+ """
197
+ kwargs = _grid_etc1.create_box(
198
+ dimension=dimension,
199
+ origin=origin,
200
+ oricenter=oricenter,
201
+ increment=increment,
202
+ rotation=rotation,
203
+ flip=flip,
204
+ )
205
+
206
+ return Grid(**kwargs)
207
+
208
+
209
+ def grid_from_cube(
210
+ cube: xtgeo.Cube,
211
+ propname: str | None = "seismics",
212
+ oricenter: bool = True,
213
+ ) -> Grid:
214
+ """Create a rectangular 'shoebox' grid from an existing cube.
215
+
216
+ The cube values itself will then be stored with name given by ``propname`` key.
217
+
218
+ Since the cube actually is node centered, while grids are cell oriented,
219
+ the geometries here are shifted half an increment as default. To avoid this, use
220
+ oricenter=False.
221
+
222
+ Args:
223
+ cube: The xtgeo Cube instance
224
+ propname: Name of seismic property, if None then only the grid geometry
225
+ will be made
226
+ oricenter: Default is True, to treat seismic nodes as cell center values in
227
+ a grid.
228
+
229
+ .. versionadded:: 3.4
230
+ """
231
+
232
+ grd = create_box_grid(
233
+ cube.dimensions,
234
+ (cube.xori, cube.yori, cube.zori),
235
+ oricenter=oricenter,
236
+ increment=(cube.xinc, cube.yinc, cube.zinc),
237
+ rotation=cube.rotation,
238
+ flip=cube.yflip,
239
+ )
240
+ if propname is not None:
241
+ grd.props = [
242
+ xtgeo.GridProperty(
243
+ ncol=cube.ncol,
244
+ nrow=cube.nrow,
245
+ nlay=cube.nlay,
246
+ values=cube.values.copy(),
247
+ name=propname,
248
+ )
249
+ ]
250
+ return grd
251
+
252
+
253
+ def grid_from_surfaces(
254
+ surfaces: xtgeo.Surfaces,
255
+ ij_dimension: tuple[int, int] | None = None,
256
+ ij_origin: tuple[float, float] | None = None,
257
+ ij_increment: tuple[float, float] | None = None,
258
+ rotation: float | None = None,
259
+ tolerance: float | None = None,
260
+ ) -> Grid:
261
+ """Create a simple grid (non-faulted) from a stack of surfaces.
262
+
263
+ The surfaces shall be sorted from top to base, and they should not cross in depth.
264
+ In addition, it is required that they have the same settings (origin, rotation,
265
+ etc).
266
+
267
+ Args:
268
+ surfaces: The Surfaces instance
269
+ ij_dimension: The dimensions of the grid (ncol, nrow), default is to use the
270
+ dimension from the surfaces
271
+ ij_origin: The origin of the grid (x, y)
272
+ ij_increment: The increment of the grid (xinc, yinc), default is to use the
273
+ increment from the surfaces
274
+ rotation: The rotation of the grid in degrees, default is to use the rotation
275
+ from the surfaces
276
+ tolerance: The tolerance for sampling the surfaces. In particualar if the grid
277
+ origin, resolution and rotation are exactly the same as the surfaces,
278
+ the grid may not be able to sample the surfaces exactly at edges.
279
+ Lowering the tolerance may be used to avoid this. Default is 1e-6.
280
+
281
+ Example::
282
+
283
+ import xtgeo
284
+ surf1 = xtgeo.surface_from_file("top.surf")
285
+ surf2 = xtgeo.surface_from_file("base.surf")
286
+ surfaces = xtgeo.Surfaces([surf1, surf2])
287
+
288
+ grid = xtgeo.grid_from_surfaces(surfaces, ij_dimension=(20,30),
289
+ ij_increment=(50, 50), rotation=10)
290
+
291
+ """
292
+
293
+ tolerance = tolerance if tolerance else 1e-6
294
+
295
+ return _grid_etc1.create_grid_from_surfaces(
296
+ surfaces, ij_dimension, ij_origin, ij_increment, rotation, tolerance
297
+ )
298
+
299
+
300
+ # --------------------------------------------------------------------------------------
301
+ # Comment on dual porosity grids:
302
+ #
303
+ # Simulation grids may hold a "dual poro" or/and a "dual perm" system. This is
304
+ # supported here for EGRID format (only, so far), which:
305
+ # * Index 5 in FILEHEAD will be 1 if dual poro is True
306
+ # * Index 5 in FILEHEAD will be 2 if dual poro AND dual perm is True
307
+ # * ACTNUM values will be: 0, 1, 2 (inactive) or 3 (active) instead of normal
308
+ # 0 / 1 in the file:
309
+ # * 0 both Fracture and Matrix are inactive
310
+ # * 1 Matrix is active, Fracture is inactive (set to zero)
311
+ # * 2 Matrix is inactive (set to zero), Fracture is active
312
+ # * 3 Both Fracture and Matrix are active
313
+ #
314
+ # However, XTGeo will convert this 0..3 scheme back to 0..1 scheme for ACTNUM!
315
+ # In case of dualporo/perm, a special property holding the initial actnum
316
+ # will be made, which is self._dualactnum
317
+ #
318
+ # The property self._dualporo is True in case of Dual Porosity
319
+ # BOTH self._dualperm AND self._dualporo are True in case of Dual Permeability
320
+ #
321
+ # All properties in a dual p* system will be given a postfix "M" of "F", e.g.
322
+ # PORO --> POROM and POROF
323
+ # --------------------------------------------------------------------------------------
324
+
325
+ IJKRange: tuple[int, int, int, int, int, int]
326
+
327
+
328
+ class Grid(_Grid3D):
329
+ """Class for a 3D grid corner point geometry in XTGeo.
330
+
331
+ I.e. the geometric grid cells and the active cell indicator.
332
+
333
+ The grid geometry class instances are normally created when
334
+ importing a grid from file, as it is normally too complex to create from
335
+ scratch.
336
+
337
+ Args:
338
+ coordsv: numpy array of dtype float64 and dimensions (nx + 1, ny + 1, 6)
339
+ Giving the x,y,z values of the upper and lower corners in the grid.
340
+ zcornsv: numpy array of dtype float32 and dimensions (nx + 1, ny + 1, nz + 1, 4)
341
+ giving the sw, se, nw, ne corners along the i,jth corner line for
342
+ the kth layer.
343
+ actnumsv: numpy array of dtype int32 and dimensions (nx, ny, nz) giving
344
+ the activity number for each cell. 0 means inactive, 1 means
345
+ active. For dualporo=True/dualperm=True grids, value can also be 2
346
+ or 3 meaning rock volume only and pore volume only respectively.
347
+ dualporo (bool): True if dual porosity grid.
348
+ dualperm (bool): True if dual permeability grid.
349
+ subgrids: dictionary giving names to subset of layers. Has name as key and
350
+ list of layer indices as values. Defaults to no names given.
351
+ units: The length units the coordinates are in,
352
+ (either Units.CM, Units.METRES, Units.FEET for cm, metres and
353
+ feet respectively). Default (None) is unitless.
354
+ filesrc: Optional filename of grid.
355
+ props: GridProperties instance containing the properties of the grid, defaults
356
+ to empty instance.
357
+ name: Optional name of the grid.
358
+ roxgrid: Roxar Grid the Grid originates from if any, defaults to no such grid.
359
+ roxindexer: Roxar grid indexer for the roxgrid. Defaults to no such indexer.
360
+
361
+ See Also:
362
+ The :class:`.GridProperty` and the :class:`.GridProperties` classes.
363
+
364
+ """
365
+
366
+ def __init__(
367
+ self,
368
+ coordsv: np.ndarray,
369
+ zcornsv: np.ndarray,
370
+ actnumsv: np.ndarray,
371
+ dualporo: bool = False,
372
+ dualperm: bool = False,
373
+ subgrids: dict | None = None,
374
+ units: Units | None = None,
375
+ filesrc: pathlib.Path | str | None = None,
376
+ props: GridProperties | None = None,
377
+ name: str | None = None,
378
+ roxgrid: Any | None = None,
379
+ roxindexer: Any | None = None,
380
+ ):
381
+ coordsv = np.asarray(coordsv)
382
+ zcornsv = np.asarray(zcornsv)
383
+ actnumsv = np.asarray(actnumsv)
384
+ if coordsv.dtype != np.float64:
385
+ raise TypeError(
386
+ f"The dtype of the coordsv array must be float64, got {coordsv.dtype}"
387
+ )
388
+ if zcornsv.dtype != np.float32:
389
+ raise TypeError(
390
+ f"The dtype of the zcornsv array must be float32, got {zcornsv.dtype}"
391
+ )
392
+ if actnumsv.dtype != np.int32:
393
+ raise TypeError(
394
+ f"The dtype of the actnumsv array must be int32, got {actnumsv.dtype}"
395
+ )
396
+ if len(coordsv.shape) != 3 or coordsv.shape[2] != 6:
397
+ raise ValueError(
398
+ f"shape of coordsv should be (nx+1,ny+1,6), got {coordsv.shape}"
399
+ )
400
+ if len(zcornsv.shape) != 4 or zcornsv.shape[3] != 4:
401
+ raise ValueError(
402
+ f"shape of zcornsv should be (nx+1,ny+1,nz+1, 4), got {zcornsv.shape}"
403
+ )
404
+ if zcornsv.shape[0:2] != coordsv.shape[0:2]:
405
+ raise ValueError(
406
+ f"Mismatch between zcornsv and coordsv shape: {zcornsv.shape}"
407
+ f" vs {coordsv.shape}"
408
+ )
409
+ if np.any(np.asarray(zcornsv.shape[0:3]) != np.asarray(actnumsv.shape) + 1):
410
+ raise ValueError(
411
+ f"Mismatch between zcornsv and actnumsv shape: {zcornsv.shape}"
412
+ f" vs {actnumsv.shape}"
413
+ )
414
+
415
+ super().__init__(*actnumsv.shape)
416
+
417
+ self._xtgformat = 2
418
+ self._ncol = actnumsv.shape[0]
419
+ self._nrow = actnumsv.shape[1]
420
+ self._nlay = actnumsv.shape[2]
421
+
422
+ self._coordsv = coordsv
423
+ self._zcornsv = zcornsv
424
+ self._actnumsv = actnumsv
425
+ self._dualporo = dualporo
426
+ self._dualperm = dualperm
427
+
428
+ self._filesrc = filesrc
429
+
430
+ self._props: GridProperties | None = (
431
+ GridProperties(props=[]) if props is None else props
432
+ )
433
+
434
+ self._name = name
435
+ self._subgrids = subgrids
436
+ self._ijk_handedness: Literal["left", "right"] | None = None
437
+
438
+ self._dualactnum = None
439
+ if dualporo:
440
+ self._dualactnum = self.get_actnum(name="DUALACTNUM")
441
+ acttmp = self._dualactnum.copy()
442
+ acttmp.values[acttmp.values >= 1] = 1
443
+ self.set_actnum(acttmp)
444
+
445
+ self._metadata = xtgeo.MetaDataCPGeometry()
446
+ self._metadata.required = self
447
+
448
+ # Roxar api spesific:
449
+ self._roxgrid = roxgrid
450
+ self._roxindexer = roxindexer
451
+
452
+ self.units = units
453
+
454
+ self._tmp: dict = {}
455
+
456
+ def __repr__(self) -> str:
457
+ """The __repr__ method."""
458
+ logger.info("Invoke __repr__ for grid")
459
+ return (
460
+ f"{self.__class__.__name__} (id={id(self)}) ncol={self._ncol!r}, "
461
+ f"nrow={self._nrow!r}, nlay={self._nlay!r}, filesrc={self._filesrc!r}"
462
+ )
463
+
464
+ def __str__(self) -> str:
465
+ """The __str__ method for user friendly print."""
466
+ logger.debug("Invoke __str__ for grid", stack_info=True)
467
+
468
+ return self.describe(flush=False) or ""
469
+
470
+ def __hash__(self):
471
+ """The __hash__ method."""
472
+ return hash(self.generate_hash())
473
+
474
+ # ==================================================================================
475
+ # Public Properties:
476
+ # ==================================================================================
477
+
478
+ @property
479
+ def metadata(self) -> xtgeo.MetaDataCPGeometry:
480
+ """obj: Return or set metadata instance of type MetaDataCPGeometry."""
481
+ return self._metadata
482
+
483
+ @metadata.setter
484
+ def metadata(self, obj: xtgeo.MetaDataCPGeometry) -> None:
485
+ # The current metadata object can be replaced. A bit dangerous so further
486
+ # check must be done to validate. TODO.
487
+ if not isinstance(obj, xtgeo.MetaDataCPGeometry):
488
+ raise ValueError("Input obj not an instance of MetaDataCPGeometry")
489
+
490
+ self._metadata = obj # checking is currently missing! TODO
491
+
492
+ @property
493
+ def filesrc(self) -> str | pathlib.Path | None:
494
+ """str: Source for grid (filepath or name in RMS)."""
495
+ return self._filesrc
496
+
497
+ @property
498
+ def name(self) -> str | None:
499
+ """str: Name attribute of grid."""
500
+ return self._name
501
+
502
+ @name.setter
503
+ def name(self, name: str) -> None:
504
+ if not isinstance(name, str):
505
+ raise ValueError("Input name is not a text string")
506
+ self._name = name
507
+
508
+ @property
509
+ def dimensions(self) -> Dimensions:
510
+ """Dimensions NamedTuple: The grid dimensions (read only)."""
511
+ return Dimensions(self.ncol, self.nrow, self.nlay)
512
+
513
+ @property
514
+ def vectordimensions(self) -> tuple[int, int, int]:
515
+ """3-tuple: The storage grid array dimensions tuple of 3 integers (read only).
516
+
517
+ The tuple is (ncoord, nzcorn, nactnum).
518
+ """
519
+ ncoord = (self.ncol + 1) * (self.nrow + 1) * 2 * 3
520
+ nzcorn = self.ncol * self.nrow * (self.nlay + 1) * 4
521
+ ntot = self.ncol * self.nrow * self.nlay
522
+
523
+ return (ncoord, nzcorn, ntot)
524
+
525
+ @property
526
+ def ijk_handedness(self) -> Literal["left", "right"] | None:
527
+ """str: IJK handedness for grids, "right" or "left".
528
+
529
+ For a non-rotated grid with K increasing with depth, 'left' is corner in
530
+ lower-left, while 'right' is origin in upper-left corner.
531
+
532
+ """
533
+ nflip = _grid_etc1.estimate_flip(self)
534
+ if nflip == 1:
535
+ self._ijk_handedness = "left"
536
+ elif nflip == -1:
537
+ self._ijk_handedness = "right"
538
+ else:
539
+ self._ijk_handedness = None # cannot determine
540
+
541
+ return self._ijk_handedness
542
+
543
+ @ijk_handedness.setter
544
+ def ijk_handedness(self, value: Literal["left", "right"]) -> None:
545
+ if value not in ("right", "left"):
546
+ raise ValueError("The value must be 'right' or 'left'")
547
+ self.reverse_row_axis(ijk_handedness=value)
548
+ self._ijk_handedness = value
549
+
550
+ @property
551
+ def subgrids(self) -> dict[str, range | list[int]] | None:
552
+ """:obj:`list` of :obj:`int`: A dict with subgrid name and an array as value.
553
+
554
+ I.e. a dict on the form ``{"name1": [1, 2, 3, 4], "name2": [5, 6, 7],
555
+ "name3": [8, 9, 10]}``, here meaning 3 subgrids where upper is 4
556
+ cells vertically, then 3, then 3. The numbers must sum to NLAY.
557
+
558
+ The numbering in the arrays are 1 based; meaning uppermost layer is 1
559
+ (not 0).
560
+
561
+ None will be returned if no subgrid indexing is present.
562
+
563
+ See also :meth:`set_subgrids()` and :meth:`get_subgrids()` which
564
+ have a similar function, but differs a bit.
565
+
566
+ Note that this design is a bit different from the Roxar API, where
567
+ repeated sections are allowed, and where indices start from 0,
568
+ not one.
569
+ """
570
+ return None if self._subgrids is None else self._subgrids
571
+
572
+ @subgrids.setter
573
+ def subgrids(
574
+ self,
575
+ sgrids: dict[str, range | list[int]] | None,
576
+ ) -> None:
577
+ if sgrids is None:
578
+ self._subgrids = None
579
+ return
580
+
581
+ if not isinstance(sgrids, dict):
582
+ raise ValueError("Input to subgrids must be an ordered dictionary")
583
+
584
+ lengths = 0
585
+ zarr: list[Hashable] = []
586
+ keys: list[Hashable] = []
587
+
588
+ for key, val in sgrids.items():
589
+ lengths += len(val)
590
+ keys.append(key)
591
+ zarr.extend(val)
592
+
593
+ if lengths != self._nlay:
594
+ raise ValueError(
595
+ f"Subgrids lengths <{lengths}> not equal NLAY <{self.nlay}>"
596
+ )
597
+
598
+ if set(zarr) != set(range(1, self._nlay + 1)):
599
+ raise ValueError(
600
+ f"Arrays are not valid as the do not sum to vertical range, {zarr}"
601
+ )
602
+
603
+ if len(keys) != len(set(keys)):
604
+ raise ValueError(f"Subgrid keys are not unique: {keys}")
605
+
606
+ self._subgrids = sgrids
607
+
608
+ @property
609
+ def nactive(self) -> int:
610
+ """int: Returns the number of active cells (read only)."""
611
+ return len(self.actnum_indices)
612
+
613
+ @property
614
+ def actnum_array(self) -> np.ndarray:
615
+ """Returns the 3D ndarray which for active cells.
616
+
617
+ Values are 1 for active, 0 for inactive, in C order (read only).
618
+
619
+ """
620
+ actnumv = self.get_actnum().values
621
+ return ma.filled(actnumv, fill_value=0)
622
+
623
+ @property
624
+ def actnum_indices(self) -> np.ndarray:
625
+ """:obj:np.ndrarray: Indices (1D array) for active cells (read only).
626
+
627
+ In dual poro/perm systems, this will be the active indices for the
628
+ matrix cells and/or fracture cells (i.e. actnum >= 1).
629
+ """
630
+ actnumv = self.get_actnum()
631
+ actnumv = np.ravel(actnumv.values)
632
+ return np.flatnonzero(actnumv)
633
+
634
+ @property
635
+ def ntotal(self) -> int:
636
+ """Returns the total number of cells (read only)."""
637
+ return self.ncol * self.nrow * self.nlay
638
+
639
+ @property
640
+ def dualporo(self) -> bool:
641
+ """Boolean flag for dual porosity scheme (read only)."""
642
+ return self._dualporo
643
+
644
+ @property
645
+ def dualperm(self) -> bool:
646
+ """Boolean flag for dual porosity scheme (read only)."""
647
+ return self._dualperm
648
+
649
+ @property
650
+ def gridprops(self) -> GridProperties:
651
+ """Return or set a XTGeo GridProperties objects attached to the Grid."""
652
+ # Note, internally, the _props is a GridProperties instance, which is
653
+ # a class that holds a list of properties.
654
+ # Note that the `props` methods below will deal with properties in a
655
+ # list context
656
+
657
+ return self._props
658
+
659
+ @gridprops.setter
660
+ def gridprops(self, gprops: GridProperties) -> None:
661
+ if not isinstance(gprops, GridProperties):
662
+ raise ValueError("Input must be a GridProperties instance")
663
+
664
+ self._props = gprops # self._props is a GridProperties instance
665
+
666
+ @property
667
+ def props(self) -> list[GridProperty] | None:
668
+ """Return or set a list of XTGeo GridProperty objects.
669
+
670
+ When setting, the dimension of the property object is checked,
671
+ and will raise an IndexError if it does not match the grid.
672
+
673
+ When setting props, the current property list is replaced.
674
+
675
+ See also :meth:`append_prop()` method to add a property to the current list.
676
+
677
+ """
678
+ # Note, internally, the _props is a GridProperties instance, which is
679
+ # a class that holds a list of properties.
680
+
681
+ if isinstance(self._props, GridProperties):
682
+ return self._props.props
683
+ if isinstance(self._props, list):
684
+ raise RuntimeError("self._props is a list, not a GridProperties instance")
685
+ return None
686
+
687
+ @props.setter
688
+ def props(self, plist: list[GridProperty]) -> None:
689
+ if not isinstance(plist, list):
690
+ raise ValueError("Input to props must be a list")
691
+
692
+ for gridprop in plist:
693
+ if gridprop.dimensions != self.dimensions:
694
+ raise IndexError(
695
+ f"Property NX NY NZ <{gridprop.name}> does not match grid!"
696
+ )
697
+
698
+ self._props.props = plist # self._props is a GridProperties instance
699
+
700
+ @property
701
+ def propnames(self) -> list[str] | None:
702
+ """Returns a list of property names that are hooked to a grid."""
703
+ return None if self._props is None else self._props.names
704
+
705
+ @property
706
+ def roxgrid(self) -> Any | None:
707
+ """Get the Roxar native proj.grid_models[gname].get_grid() object."""
708
+ return self._roxgrid
709
+
710
+ @property
711
+ def roxindexer(self) -> Any | None:
712
+ """The Roxar native proj.grid_models[gname].get_grid().grid_indexer object."""
713
+ return self._roxindexer
714
+
715
+ def generate_hash(
716
+ self,
717
+ hashmethod: Literal["md5", "sha256", "blake2b"] = "md5",
718
+ ) -> str:
719
+ """Return a unique hash ID for current instance.
720
+
721
+ See :meth:`~xtgeo.common.sys.generic_hash()` for documentation.
722
+
723
+ .. versionadded:: 2.14
724
+ """
725
+ required = (
726
+ "_ncol",
727
+ "_nrow",
728
+ "_nlay",
729
+ "_coordsv",
730
+ "_zcornsv",
731
+ "_actnumsv",
732
+ )
733
+
734
+ gid = "".join(str(getattr(self, att)) for att in required)
735
+
736
+ return generic_hash(gid, hashmethod=hashmethod)
737
+
738
+ # ==================================================================================
739
+ # Create/import/export
740
+ # ==================================================================================
741
+
742
+ def to_file(self, gfile: FileLike, fformat: str = "roff") -> None:
743
+ """Export grid geometry to file, various vendor formats.
744
+
745
+ Args:
746
+ gfile (str): Name of output file
747
+ fformat (str): File format; roff/roff_binary/roff_ascii/
748
+ grdecl/bgrdecl/egrid.
749
+
750
+ Raises:
751
+ OSError: Directory does not exist
752
+
753
+ Example::
754
+ >>> grid = create_box_grid((2,2,2))
755
+ >>> grid.to_file(outdir + "/myfile.roff")
756
+ """
757
+ _gfile = FileWrapper(gfile, mode="wb")
758
+
759
+ _gfile.check_folder(raiseerror=OSError)
760
+
761
+ if fformat in FileFormat.ROFF_BINARY.value:
762
+ _grid_export.export_roff(self, _gfile.name, "binary")
763
+ elif fformat in FileFormat.ROFF_ASCII.value:
764
+ _grid_export.export_roff(self, _gfile.name, "ascii")
765
+ elif fformat in FileFormat.GRDECL.value:
766
+ _grid_export.export_grdecl(self, _gfile.name, 1)
767
+ elif fformat in FileFormat.BGRDECL.value:
768
+ _grid_export.export_grdecl(self, _gfile.name, 0)
769
+ elif fformat in FileFormat.EGRID.value:
770
+ _grid_export.export_egrid(self, _gfile.name)
771
+ elif fformat in FileFormat.FEGRID.value:
772
+ _grid_export.export_fegrid(self, _gfile.name)
773
+ elif fformat in FileFormat.HDF.value:
774
+ self.to_hdf(gfile)
775
+ elif fformat in FileFormat.XTG.value:
776
+ self.to_xtgf(gfile)
777
+ else:
778
+ extensions = FileFormat.extensions_string(
779
+ [
780
+ FileFormat.ROFF_BINARY,
781
+ FileFormat.ROFF_ASCII,
782
+ FileFormat.EGRID,
783
+ FileFormat.FEGRID,
784
+ FileFormat.GRDECL,
785
+ FileFormat.BGRDECL,
786
+ FileFormat.XTG,
787
+ FileFormat.HDF,
788
+ ]
789
+ )
790
+ raise InvalidFileFormatError(
791
+ f"File format {fformat} is invalid for type Grid. "
792
+ f"Supported formats are {extensions}."
793
+ )
794
+
795
+ def to_hdf(
796
+ self,
797
+ gfile: str | pathlib.Path,
798
+ compression: str | None = None,
799
+ chunks: bool | None = False,
800
+ subformat: int | None = 844,
801
+ ) -> FileLike:
802
+ """Export grid geometry to HDF5 storage format (experimental!).
803
+
804
+ Args:
805
+ gfile: Name of output file
806
+ compression: Compression method, such as "blosc" or "lzf"
807
+ chunks: chunks settings
808
+ subformat: Format of output arrays in terms of bytes. E.g. 844 means
809
+ 8 byte for COORD, 4 byte for ZCORNS, 4 byte for ACTNUM.
810
+
811
+ Raises:
812
+ OSError: Directory does not exist
813
+
814
+ Returns:
815
+ Used file object, or None if memory stream
816
+
817
+ Example:
818
+
819
+ >>> grid = create_box_grid((2,2,2))
820
+ >>> filename = grid.to_hdf(outdir + "/myfile_grid.h5")
821
+ """
822
+ _gfile = FileWrapper(gfile, mode="wb", obj=self)
823
+ _gfile.check_folder(raiseerror=OSError)
824
+
825
+ _grid_export.export_hdf5_cpgeom(
826
+ self, _gfile, compression=compression, chunks=chunks, subformat=subformat
827
+ )
828
+
829
+ return _gfile.file
830
+
831
+ def to_xtgf(
832
+ self,
833
+ gfile: str | pathlib.Path,
834
+ subformat: int | None = 844,
835
+ ) -> pathlib.Path:
836
+ """Export grid geometry to xtgeo native binary file format (experimental!).
837
+
838
+ Args:
839
+ gfile: Name of output file
840
+ subformat: Format of output arryas in terms of bytes. E.g. 844 means
841
+ 8 byte for COORD, 4 byte for ZCORNS, 4 byte for ACTNUM.
842
+
843
+ Raises:
844
+ OSError: Directory does not exist
845
+
846
+ Returns:
847
+ gfile (pathlib.Path): Used pathlib.Path file object, or None if
848
+ memory stream
849
+
850
+ Example::
851
+ >>> grid = create_box_grid((2,2,2))
852
+ >>> filename = grid.to_xtgf(outdir + "/myfile.xtg")
853
+ """
854
+ _gfile = FileWrapper(gfile, mode="wb", obj=self)
855
+ _gfile.check_folder(raiseerror=OSError)
856
+
857
+ _grid_export.export_xtgcpgeom(self, _gfile, subformat=subformat)
858
+
859
+ return _gfile.file
860
+
861
+ def to_roxar(
862
+ self,
863
+ project: str,
864
+ gname: str,
865
+ realisation: int = 0,
866
+ info: bool = False,
867
+ method: Literal["cpg", "roff"] = "cpg",
868
+ ) -> None:
869
+ """Export (upload) a grid from XTGeo to RMS via Roxar API.
870
+
871
+ Note:
872
+ When project is file path (direct access, outside RMS) then
873
+ ``to_roxar()`` will implicitly do a project save. Otherwise, the project
874
+ will not be saved until the user do an explicit project save action.
875
+
876
+ Args:
877
+ project (str or roxar._project): Inside RMS use the magic 'project',
878
+ else use path to RMS project, or a project reference
879
+ gname (str): Name of grid in RMS
880
+ realisation (int): Realisation umber, default 0
881
+ info (bool): TBD
882
+ method (str): Save approach, the default is 'cpg' which applied the internal
883
+ RMS API, while 'roff' will do a save to a temporary area, and then load
884
+ into RMS. For strange reasons, the 'roff' method is per RMS version
885
+ 14.2 a faster method (strange since file i/o is way more costly than
886
+ direct API access, in theory).
887
+
888
+ Note:
889
+ When storing grids that needs manipulation of inactive cells, .e.g.
890
+ ``activate_all()`` method, using method='roff' is recommended. The reason
891
+ is that saving cells using 'cpg' method will force zero depth values on
892
+ inactive cells.
893
+
894
+ """
895
+ _grid_roxapi.save_grid_to_rms(
896
+ self, project, gname, realisation, info=info, method=method
897
+ )
898
+
899
+ def convert_units(self, units: Units) -> None:
900
+ """
901
+ Convert the units of the grid.
902
+ Args:
903
+ units: The unit to convert to.
904
+ Raises:
905
+ ValueError: When the grid is unitless (no initial
906
+ unit information available).
907
+ """
908
+ if self.units is None:
909
+ raise ValueError("convert_units called on unitless grid.")
910
+ if self.units == units:
911
+ return
912
+ factor = self.units.conversion_factor(units)
913
+ self._coordsv *= factor
914
+ self._zcornsv *= factor
915
+ self.units = units
916
+
917
+ # ==================================================================================
918
+ # Various public methods
919
+ # ==================================================================================
920
+
921
+ def copy(self) -> Grid:
922
+ """Copy from one existing Grid instance to a new unique instance.
923
+
924
+ Note that associated properties will also be copied.
925
+
926
+ Example::
927
+
928
+ >>> grd = create_box_grid((5,5,5))
929
+ >>> newgrd = grd.copy()
930
+ """
931
+ logger.info("Copy a Grid instance")
932
+ return _grid_etc1.copy(self)
933
+
934
+ def describe(
935
+ self,
936
+ details: bool = False,
937
+ flush: bool = True,
938
+ ) -> str | None:
939
+ """Describe an instance by printing to stdout."""
940
+ logger.info("Print a description...")
941
+
942
+ dsc = XTGDescription()
943
+ dsc.title("Description of Grid instance")
944
+ dsc.txt("Object ID", id(self))
945
+ dsc.txt("File source", self._filesrc)
946
+ dsc.txt("Shape: NCOL, NROW, NLAY", self.ncol, self.nrow, self.nlay)
947
+ dsc.txt("Number of active cells", self.nactive)
948
+
949
+ if details:
950
+ geom = self.get_geometrics(cellcenter=True, return_dict=True)
951
+
952
+ assert isinstance(geom, dict)
953
+
954
+ prp1: list[str] = []
955
+ for prp in ("xmin", "xmax", "ymin", "ymax", "zmin", "zmax"):
956
+ prp1.append(f"{geom[prp]:10.3f}")
957
+
958
+ prp2: list[str] = []
959
+ for prp in ("avg_dx", "avg_dy", "avg_dz", "avg_rotation"):
960
+ prp2.append(f"{geom[prp]:7.4f}")
961
+
962
+ geox = self.get_geometrics(
963
+ cellcenter=False, allcells=True, return_dict=True
964
+ )
965
+ assert isinstance(geox, dict)
966
+ prp3: list[str] = []
967
+ for prp in ("xmin", "xmax", "ymin", "ymax", "zmin", "zmax"):
968
+ prp3.append(f"{geox[prp]:10.3f}")
969
+
970
+ prp4 = []
971
+ for prp in ("avg_dx", "avg_dy", "avg_dz", "avg_rotation"):
972
+ prp4.append(f"{geox[prp]:7.4f}")
973
+
974
+ dsc.txt("For active cells, using cell centers:")
975
+ dsc.txt("Xmin, Xmax, Ymin, Ymax, Zmin, Zmax:", *prp1)
976
+ dsc.txt("Avg DX, Avg DY, Avg DZ, Avg rotation:", *prp2)
977
+ dsc.txt("For all cells, using cell corners:")
978
+ dsc.txt("Xmin, Xmax, Ymin, Ymax, Zmin, Zmax:", *prp3)
979
+ dsc.txt("Avg DX, Avg DY, Avg DZ, Avg rotation:", *prp4)
980
+
981
+ dsc.txt("Attached grid props objects (names)", self.propnames)
982
+
983
+ if details:
984
+ dsc.txt("Attached grid props objects (id)", self.props)
985
+ if self.subgrids:
986
+ dsc.txt("Number of subgrids", len(list(self.subgrids.keys())))
987
+ else:
988
+ dsc.txt("Number of subgrids", "No subgrids")
989
+ if details:
990
+ dsc.txt("Subgrids details", json.dumps(self.get_subgrids()))
991
+ dsc.txt("Subgrids with values array", self.subgrids)
992
+
993
+ if flush:
994
+ dsc.flush()
995
+ return None
996
+
997
+ return dsc.astext()
998
+
999
+ def get_dataframe(
1000
+ self,
1001
+ activeonly: bool = True,
1002
+ ijk: bool = True,
1003
+ xyz: bool = True,
1004
+ doubleformat: bool = False,
1005
+ ) -> pd.DataFrame:
1006
+ """Returns a Pandas dataframe for the grid and any attached grid properties.
1007
+
1008
+ Note that this dataframe method is rather similar to GridProperties
1009
+ dataframe function, but have other defaults.
1010
+
1011
+ Args:
1012
+ activeonly (bool): If True (default), return only active cells.
1013
+ ijk (bool): If True (default), show cell indices, IX JY KZ columns
1014
+ xyz (bool): If True (default), show cell center coordinates.
1015
+ doubleformat (bool): If True, floats are 64 bit, otherwise 32 bit.
1016
+ Note that coordinates (if xyz=True) is always 64 bit floats.
1017
+
1018
+ Returns:
1019
+ A Pandas dataframe object
1020
+
1021
+ Example::
1022
+
1023
+ >>> import xtgeo
1024
+ >>> grd = xtgeo.grid_from_file(reek_dir + "/REEK.EGRID", fformat="egrid")
1025
+ >>> names = ["SOIL", "SWAT", "PRESSURE"]
1026
+ >>> dates = [19991201]
1027
+ >>> xpr = xtgeo.gridproperties_from_file(
1028
+ ... reek_dir + "/REEK.UNRST",
1029
+ ... fformat="unrst",
1030
+ ... names=names,
1031
+ ... dates=dates,
1032
+ ... grid=grd,
1033
+ ... )
1034
+ >>> grd.gridprops = xpr # attach properties to grid
1035
+
1036
+ >>> df = grd.get_dataframe()
1037
+
1038
+ >>> # save as CSV file
1039
+ >>> df.to_csv(outdir + "/mygrid.csv")
1040
+ """
1041
+ return self.gridprops.get_dataframe(
1042
+ grid=self,
1043
+ activeonly=activeonly,
1044
+ ijk=ijk,
1045
+ xyz=xyz,
1046
+ doubleformat=doubleformat,
1047
+ )
1048
+
1049
+ def get_vtk_esg_geometry_data(
1050
+ self,
1051
+ ) -> tuple[
1052
+ np.ndarray,
1053
+ np.ndarray,
1054
+ np.ndarray,
1055
+ np.ndarray,
1056
+ ]:
1057
+ """Get grid geometry data suitable for use with VTK's vtkExplicitStructuredGrid.
1058
+
1059
+ Builds and returns grid geometry data in a format tailored for use with VTK's
1060
+ explicit structured grid (ESG). Essentially this entails building an
1061
+ unstructured grid representation where all the grid cells are represented as
1062
+ hexahedrons with explicit connectivities. The cell connectivity array refers
1063
+ into the accompanying vertex array.
1064
+
1065
+ In VTK, cell order increases in I fastest, then J, then K.
1066
+
1067
+ The returned tuple contains:
1068
+ - numpy array with dimensions in terms of points (not cells)
1069
+ - vertex array, numpy array with vertex coordinates
1070
+ - connectivity array for all the cells, numpy array with integer indices
1071
+ - inactive cell indices, numpy array with integer indices
1072
+
1073
+ This function also tries to remove/weld duplicate vertices, but this is still
1074
+ a work in progress.
1075
+
1076
+ Example usage with VTK::
1077
+
1078
+ dims, vert_arr, conn_arr, inact_arr = xtg_grid.get_vtk_esg_geometry_data()
1079
+
1080
+ vert_arr = vert_arr.reshape(-1, 3)
1081
+ vtk_points = vtkPoints()
1082
+ vtk_points.SetData(numpy_to_vtk(vert_arr, deep=1))
1083
+
1084
+ vtk_cell_array = vtkCellArray()
1085
+ vtk_cell_array.SetData(8, numpy_to_vtkIdTypeArray(conn_arr, deep=1))
1086
+
1087
+ vtk_esgrid = vtkExplicitStructuredGrid()
1088
+ vtk_esgrid.SetDimensions(dims)
1089
+ vtk_esgrid.SetPoints(vtk_points)
1090
+ vtk_esgrid.SetCells(vtk_cell_array)
1091
+
1092
+ vtk_esgrid.ComputeFacesConnectivityFlagsArray()
1093
+
1094
+ ghost_arr_vtk = vtk_esgrid.AllocateCellGhostArray()
1095
+ ghost_arr_np = vtk_to_numpy(ghost_arr_vtk)
1096
+ ghost_arr_np[inact_arr] = vtkDataSetAttributes.HIDDENCELL
1097
+
1098
+ .. versionadded:: 2.20
1099
+ """
1100
+ return _grid_etc1.get_vtk_esg_geometry_data(self)
1101
+
1102
+ def get_vtk_geometries(self) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
1103
+ """Get necessary arrays on correct layout for VTK ExplicitStructuredGrid usage.
1104
+
1105
+ Example::
1106
+
1107
+ import pyvista as pv
1108
+ dim, crn, inactind = grd.get_vtk_geometries()
1109
+ grid = pv.ExplicitStructuredGrid(dim, crn)
1110
+ grid.flip_z(inplace=True)
1111
+ grid.hide_cells(inactind, inplace=True)
1112
+ grid.plot(show_edges=True)
1113
+
1114
+ Returns:
1115
+ dims, corners, inactive_indices
1116
+
1117
+ .. versionadded:: 2.18
1118
+ """
1119
+
1120
+ return _grid_etc1.get_vtk_geometries(self)
1121
+
1122
+ def append_prop(self, prop: GridProperty) -> None:
1123
+ """Append a single property to the grid."""
1124
+ if prop.dimensions != self.dimensions:
1125
+ raise ValueError(
1126
+ f"Dimensions does not match, got: {prop.dimensions} "
1127
+ f"expected: {self.dimensions}."
1128
+ )
1129
+
1130
+ self._props.append_props([prop])
1131
+
1132
+ def set_subgrids(self, sdict: dict[str, int] | None) -> None:
1133
+ """Set the subgrid from a simplified ordered dictionary.
1134
+
1135
+ The simplified dictionary is on the form
1136
+ {"name1": 3, "name2": 5}
1137
+
1138
+ Note that the input must be an dict!
1139
+
1140
+ """
1141
+ if sdict is None:
1142
+ return
1143
+
1144
+ if not isinstance(sdict, dict):
1145
+ raise ValueError("Input sdict is not an dict")
1146
+
1147
+ newsub: dict[str, range | list[int]] = {}
1148
+
1149
+ inn1 = 1
1150
+ for name, nsub in sdict.items():
1151
+ inn2 = inn1 + nsub
1152
+ newsub[name] = range(inn1, inn2)
1153
+ inn1 = inn2
1154
+
1155
+ self.subgrids = newsub
1156
+
1157
+ def get_subgrids(self) -> dict[str, int] | None:
1158
+ """Get the subgrids on a simplified ordered dictionary.
1159
+
1160
+ The simplified dictionary is on the form {"name1": 3, "name2": 5}
1161
+ """
1162
+ if not self.subgrids:
1163
+ return None
1164
+
1165
+ return {name: len(subb) for name, subb in self.subgrids.items()}
1166
+
1167
+ def rename_subgrids(self, names: list[str] | tuple[str, ...]) -> None:
1168
+ """Rename the names in the subgrids with the new names.
1169
+
1170
+ Args:
1171
+ names (list): List of new names, length of list must be same as length of
1172
+ subgrids
1173
+
1174
+
1175
+ Example::
1176
+
1177
+ >>> grd = create_box_grid((3, 3, 3))
1178
+ >>> grd.subgrids = dict(
1179
+ ... [("1", range(1,2)), ("2", range(2,3)), ("3", range(3,4))]
1180
+ ... )
1181
+ >>> grd.rename_subgrids(["Inky", "Tinky", "Pinky"])
1182
+
1183
+ Raises:
1184
+ ValueError: Input names not a list or a tuple
1185
+ ValueError: Lenght of names list not same as number of subgrids
1186
+
1187
+ .. versionadded:: 2.12
1188
+ """
1189
+ if not isinstance(names, (list, tuple)):
1190
+ raise ValueError("Input names not a list or a tuple")
1191
+
1192
+ assert self.subgrids is not None
1193
+ if len(names) != len(list(self.subgrids.keys())):
1194
+ raise ValueError("Lenght of names list not same as number of subgrids")
1195
+
1196
+ subs = self.get_subgrids()
1197
+ assert subs is not None
1198
+ subs_copy = subs.copy()
1199
+ for num, oldname in enumerate(self.subgrids.keys()):
1200
+ subs_copy[str(names[num])] = subs_copy.pop(oldname)
1201
+
1202
+ self.set_subgrids(subs_copy)
1203
+
1204
+ def estimate_design(
1205
+ self,
1206
+ nsub: str | int | None = None,
1207
+ ) -> dict[str, str | float] | None:
1208
+ """Estimate design and simbox thickness of the grid or a subgrid.
1209
+
1210
+ If the grid consists of several subgrids, and nsub is not specified, then
1211
+ a failure should be raised.
1212
+
1213
+ Args:
1214
+ nsub (int or str): Subgrid index to check, either as a number (starting
1215
+ with 1) or as subgrid name. If set to None, the whole grid will
1216
+ examined.
1217
+
1218
+ Returns:
1219
+ result (dict): where key "design" gives one letter in(P, T, B, X, M)
1220
+ P=proportional, T=topconform, B=baseconform,
1221
+ X=underdetermined, M=Mixed conform. Key "dzsimbox" is simbox thickness
1222
+ estimate per cell. None if nsub is given, but subgrids are missing, or
1223
+ nsub (name or number) is out of range.
1224
+
1225
+ Example::
1226
+
1227
+ >>> import xtgeo
1228
+ >>> grd = xtgeo.grid_from_file(emerald_dir + "/emerald_hetero_grid.roff")
1229
+ >>> print(grd.subgrids)
1230
+ dict([('subgrid_0', range(1, 17)), ('subgrid_1', range(17, 47))])
1231
+ >>> res = grd.estimate_design(nsub="subgrid_0")
1232
+ >>> print("Subgrid design is", res["design"])
1233
+ Subgrid design is P
1234
+ >>> print("Subgrid simbox thickness is", res["dzsimbox"])
1235
+ Subgrid simbox thickness is 2.548...
1236
+
1237
+
1238
+
1239
+ """
1240
+ nsubname = None
1241
+
1242
+ if nsub is None and self.subgrids:
1243
+ raise ValueError("Subgrids exists, nsub cannot be None")
1244
+
1245
+ if nsub is not None:
1246
+ if not self.subgrids:
1247
+ return None
1248
+
1249
+ if isinstance(nsub, int):
1250
+ try:
1251
+ nsubname = list(self.subgrids.keys())[nsub - 1]
1252
+ except IndexError:
1253
+ return None
1254
+
1255
+ elif isinstance(nsub, str):
1256
+ nsubname = nsub
1257
+ else:
1258
+ raise ValueError("Key nsub of wrong type, must be a number or a name")
1259
+
1260
+ if nsubname not in self.subgrids:
1261
+ return None
1262
+
1263
+ return _grid_etc1.estimate_design(self, nsubname)
1264
+
1265
+ def estimate_flip(self) -> Literal[1, -1]:
1266
+ """Estimate flip (handedness) of grid returns as 1 or -1.
1267
+
1268
+ The flip numbers are 1 for left-handed and -1 for right-handed.
1269
+
1270
+ .. seealso:: :py:attr:`~ijk_handedness`
1271
+ """
1272
+ return _grid_etc1.estimate_flip(self)
1273
+
1274
+ def subgrids_from_zoneprop(self, zoneprop: GridProperty) -> dict[str, int] | None:
1275
+ """Estimate subgrid index from a zone property.
1276
+
1277
+ The new will esimate which will replace the current if any.
1278
+
1279
+ Args:
1280
+ zoneprop(GridProperty): a XTGeo GridProperty instance.
1281
+
1282
+ Returns:
1283
+ Will also return simplified dictionary is on the form
1284
+ {"name1": 3, "name2": 5}
1285
+ """
1286
+ _, _, k_index = self.get_ijk()
1287
+ kval = k_index.values
1288
+ zprval = zoneprop.values
1289
+ minzone = int(zprval.min())
1290
+ maxzone = int(zprval.max())
1291
+
1292
+ newd: dict[str, range] = {}
1293
+ for izone in range(minzone, maxzone + 1):
1294
+ mininzn = int(kval[zprval == izone].min()) # 1 base
1295
+ maxinzn = int(kval[zprval == izone].max()) # 1 base
1296
+
1297
+ newd[zoneprop.codes.get(izone, "zone" + str(izone))] = range(
1298
+ mininzn, maxinzn + 1
1299
+ )
1300
+
1301
+ self.subgrids = newd # type: ignore
1302
+
1303
+ return self.get_subgrids()
1304
+
1305
+ def get_zoneprop_from_subgrids(self) -> NoReturn:
1306
+ """Make a XTGeo GridProperty instance for a Zone property subgrid index."""
1307
+ raise NotImplementedError("Not yet; todo")
1308
+
1309
+ def get_boundary_polygons(
1310
+ self: Grid,
1311
+ alpha_factor: float = 1.0,
1312
+ convex: bool = False,
1313
+ simplify: bool | dict[str, Any] = True,
1314
+ filter_array: np.ndarray | None = None,
1315
+ ) -> Polygons:
1316
+ """Extract boundary polygons from the grid cell centers.
1317
+
1318
+ A ``filter_array`` can be applied to extract boundaries around specific
1319
+ parts of the grid e.g. a region or a zone.
1320
+
1321
+ The concavity and precision of the boundaries are controlled by the
1322
+ ``alpha_factor``. A low ``alpha_factor`` makes more precise boundaries,
1323
+ while a larger value makes more rough polygons.
1324
+
1325
+ Note that the ``alpha_factor`` is a multiplier (default value 1) on top
1326
+ of an auto estimated value, derived from the maximum xinc and yinc from
1327
+ the grid cells. Dependent on the regularity of the grid, tuning of the
1328
+ alpha_factor (up/down) is sometimes necessary to get satisfactory results.
1329
+
1330
+ Args:
1331
+ alpha_factor: An alpha multiplier, which controls the precision of the
1332
+ boundaries. A higher number will produce smoother and less accurate
1333
+ polygons. Not applied if convex is set to True.
1334
+ convex: The default is False, which means that a "concave hull" algorithm
1335
+ is used. If convex is True, the alpha factor is overridden to a large
1336
+ number, producing a 'convex' shape boundary instead.
1337
+ simplify: If True, a simplification is done in order to reduce the number
1338
+ of points in the polygons, where tolerance is 0.1. Another
1339
+ alternative to True is to input a Dict on the form
1340
+ ``{"tolerance": 2.0, "preserve_topology": True}``, cf. the
1341
+ :func:`Polygons.simplify()` method. For details on e.g. tolerance, see
1342
+ Shapely's simplify() method.
1343
+ filter_array: An numpy boolean array with equal shape as the grid dimension,
1344
+ used to filter the grid cells and define where to extract boundaries.
1345
+
1346
+ Returns:
1347
+ A XTGeo Polygons instance
1348
+
1349
+ Example::
1350
+
1351
+ grid = xtgeo.grid_from_roxar(project, "Simgrid")
1352
+ # extract polygon for a specific region, here region 3
1353
+ region = xtgeo.gridproperty_from_roxar(project, "Simgrid", "Regions")
1354
+ filter_array = (region.values==3)
1355
+ boundary = grid.get_boundary_polygons(filter_array=filter_array)
1356
+
1357
+ See also:
1358
+ The :func:`Polygons.boundary_from_points()` class method.
1359
+
1360
+ """
1361
+ return _grid_boundary.create_boundary(
1362
+ self, alpha_factor, convex, simplify, filter_array
1363
+ )
1364
+
1365
+ def get_actnum_indices(
1366
+ self,
1367
+ order: Literal["C", "F", "A", "K"] = "C",
1368
+ inverse: bool = False,
1369
+ ) -> np.ndarray:
1370
+ """Returns the 1D ndarray which holds the indices for active cells.
1371
+
1372
+ Args:
1373
+ order (str): "Either 'C' (default) or 'F' order).
1374
+ inverse (bool): Default is False, returns indices for inactive cells
1375
+ if True.
1376
+
1377
+ .. versionchanged:: 2.18 Added inverse option
1378
+ """
1379
+ actnumv = self.get_actnum().values.copy(order=order)
1380
+ actnumv = np.ravel(actnumv, order=order)
1381
+ if inverse:
1382
+ actnumv -= 1
1383
+ return np.flatnonzero(actnumv)
1384
+ return np.flatnonzero(actnumv)
1385
+
1386
+ def get_dualactnum_indices(
1387
+ self,
1388
+ order: Literal["C", "F", "A", "K"] = "C",
1389
+ fracture: bool = False,
1390
+ ) -> np.ndarray | None:
1391
+ """Returns the 1D ndarray which holds the indices for matrix/fracture cases.
1392
+
1393
+ Args:
1394
+ order (str): "Either 'C' (default) or 'F' order).
1395
+ fracture (bool): If True use Fracture properties.
1396
+ """
1397
+ if not self._dualporo:
1398
+ return None
1399
+
1400
+ assert self._dualactnum is not None
1401
+ actnumv = self._dualactnum.values.copy(order=order)
1402
+ actnumv = np.ravel(actnumv, order=order)
1403
+
1404
+ if fracture:
1405
+ actnumvf = actnumv.copy()
1406
+ actnumvf[(actnumv == 3) | (actnumv == 2)] = 1
1407
+ actnumvf[(actnumv == 1) | (actnumv == 0)] = 0
1408
+ return np.flatnonzero(actnumvf)
1409
+
1410
+ actnumvm = actnumv.copy()
1411
+ actnumvm[(actnumv == 3) | (actnumv == 1)] = 1
1412
+ actnumvm[(actnumv == 2) | (actnumv == 0)] = 0
1413
+ return np.flatnonzero(actnumvm)
1414
+
1415
+ def get_prop_by_name(self, name: str) -> GridProperty | None:
1416
+ """Gets a property object by name lookup, return None if not present."""
1417
+
1418
+ if self.props is None:
1419
+ raise RuntimeError(
1420
+ f"{self.__class__.__name__} has no gird "
1421
+ "property objects (self.props is None)"
1422
+ )
1423
+
1424
+ for obj in self.props:
1425
+ if obj.name == name:
1426
+ return obj
1427
+
1428
+ return None
1429
+
1430
+ def get_actnum(
1431
+ self,
1432
+ name: str = "ACTNUM",
1433
+ asmasked: bool = False,
1434
+ dual: bool = False,
1435
+ ) -> GridProperty:
1436
+ """Return an ACTNUM GridProperty object.
1437
+
1438
+ Args:
1439
+ name (str): name of property in the XTGeo GridProperty object.
1440
+ asmasked (bool): Actnum is returned with all cells shown
1441
+ as default. Use asmasked=True to make 0 entries masked.
1442
+ dual (bool): If True, and the grid is a dualporo/perm grid, an
1443
+ extended ACTNUM is applied (numbers 0..3)
1444
+
1445
+ Example::
1446
+
1447
+ >>> import xtgeo
1448
+ >>> mygrid = xtgeo.create_box_grid((2,2,2))
1449
+ >>> act = mygrid.get_actnum()
1450
+ >>> print("{}% of cells are active".format(act.values.mean() * 100))
1451
+ 100.0% of cells are active
1452
+
1453
+ .. versionchanged:: 2.6 Added ``dual`` keyword
1454
+ """
1455
+ if dual and self._dualactnum:
1456
+ act = self._dualactnum.copy()
1457
+ else:
1458
+ act = xtgeo.grid3d.GridProperty(
1459
+ ncol=self._ncol,
1460
+ nrow=self._nrow,
1461
+ nlay=self._nlay,
1462
+ values=np.zeros((self._ncol, self._nrow, self._nlay), dtype=np.int32),
1463
+ name=name,
1464
+ discrete=True,
1465
+ )
1466
+
1467
+ if self._xtgformat == 1:
1468
+ values = _gridprop_lowlevel.f2c_order(self, self._actnumsv)
1469
+ else:
1470
+ values = self._actnumsv
1471
+
1472
+ act.values = values
1473
+ act.mask_undef()
1474
+
1475
+ if asmasked:
1476
+ act.values = ma.masked_equal(act.values, 0)
1477
+
1478
+ act.codes = {0: "0", 1: "1"}
1479
+ if dual and self._dualactnum:
1480
+ act.codes = {0: "0", 1: "1", 2: "2", 3: "3"}
1481
+
1482
+ return act
1483
+
1484
+ def set_actnum(self, actnum: GridProperty) -> None:
1485
+ """Modify the existing active cell index, ACTNUM.
1486
+
1487
+ Args:
1488
+ actnum (GridProperty): a gridproperty instance with 1 for active
1489
+ cells, 0 for inactive cells
1490
+
1491
+ Example::
1492
+ >>> mygrid = create_box_grid((5,5,5))
1493
+ >>> act = mygrid.get_actnum()
1494
+ >>> act.values[:, :, :] = 1
1495
+ >>> act.values[:, :, 4] = 0
1496
+ >>> mygrid.set_actnum(act)
1497
+ """
1498
+ val1d = actnum.values.ravel()
1499
+
1500
+ if self._xtgformat == 1:
1501
+ self._actnumsv = _gridprop_lowlevel.c2f_order(self, val1d)
1502
+ else:
1503
+ self._actnumsv = np.ma.filled(actnum.values, fill_value=0).astype(np.int32)
1504
+
1505
+ def get_dz(
1506
+ self,
1507
+ name: str = "dZ",
1508
+ flip: bool = True,
1509
+ asmasked: bool = True,
1510
+ metric: METRIC = "z projection",
1511
+ ) -> GridProperty:
1512
+ """Return the dZ as GridProperty object.
1513
+
1514
+ Returns the average length of z direction edges for each
1515
+ cell as a GridProperty. The length is by default the
1516
+ z delta, ie. projected onto the z dimension (see the metric parameter).
1517
+
1518
+ Args:
1519
+ name (str): name of property
1520
+ flip (bool): Use False for Petrel grids were Z is negative down
1521
+ (experimental)
1522
+ asmasked (bool): True if only for active cells, False for all cells
1523
+ metric (str): One of the following metrics:
1524
+ * "euclid": sqrt(dx^2 + dy^2 + dz^2)
1525
+ * "horizontal": sqrt(dx^2 + dy^2)
1526
+ * "east west vertical": sqrt(dy^2 + dz^2)
1527
+ * "north south vertical": sqrt(dx^2 + dz^2)
1528
+ * "x projection": dx
1529
+ * "y projection": dy
1530
+ * "z projection": dz
1531
+
1532
+ Returns:
1533
+ A XTGeo GridProperty object dZ
1534
+ """
1535
+ return _grid_etc1.get_dz(
1536
+ self,
1537
+ name=name,
1538
+ flip=flip,
1539
+ asmasked=asmasked,
1540
+ metric=metric,
1541
+ )
1542
+
1543
+ def get_dx(
1544
+ self,
1545
+ name: str = "dX",
1546
+ asmasked: bool = True,
1547
+ metric: METRIC = "horizontal",
1548
+ ) -> GridProperty:
1549
+ """Return the dX as GridProperty object.
1550
+
1551
+ Returns the average length of x direction edges for each
1552
+ cell as a GridProperty. The length is by default horizontal
1553
+ vector length (see the metric parameter).
1554
+
1555
+ Args:
1556
+ name (str): names of properties
1557
+ asmasked (bool). If True, make a np.ma array where inactive cells
1558
+ are masked.
1559
+ metric (str): One of the following metrics:
1560
+ * "euclid": sqrt(dx^2 + dy^2 + dz^2)
1561
+ * "horizontal": sqrt(dx^2 + dy^2)
1562
+ * "east west vertical": sqrt(dy^2 + dz^2)
1563
+ * "north south vertical": sqrt(dx^2 + dz^2)
1564
+ * "x projection": dx
1565
+ * "y projection": dy
1566
+ * "z projection": dz
1567
+
1568
+ Returns:
1569
+ XTGeo GridProperty objects containing dx.
1570
+ """
1571
+ return _grid_etc1.get_dx(self, name=name, asmasked=asmasked, metric=metric)
1572
+
1573
+ def get_dy(
1574
+ self,
1575
+ name: str = "dY",
1576
+ asmasked: bool = True,
1577
+ metric: METRIC = "horizontal",
1578
+ ) -> GridProperty:
1579
+ """Return the dY as GridProperty object.
1580
+
1581
+ Returns the average length of y direction edges for each
1582
+ cell as a GridProperty. The length is by default horizontal
1583
+ vector length (see the metric parameter).
1584
+
1585
+ Args:
1586
+ name (str): names of properties
1587
+ asmasked (bool). If True, make a np.ma array where inactive cells
1588
+ are masked.
1589
+ metric (str): One of the following metrics:
1590
+ * "euclid": sqrt(dx^2 + dy^2 + dz^2)
1591
+ * "horizontal": sqrt(dx^2 + dy^2)
1592
+ * "east west vertical": sqrt(dy^2 + dz^2)
1593
+ * "north south vertical": sqrt(dx^2 + dz^2)
1594
+ * "x projection": dx
1595
+ * "y projection": dy
1596
+ * "z projection": dz
1597
+
1598
+ Returns:
1599
+ Two XTGeo GridProperty objects (dx, dy).
1600
+ """
1601
+ return _grid_etc1.get_dy(self, name=name, asmasked=asmasked, metric=metric)
1602
+
1603
+ def get_cell_volume(
1604
+ self,
1605
+ ijk: tuple[int, int, int] = (1, 1, 1),
1606
+ activeonly: bool = True,
1607
+ zerobased: bool = False,
1608
+ precision: Literal[1, 2, 4] = 2,
1609
+ ) -> float:
1610
+ """Return the bulk volume for a given cell.
1611
+
1612
+ This method is currently *experimental*.
1613
+
1614
+ A bulk volume of a cornerpoint cell is actually a non-trivial and a non-unique
1615
+ entity. The volume is approximated by dividing the cell (hexahedron) into
1616
+ 6 tetrehedrons; there is however a large number of ways to do this division.
1617
+
1618
+ As default (precision=2) an average of two different ways to divide the cell
1619
+ into tetrahedrons is averaged.
1620
+
1621
+ Args:
1622
+ ijk (tuple): A tuple of I J K (NB! cell counting starts from 1
1623
+ unless zerobased is True).
1624
+ activeonly (bool): Skip undef cells if True; return None for inactive.
1625
+ precision (int): An even number indication precision level,where
1626
+ a higher number means increased precision but also increased computing
1627
+ time. Currently 1, 2, 4 are supported.
1628
+
1629
+ Returns:
1630
+ Cell total bulk volume
1631
+
1632
+ Example::
1633
+
1634
+ >>> import xtgeo
1635
+ >>> grid = xtgeo.grid_from_file(reek_dir + "/REEK.EGRID")
1636
+ >>> print(grid.get_cell_volume(ijk=(10,13,2)))
1637
+ 107056...
1638
+
1639
+ .. versionadded:: 2.13 (as experimental)
1640
+ """
1641
+ return _grid_etc1.get_cell_volume(
1642
+ self,
1643
+ ijk=ijk,
1644
+ activeonly=activeonly,
1645
+ zerobased=zerobased,
1646
+ precision=precision,
1647
+ )
1648
+
1649
+ def get_bulk_volume(
1650
+ self,
1651
+ name: str = "bulkvol",
1652
+ asmasked: bool = True,
1653
+ precision: Literal[1, 2, 4] = 2,
1654
+ ) -> GridProperty:
1655
+ """Return the geometric cell volume for all cells as a GridProperty object.
1656
+
1657
+ This method is currently *experimental*.
1658
+
1659
+ A bulk volume of a cornerpoint cell is actually a non-trivial and a non-unique
1660
+ entity. The volume is approximated by dividing the cell (hexahedron) into
1661
+ 6 tetrehedrons; there is however a large number of ways to do this division.
1662
+
1663
+ As default (precision=2) an average of two different ways to divide the cell
1664
+ into tetrahedrons is averaged.
1665
+
1666
+ Args:
1667
+ name (str): name of property, default to "bulkvol"
1668
+ asmasked (bool). If True, make a np.ma array where inactive cells
1669
+ are masked. Otherwise a numpy array will all bulk for all cells is
1670
+ returned
1671
+ precision (int): An number indication precision level, where
1672
+ a higher number means increased precision but also increased computing
1673
+ time. Currently 1, 2 (default), 4 are supported.
1674
+
1675
+ Returns:
1676
+ XTGeo GridProperty object
1677
+
1678
+ .. versionadded:: 2.13 (as experimental)
1679
+
1680
+ """
1681
+ return _grid_etc1.get_bulk_volume(
1682
+ self, name=name, asmasked=asmasked, precision=precision
1683
+ )
1684
+
1685
+ def get_heights_above_ffl(
1686
+ self,
1687
+ ffl: GridProperty,
1688
+ option: str = "cell_center_above_ffl",
1689
+ ) -> tuple[GridProperty, GridProperty, GridProperty]:
1690
+ """Returns 3 properties: htop, hbot and hmid, primarely for use in Sw models."
1691
+
1692
+ Args:
1693
+ ffl: Free fluid level e.g. FWL (or level whatever is required; a level from
1694
+ which cells above will be shown as delta heights (positive), while
1695
+ cells below will have 0.0 values.
1696
+ option: How to compute values, as either "cell_center_above_ffl" or
1697
+ "cell_corners_above_ffl". The first one looks at cell Z centerlines, and
1698
+ compute the top, the bottom and the midpoint. The second will look at
1699
+ cell corners, using the uppermost corner for top, and the lowermost
1700
+ corner for bottom. In both cases, values are modified if cell is
1701
+ intersected with the provided ffl.
1702
+
1703
+ Returns:
1704
+ (htop, hbot, hmid) delta heights, as xtgeo GridProperty objects
1705
+
1706
+ .. versionadded:: 3.9
1707
+
1708
+ """
1709
+ return _grid_etc1.get_heights_above_ffl(self, ffl=ffl, option=option)
1710
+
1711
+ def get_property_between_surfaces(
1712
+ self,
1713
+ top: xtgeo.RegularSurface,
1714
+ base: xtgeo.RegularSurface,
1715
+ value: int = 1,
1716
+ name: str = "between_surfaces",
1717
+ ) -> GridProperty:
1718
+ """Returns a 3D GridProperty object with <value> between two surfaces."
1719
+
1720
+ Args:
1721
+ top: The bounding top surface (RegularSurface object)
1722
+ base: The bounding base surface (RegularSurface object)
1723
+ value: An integer > 0 to assign to cells between surfaces, 1 as default
1724
+ name: Name of the property, default is "between_surfaces"
1725
+
1726
+ Returns:
1727
+ xtgeo GridProperty object with <value> if cell center is between surfaces,
1728
+ otherwise 0. Note that the property wil be discrete if input value is an
1729
+ integer, otherwise it will be continuous.
1730
+
1731
+ .. versionadded:: 4.5
1732
+
1733
+ """
1734
+ return _grid_etc1.get_property_between_surfaces(self, top, base, value, name)
1735
+
1736
+ def get_ijk(
1737
+ self,
1738
+ names: tuple[str, str, str] = ("IX", "JY", "KZ"),
1739
+ asmasked: bool = True,
1740
+ zerobased: bool = False,
1741
+ ) -> tuple[GridProperty, GridProperty, GridProperty]:
1742
+ """Returns 3 xtgeo.grid3d.GridProperty objects: I counter, J counter, K counter.
1743
+
1744
+ Args:
1745
+ names: a 3 x tuple of names per property (default IX, JY, KZ).
1746
+ asmasked: If True, UNDEF cells are masked, default is True
1747
+ zerobased: If True, counter start from 0, otherwise 1 (default=1).
1748
+ """
1749
+ ixc, jyc, kzc = _grid_etc1.get_ijk(
1750
+ self, names=names, asmasked=asmasked, zerobased=zerobased
1751
+ )
1752
+
1753
+ # return the objects
1754
+ return ixc, jyc, kzc
1755
+
1756
+ def get_ijk_from_points(
1757
+ self,
1758
+ points: Points,
1759
+ activeonly: bool = True,
1760
+ zerobased: bool = False,
1761
+ dataframe: bool = True,
1762
+ includepoints: bool = True,
1763
+ columnnames: tuple[str, str, str] = ("IX", "JY", "KZ"),
1764
+ fmt: Literal["int", "float"] = "int",
1765
+ undef: int = -1,
1766
+ ) -> pd.DataFrame | list:
1767
+ """Returns a list/dataframe of cell indices based on a Points() instance.
1768
+
1769
+ If a point is outside the grid, -1 values are returned
1770
+
1771
+ Args:
1772
+ points (Points): A XTGeo Points instance
1773
+ activeonly (bool): If True, UNDEF cells are not included
1774
+ zerobased (bool): If True, counter start from 0, otherwise 1 (default=1).
1775
+ dataframe (bool): If True result is Pandas dataframe, otherwise a list
1776
+ of tuples
1777
+ includepoints (bool): If True, include the input points in result
1778
+ columnnames (tuple): Name of columns if dataframe is returned
1779
+ fmt (str): Format of IJK arrays (int/float). Default is "int"
1780
+ undef (int or float): Value to assign to undefined (outside) entries.
1781
+
1782
+ .. versionadded:: 2.6
1783
+ .. versionchanged:: 2.8 Added keywords `columnnames`, `fmt`, `undef`
1784
+ """
1785
+ return _grid_etc1.get_ijk_from_points(
1786
+ self,
1787
+ points,
1788
+ activeonly=activeonly,
1789
+ zerobased=zerobased,
1790
+ dataframe=dataframe,
1791
+ includepoints=includepoints,
1792
+ columnnames=columnnames,
1793
+ fmt=fmt,
1794
+ undef=undef,
1795
+ )
1796
+
1797
+ def get_xyz(
1798
+ self,
1799
+ names: tuple[str, str, str] = ("X_UTME", "Y_UTMN", "Z_TVDSS"),
1800
+ asmasked: bool = True,
1801
+ ) -> tuple[
1802
+ GridProperty,
1803
+ GridProperty,
1804
+ GridProperty,
1805
+ ]:
1806
+ """Returns 3 xtgeo.grid3d.GridProperty objects for x, y, z coordinates.
1807
+
1808
+ The values are mid cell values. Note that ACTNUM is
1809
+ ignored, so these is also extracted for UNDEF cells (which may have
1810
+ weird coordinates). However, the option asmasked=True will mask
1811
+ the numpies for undef cells.
1812
+
1813
+ Args:
1814
+ names: a 3 x tuple of names per property (default is X_UTME,
1815
+ Y_UTMN, Z_TVDSS).
1816
+ asmasked: If True, then inactive cells is masked (numpy.ma).
1817
+ """
1818
+ return _grid_etc1.get_xyz(self, names=tuple(names), asmasked=asmasked)
1819
+
1820
+ def get_xyz_cell_corners(
1821
+ self,
1822
+ ijk: tuple[int, int, int] = (1, 1, 1),
1823
+ activeonly: bool = True,
1824
+ zerobased: bool = False,
1825
+ ) -> tuple[int, ...]:
1826
+ """Return a 8 * 3 tuple x, y, z for each corner.
1827
+
1828
+ .. code-block:: none
1829
+
1830
+ 2 3
1831
+ !~~~~~~~!
1832
+ ! top !
1833
+ !~~~~~~~! Listing corners with Python index (0 base)
1834
+ 0 1
1835
+
1836
+ 6 7
1837
+ !~~~~~~~!
1838
+ ! base !
1839
+ !~~~~~~~!
1840
+ 4 5
1841
+
1842
+ Args:
1843
+ ijk (tuple): A tuple of I J K (NB! cell counting starts from 1
1844
+ unless zerobased is True)
1845
+ activeonly (bool): Skip undef cells if set to True.
1846
+
1847
+ Returns:
1848
+ A tuple with 24 elements (x1, y1, z1, ... x8, y8, z8)
1849
+ for 8 corners. None if cell is inactive and activeonly=True.
1850
+
1851
+ Example::
1852
+
1853
+ >>> grid = grid_from_file(reek_dir + "REEK.EGRID")
1854
+ >>> print(grid.get_xyz_cell_corners(ijk=(10,13,2)))
1855
+ (458704.10..., 1716.969970703125)
1856
+
1857
+ Raises:
1858
+ RuntimeWarning if spesification is invalid.
1859
+ """
1860
+ return _grid_etc1.get_xyz_cell_corners(
1861
+ self, ijk=ijk, activeonly=activeonly, zerobased=zerobased
1862
+ )
1863
+
1864
+ def get_xyz_corners(
1865
+ self, names: tuple[str, str, str] = ("X_UTME", "Y_UTMN", "Z_TVDSS")
1866
+ ) -> tuple[GridProperty, ...]:
1867
+ """Returns 8*3 (24) xtgeo.grid3d.GridProperty objects, x, y, z for each corner.
1868
+
1869
+ The values are cell corner values. Note that ACTNUM is
1870
+ ignored, so these is also extracted for UNDEF cells (which may have
1871
+ weird coordinates).
1872
+
1873
+ .. code-block:: none
1874
+
1875
+ 2 3
1876
+ !~~~~~~~!
1877
+ ! top !
1878
+ !~~~~~~~! Listing corners with Python index (0 base)
1879
+ 0 1
1880
+
1881
+ 6 7
1882
+ !~~~~~~~!
1883
+ ! base !
1884
+ !~~~~~~~!
1885
+ 4 5
1886
+
1887
+ Args:
1888
+ names (list): Generic name of the properties, will have a
1889
+ number added, e.g. X0, X1, etc.
1890
+
1891
+ Example::
1892
+
1893
+ >>> import xtgeo
1894
+ >>> grid = xtgeo.create_box_grid((2,2,2))
1895
+ >>> gps = grid.get_xyz_corners() # list of 24 grid properties
1896
+ >>> len(gps)
1897
+ 24
1898
+ >>> gps[0].values.tolist()
1899
+ [[[0.0, 0.0], ... [[1.0, 1.0], [1.0, 1.0]]]
1900
+
1901
+
1902
+ Raises:
1903
+ RunetimeError if corners has wrong spesification
1904
+ """
1905
+ # return the 24 objects in a long tuple (x1, y1, z1, ... x8, y8, z8)
1906
+ return _grid_etc1.get_xyz_corners(self, names=names)
1907
+
1908
+ def get_layer_slice(
1909
+ self, layer: int, top: bool = True, activeonly: bool = True
1910
+ ) -> tuple[np.ndarray, np.ndarray]:
1911
+ """Get numpy arrays for cell coordinates e.g. for plotting.
1912
+
1913
+ In each cell there are 5 XY pairs, making a closed polygon as illustrated here:
1914
+
1915
+ XY3 < XY2
1916
+ !~~~~~~~!
1917
+ ! ! ^
1918
+ !~~~~~~~!
1919
+ XY0 -> XY1
1920
+ XY4
1921
+
1922
+ Note that cell ordering is C ordering (row is fastest)
1923
+
1924
+ Args:
1925
+ layer (int): K layer, starting with 1 as topmost
1926
+ tip (bool): If True use top of cell, otherwise use base
1927
+ activeonly (bool): If True, only return active cells
1928
+
1929
+ Returns:
1930
+ layerarray (np): [[[X0, Y0], [X1, Y1]...[X4, Y4]], [[..][..]]...]
1931
+ icarray (np): On the form [ic1, ic2, ...] where ic is cell count (C order)
1932
+
1933
+ Example:
1934
+
1935
+ Return two arrays forr cell corner for bottom layer::
1936
+
1937
+ grd = xtgeo.grid_from_file(REEKFILE)
1938
+
1939
+ parr, ibarr = grd.get_layer_slice(grd.nlay, top=False)
1940
+
1941
+ .. versionadded:: 2.3
1942
+ """
1943
+ return _grid_etc1.get_layer_slice(self, layer, top=top, activeonly=activeonly)
1944
+
1945
+ def get_geometrics(
1946
+ self,
1947
+ allcells: bool = False,
1948
+ cellcenter: bool = True,
1949
+ return_dict: bool = False,
1950
+ _ver: Literal[1, 2] = 1,
1951
+ ) -> dict | tuple:
1952
+ """Get a list of grid geometrics such as origin, min, max, etc.
1953
+
1954
+ This returns a tuple: (xori, yori, zori, xmin, xmax, ymin, ymax, zmin,
1955
+ zmax, avg_rotation, avg_dx, avg_dy, avg_dz, grid_regularity_flag)
1956
+
1957
+ If a dictionary is returned, the keys are as in the list above.
1958
+
1959
+ Args:
1960
+ allcells (bool): If True, return also for inactive cells
1961
+ cellcenter (bool): If True, use cell center, otherwise corner
1962
+ coords
1963
+ return_dict (bool): If True, return a dictionary instead of a
1964
+ list, which is usually more convinient.
1965
+ _ver (int): Private option; only for developer!
1966
+
1967
+ Raises: Nothing
1968
+
1969
+ Example::
1970
+
1971
+ >>> mygrid = grid_from_file(reek_dir + "REEK.EGRID")
1972
+ >>> gstuff = mygrid.get_geometrics(return_dict=True)
1973
+ >>> print(f"X min/max is {gstuff['xmin']:.2f} {gstuff['xmax']:.2f}")
1974
+ X min/max is 456620.79 467106.33
1975
+
1976
+ """
1977
+ # TODO(JB): _grid_etc1.get_geometrics(False, False, True): Looks like it will
1978
+ # fail due to glist and gkeys will be out of sync (lengths will be differnt)
1979
+ return _grid_etc1.get_geometrics(
1980
+ self,
1981
+ allcells=allcells,
1982
+ cellcenter=cellcenter,
1983
+ return_dict=return_dict,
1984
+ _ver=_ver,
1985
+ )
1986
+
1987
+ def get_adjacent_cells(
1988
+ self,
1989
+ prop: GridProperty,
1990
+ val1: int,
1991
+ val2: int,
1992
+ activeonly: bool = True,
1993
+ ) -> GridProperty:
1994
+ """Get a discrete property which reports val1 properties vs neighbouring val2.
1995
+
1996
+ The result will be a new gridproperty, which in general has value 0
1997
+ but 1 if criteria is met, and 2 if criteria is met but cells are
1998
+ faulted.
1999
+
2000
+ Args:
2001
+ prop (xtgeo.GridProperty): A discrete grid property, e.g region
2002
+ val1 (int): Primary value to evaluate
2003
+ val2 (int): Neighbourung value
2004
+ activeonly (bool): If True, do not look at inactive cells
2005
+
2006
+ Raises: Nothing
2007
+
2008
+ """
2009
+ return _grid_etc1.get_adjacent_cells(
2010
+ self, prop, val1, val2, activeonly=activeonly
2011
+ )
2012
+
2013
+ def get_gridquality_properties(self) -> GridProperties:
2014
+ """Return a GridProperties() instance with grid quality measures.
2015
+
2016
+ These measures are currently:
2017
+
2018
+ * minangle_topbase (degrees) - minimum angle of top and base
2019
+ * maxangle_topbase (degrees) - maximum angle of top and base
2020
+ * minangle_topbase_proj (degrees) min angle projected (bird view)
2021
+ * maxangle_topbase_proj (degrees) max angle projected (bird view)
2022
+ * minangle_sides (degress) minimum angle, all side surfaces
2023
+ * maxangle_sides (degress) maximum angle, all side surfaces
2024
+ * collapsed (int) Integer, 1 of one or more corners are collpased in Z
2025
+ * faulted (int) Integer, 1 if cell is faulted (one or more neighbours offset)
2026
+ * negative_thickness (int) Integer, 1 if cell has negative thickness
2027
+ * concave_proj (int) 1 if cell is concave seen from projected bird view
2028
+
2029
+ Example::
2030
+
2031
+ # store grid quality measures in RMS
2032
+ gprops = grd.gridquality()
2033
+ for gprop in gprops:
2034
+ gprop.to_roxar(project, "MyGrid", gprop.name)
2035
+
2036
+
2037
+ """
2038
+ return _grid_etc1.get_gridquality_properties(self)
2039
+
2040
+ # =========================================================================
2041
+ # Some more special operations that changes the grid or actnum
2042
+ # =========================================================================
2043
+ def activate_all(self) -> None:
2044
+ """Activate all cells in the grid, by manipulating ACTNUM."""
2045
+ self._actnumsv = np.ones(self.dimensions, dtype=np.int32)
2046
+
2047
+ if self._xtgformat == 1:
2048
+ self._actnumsv = self._actnumsv.flatten()
2049
+
2050
+ self._tmp = {}
2051
+
2052
+ def inactivate_by_dz(self, threshold: float) -> None:
2053
+ """Inactivate cells thinner than a given threshold."""
2054
+ _grid_etc1.inactivate_by_dz(self, threshold)
2055
+ self._tmp = {}
2056
+
2057
+ def inactivate_inside(
2058
+ self,
2059
+ poly: Polygons,
2060
+ layer_range: tuple[int, int] | None = None,
2061
+ inside: bool = True,
2062
+ force_close: bool = False,
2063
+ ) -> None:
2064
+ """Inacativate grid inside a polygon.
2065
+
2066
+ The Polygons instance may consist of several polygons. If a polygon
2067
+ is open, then the flag force_close will close any that are not open
2068
+ when doing the operations in the grid.
2069
+
2070
+ Args:
2071
+ poly(Polygons): A polygons object
2072
+ layer_range (tuple): A tuple of two ints, upper layer = 1, e.g.
2073
+ (1, 14). Note that base layer count is 1 (not zero)
2074
+ inside (bool): True if remove inside polygon
2075
+ force_close (bool): If True then force polygons to be closed.
2076
+
2077
+ Raises:
2078
+ RuntimeError: If a problems with one or more polygons.
2079
+ ValueError: If Polygon is not a XTGeo object
2080
+ """
2081
+ _grid_etc1.inactivate_inside(
2082
+ self, poly, layer_range=layer_range, inside=inside, force_close=force_close
2083
+ )
2084
+ self._tmp = {}
2085
+
2086
+ def inactivate_outside(
2087
+ self,
2088
+ poly: Polygons,
2089
+ layer_range: tuple[int, int] | None = None,
2090
+ force_close: bool = False,
2091
+ ) -> None:
2092
+ """Inacativate grid outside a polygon."""
2093
+ self.inactivate_inside(
2094
+ poly, layer_range=layer_range, inside=False, force_close=force_close
2095
+ )
2096
+ self._tmp = {}
2097
+
2098
+ def collapse_inactive_cells(self) -> None:
2099
+ """Collapse inactive layers where, for I J with other active cells."""
2100
+ _grid_etc1.collapse_inactive_cells(self)
2101
+ self._tmp = {}
2102
+
2103
+ def crop(
2104
+ self,
2105
+ colcrop: tuple[int, int],
2106
+ rowcrop: tuple[int, int],
2107
+ laycrop: tuple[int, int],
2108
+ props: Literal["all"] | list[GridProperty] | None = None,
2109
+ ) -> None:
2110
+ """Reduce the grid size by cropping.
2111
+
2112
+ The new grid will get new dimensions.
2113
+
2114
+ If props is "all" then all properties assosiated (linked) to then
2115
+ grid are also cropped, and the instances are updated.
2116
+
2117
+ Args:
2118
+ colcrop (tuple): A tuple on the form (i1, i2)
2119
+ where 1 represents start number, and 2 represent end. The range
2120
+ is inclusive for both ends, and the number start index is 1 based.
2121
+ rowcrop (tuple): A tuple on the form (j1, j2)
2122
+ laycrop (tuple): A tuple on the form (k1, k2)
2123
+ props (list or str): None is default, while properties can be listed.
2124
+ If "all", then all GridProperty objects which are linked to the
2125
+ Grid instance are updated.
2126
+
2127
+ Returns:
2128
+ The instance is updated (cropped)
2129
+
2130
+ Example::
2131
+
2132
+ >>> import xtgeo
2133
+ >>> mygrid = xtgeo.grid_from_file(reek_dir + "/REEK.EGRID")
2134
+ >>> mygrid.crop((3, 6), (4, 20), (1, 10))
2135
+ >>> mygrid.to_file(outdir + "/gf_reduced.roff")
2136
+
2137
+ """
2138
+ _grid_etc1.crop(self, (colcrop, rowcrop, laycrop), props=props)
2139
+ self._tmp = {}
2140
+
2141
+ def reduce_to_one_layer(self) -> None:
2142
+ """Reduce the grid to one single layer.
2143
+
2144
+ Example::
2145
+
2146
+ >>> import xtgeo
2147
+ >>> grid = xtgeo.grid_from_file(reek_dir + "/REEK.EGRID")
2148
+ >>> grid.nlay
2149
+ 14
2150
+ >>> grid.reduce_to_one_layer()
2151
+ >>> grid.nlay
2152
+ 1
2153
+
2154
+ """
2155
+ _grid_etc1.reduce_to_one_layer(self)
2156
+ self._tmp = {}
2157
+
2158
+ def translate_coordinates(
2159
+ self,
2160
+ translate: tuple[float, float, float] = (0.0, 0.0, 0.0),
2161
+ flip: tuple[int, int, int] = (1, 1, 1),
2162
+ ) -> None:
2163
+ """Translate (move) and/or flip grid coordinates in 3D.
2164
+
2165
+ By 'flip' here, it means that the full coordinate array are multiplied
2166
+ with -1.
2167
+
2168
+ Args:
2169
+ translate (tuple): Translation distance in X, Y, Z coordinates
2170
+ flip (tuple): Flip array. The flip values must be 1 or -1.
2171
+
2172
+ Raises:
2173
+ RuntimeError: If translation goes wrong for unknown reasons
2174
+ """
2175
+ _grid_etc1.translate_coordinates(self, translate=translate, flip=flip)
2176
+ self._tmp = {}
2177
+
2178
+ def reverse_row_axis(
2179
+ self, ijk_handedness: Literal["left", "right"] | None = None
2180
+ ) -> None:
2181
+ """Reverse the row axis (J indices).
2182
+
2183
+ This means that IJK system will switched between a left vs right handed system.
2184
+ It is here (by using ijk_handedness key), possible to set a wanted stated.
2185
+
2186
+ Note that properties that are assosiated with the grid (through the
2187
+ :py:attr:`~gridprops` or :py:attr:`~props` attribute) will also be
2188
+ reversed (which is desirable).
2189
+
2190
+ Args:
2191
+ ijk_handedness (str): If set to "right" or "left", do only reverse rows if
2192
+ handedness is not already achieved.
2193
+
2194
+ Example::
2195
+
2196
+ grd = xtgeo.grid_from_file("somefile.roff")
2197
+ prop1 = xtgeo.gridproperty_from_file("somepropfile1.roff")
2198
+ prop2 = xtgeo.gridproperty_from_file("somepropfile2.roff")
2199
+
2200
+ grd.props = [prop1, prop2]
2201
+
2202
+ # secure that the grid geometry is IJK right-handed
2203
+ grd.reverse_row_axis(ijk_handedness="right")
2204
+
2205
+ .. versionadded:: 2.5
2206
+
2207
+ """
2208
+ _grid_etc1.reverse_row_axis(self, ijk_handedness=ijk_handedness)
2209
+ self._tmp = {}
2210
+
2211
+ def make_zconsistent(self, zsep: float | int = 1e-5) -> None:
2212
+ """Make the 3D grid consistent in Z, by a minimal gap (zsep).
2213
+
2214
+ Args:
2215
+ zsep (float): Minimum gap
2216
+ """
2217
+ _grid_etc1.make_zconsistent(self, zsep)
2218
+ self._tmp = {}
2219
+
2220
+ def convert_to_hybrid(
2221
+ self,
2222
+ nhdiv: int = 10,
2223
+ toplevel: float = 1000.0,
2224
+ bottomlevel: float = 1100.0,
2225
+ region: GridProperty | None = None,
2226
+ region_number: int | None = None,
2227
+ ) -> None:
2228
+ """Convert to hybrid grid, either globally or in a selected region.
2229
+
2230
+ This function will convert the internal structure in the corner point grid,
2231
+ so that the cells between two levels ``toplevel`` and ``bottomlevel`` become
2232
+ horizontal, which can be useful in flow simulators when e.g. liquid
2233
+ contact movements are dominating. See example on `usage in the Troll field`_.
2234
+
2235
+ Note that the resulting hybrid will have an increased number of layers.
2236
+ If the initial grid has N layers, and the number of horizontal layers
2237
+ is NHDIV, then the result grid will have N * 2 + NHDIV layers.
2238
+
2239
+ .. image:: images/hybridgrid2.jpg
2240
+ :width: 600
2241
+ :align: center
2242
+
2243
+ Args:
2244
+ nhdiv (int): Number of hybrid layers.
2245
+ toplevel (float): Top of hybrid grid.
2246
+ bottomlevel (float): Base of hybrid grid.
2247
+ region (GridProperty, optional): Region property (if needed).
2248
+ region_number (int): Which region to apply hybrid grid in if region.
2249
+
2250
+ Example:
2251
+ Create a hybridgrid from file, based on a GRDECL file (no region)::
2252
+
2253
+ import xtgeo
2254
+ grd = xtgeo.grid_from_file("simgrid.grdecl", fformat="grdecl")
2255
+ grd.convert_to_hybrid(nhdiv=12, toplevel=2200, bottomlevel=2250)
2256
+ # save in binary GRDECL fmt:
2257
+ grd.to_file("simgrid_hybrid.bgrdecl", fformat="bgrdecl")
2258
+
2259
+ See Also:
2260
+ :ref:`hybrid` example.
2261
+
2262
+ .. _usage in the Troll field: https://doi.org/10.2118/148023-MS
2263
+
2264
+ """
2265
+ _grid_hybrid.make_hybridgrid(
2266
+ self,
2267
+ nhdiv=nhdiv,
2268
+ toplevel=toplevel,
2269
+ bottomlevel=bottomlevel,
2270
+ region=region,
2271
+ region_number=region_number,
2272
+ )
2273
+ self._tmp = {}
2274
+
2275
+ def refine_vertically(
2276
+ self,
2277
+ rfactor: int | dict | None,
2278
+ zoneprop: GridProperty | None = None,
2279
+ ) -> None:
2280
+ """Refine vertically, proportionally.
2281
+
2282
+ The rfactor can be a scalar or a dictionary.
2283
+
2284
+ If rfactor is a dict and zoneprop is None, then the current
2285
+ subgrids array is used. If zoneprop is defined, the
2286
+ current subgrid index will be redefined for the case. A warning will
2287
+ be issued if subgrids are defined, but the give zone
2288
+ property is inconsistent with this.
2289
+
2290
+ Also, if a zoneprop is defined but no current subgrids in the grid,
2291
+ then subgrids will be added to the grid, if more than 1 subgrid.
2292
+
2293
+ Args:
2294
+ self (object): A grid XTGeo object
2295
+ rfactor (scalar or dict): Refinement factor, if dict, then the
2296
+ dictionary must be consistent with self.subgrids if this is
2297
+ present.
2298
+ zoneprop (GridProperty): Zone property; must be defined if rfactor
2299
+ is a dict
2300
+
2301
+ Returns:
2302
+ ValueError: if..
2303
+ RuntimeError: if mismatch in dimensions for rfactor and zoneprop
2304
+
2305
+
2306
+ Examples::
2307
+
2308
+ # refine vertically all by factor 3
2309
+
2310
+ grd.refine_vertically(3)
2311
+
2312
+ # refine by using a dictionary; note that subgrids must exist!
2313
+ # and that subgrids that are not mentioned will have value 1
2314
+ # in refinement (1 is meaning no refinement)
2315
+
2316
+ grd.refine_vertically({1: 3, 2: 4, 4: 1})
2317
+
2318
+ # refine by using a a dictionary and a zonelog. If subgrids exists
2319
+ # but are inconsistent with the zonelog; the current subgrids will
2320
+ # be redefined, and a warning will be issued! Note also that ranges
2321
+ # in the dictionary rfactor and the zone property must be aligned.
2322
+
2323
+ grd.refine_vertically({1: 3, 2: 4, 4: 0}, zoneprop=myzone)
2324
+
2325
+ """
2326
+ _grid_refine.refine_vertically(self, rfactor, zoneprop=zoneprop)
2327
+ self._tmp = {}
2328
+
2329
+ def report_zone_mismatch(
2330
+ self,
2331
+ well: Well | None = None,
2332
+ zonelogname: str = "ZONELOG",
2333
+ zoneprop: GridProperty | None = None,
2334
+ zonelogrange: tuple[int, int] = (0, 9999),
2335
+ zonelogshift: int = 0,
2336
+ depthrange: tuple | None = None,
2337
+ perflogname: str | None = None,
2338
+ perflogrange: tuple[int, int] = (1, 9999),
2339
+ filterlogname: str | None = None,
2340
+ filterlogrange: tuple[float, float] = (1e-32, 9999.0),
2341
+ resultformat: Literal[1, 2] = 1,
2342
+ ) -> tuple | dict | None:
2343
+ """Reports mismatch between wells and a zone.
2344
+
2345
+ Approaches on matching:
2346
+ 1. Use the well zonelog as basis, and compare sampled zone with that
2347
+ interval. This means that zone cells outside well range will not be
2348
+ counted
2349
+ 2. Compare intervals with wellzonation in range or grid zonations in
2350
+ range. This gives a wider comparison, and will capture cases
2351
+ where grid zonations is outside well zonation
2352
+
2353
+ .. image:: images/zone-well-mismatch-plain.svg
2354
+ :width: 200
2355
+ :align: center
2356
+
2357
+ Note if `zonelogname` and/or `filterlogname` and/or `perflogname` is given,
2358
+ and such log(s) are not present, then this function will return ``None``.
2359
+
2360
+ Args:
2361
+ well (Well): a XTGeo well object
2362
+ zonelogname (str): Name of the zone logger
2363
+ zoneprop (GridProperty): Grid property instance to use for
2364
+ zonation
2365
+ zonelogrange (tuple): zone log range, from - to (inclusive)
2366
+ zonelogshift (int): Deviation (numerical shift) between grid and zonelog,
2367
+ e.g. if Zone property starts with 1 and this corresponds to a zonelog
2368
+ index of 3 in the well, the shift shall be -2.
2369
+ depthrange (tuple): Interval for search in TVD depth, to speed up
2370
+ perflogname (str): Name of perforation log to filter on (> 0 default).
2371
+ perflogrange (tuple): Range of values where perforations are present.
2372
+ filterlogname (str): General filter, work as perflog, filter on values > 0
2373
+ filterlogrange (tuple): Range of values where filter shall be present.
2374
+ resultformat (int): If 1, consider the zonelogrange in the well as
2375
+ basis for match ratio, return (percent, match count, total count).
2376
+ If 2 then a dictionary is returned with various result members
2377
+
2378
+ Returns:
2379
+ res (tuple or dict): report dependent on `resultformat`
2380
+ * A tuple with 3 members:
2381
+ (match_as_percent, number of matches, total count) approach 1
2382
+ * A dictionary with keys:
2383
+ * MATCH1 - match as percent, approach 1
2384
+ * MCOUNT1 - number of match samples approach 1
2385
+ * TCOUNT1 - total number of samples approach 1
2386
+ * MATCH2 - match as percent, approach 2
2387
+ * MCOUNT2 - a.a for option 2
2388
+ * TCOUNT2 - a.a. for option 2
2389
+ * WELLINTV - a Well() instance for the actual interval
2390
+ * None, if perflogname or zonelogname of filtername is given, but
2391
+ the log does not exists for the well
2392
+
2393
+ Example::
2394
+
2395
+ g1 = xtgeo.grid_from_file("gullfaks2.roff")
2396
+
2397
+ z = xtgeo.gridproperty_from_file(gullfaks2_zone.roff", name="Zone")
2398
+
2399
+ w2 = xtgeo.well_from_file("34_10-1.w", zonelogname="Zonelog")
2400
+
2401
+ w3 = xtgeo.well_from_file("34_10-B-21_B.w", zonelogname="Zonelog"))
2402
+
2403
+ wells = [w2, w3]
2404
+
2405
+ for w in wells:
2406
+ response = g1.report_zone_mismatch(
2407
+ well=w, zonelogname="ZONELOG", zoneprop=z,
2408
+ zonelogrange=(0, 19), depthrange=(1700, 9999))
2409
+
2410
+ print(response)
2411
+
2412
+ .. versionchanged:: 2.8 Added several new keys and better precision in result
2413
+ .. versionchanged:: 2.11 Added ``perflogrange`` and ``filterlogrange``
2414
+ """
2415
+ return _grid_wellzone.report_zone_mismatch(
2416
+ self,
2417
+ well=well,
2418
+ zonelogname=zonelogname,
2419
+ zoneprop=zoneprop,
2420
+ zonelogrange=zonelogrange,
2421
+ zonelogshift=zonelogshift,
2422
+ depthrange=depthrange,
2423
+ perflogname=perflogname,
2424
+ perflogrange=perflogrange,
2425
+ filterlogname=filterlogname,
2426
+ filterlogrange=filterlogrange,
2427
+ resultformat=resultformat,
2428
+ )
2429
+
2430
+ # ==================================================================================
2431
+ # Extract a fence/randomline by sampling, ready for plotting with e.g. matplotlib
2432
+ # ==================================================================================
2433
+ def get_randomline(
2434
+ self,
2435
+ fencespec: np.ndarray | Polygons,
2436
+ prop: str | GridProperty,
2437
+ zmin: float | None = None,
2438
+ zmax: float | None = None,
2439
+ zincrement: float = 1.0,
2440
+ hincrement: float | None = None,
2441
+ atleast: int = 5,
2442
+ nextend: int = 2,
2443
+ ) -> tuple[float, float, float, float, np.ndarray]:
2444
+ """Get a sampled randomline from a fence spesification.
2445
+
2446
+ This randomline will be a 2D numpy with depth on the vertical
2447
+ axis, and length along as horizontal axis. Undefined values will have
2448
+ the np.nan value.
2449
+
2450
+ The input fencespec is either a 2D numpy where each row is X, Y, Z, HLEN,
2451
+ where X, Y are UTM coordinates, Z is depth/time, and HLEN is a
2452
+ length along the fence, or a Polygons instance.
2453
+
2454
+ If input fencspec is a numpy 2D, it is important that the HLEN array
2455
+ has a constant increment and ideally a sampling that is less than the
2456
+ Grid resolution. If a Polygons() instance, this will be automated if
2457
+ hincrement is None.
2458
+
2459
+ Args:
2460
+ fencespec (:obj:`~numpy.ndarray` or :class:`~xtgeo.xyz.polygons.Polygons`):
2461
+ 2D numpy with X, Y, Z, HLEN as rows or a xtgeo Polygons() object.
2462
+ prop (GridProperty or str): The grid property object, or name, which shall
2463
+ be plotted.
2464
+ zmin (float): Minimum Z (default is Grid Z minima/origin)
2465
+ zmax (float): Maximum Z (default is Grid Z maximum)
2466
+ zincrement (float): Sampling vertically, default is 1.0
2467
+ hincrement (float): Resampling horizontally. This applies only
2468
+ if the fencespec is a Polygons() instance. If None (default),
2469
+ the distance will be deduced automatically.
2470
+ atleast (int): Minimum number of horizontal samples This applies
2471
+ only if the fencespec is a Polygons() instance.
2472
+ nextend (int): Extend with nextend * hincrement in both ends.
2473
+ This applies only if the fencespec is a Polygons() instance.
2474
+
2475
+ Returns:
2476
+ A tuple: (hmin, hmax, vmin, vmax, ndarray2d)
2477
+
2478
+ Raises:
2479
+ ValueError: Input fence is not according to spec.
2480
+
2481
+ Example::
2482
+
2483
+ mygrid = xtgeo.grid_from_file("somegrid.roff")
2484
+ poro = xtgeo.gridproperty_from_file("someporo.roff")
2485
+ mywell = xtgeo.well_from_file("somewell.rmswell")
2486
+ fence = mywell.get_fence_polyline(sampling=5, tvdmin=1750, asnumpy=True)
2487
+ (hmin, hmax, vmin, vmax, arr) = mygrid.get_randomline(
2488
+ fence, poro, zmin=1750, zmax=1850, zincrement=0.5,
2489
+ )
2490
+ # matplotlib ...
2491
+ plt.imshow(arr, cmap="rainbow", extent=(hmin1, hmax1, vmax1, vmin1))
2492
+
2493
+ .. versionadded:: 2.1
2494
+
2495
+ .. seealso::
2496
+ Class :class:`~xtgeo.xyz.polygons.Polygons`
2497
+ The method :meth:`~xtgeo.xyz.polygons.Polygons.get_fence()` which can be
2498
+ used to pregenerate `fencespec`
2499
+
2500
+ """
2501
+ if not isinstance(fencespec, (np.ndarray, xtgeo.Polygons)):
2502
+ raise ValueError("fencespec must be a numpy or a Polygons() object")
2503
+ logger.info("Getting randomline...")
2504
+
2505
+ res = _grid3d_fence.get_randomline(
2506
+ self,
2507
+ fencespec,
2508
+ prop,
2509
+ zmin=zmin,
2510
+ zmax=zmax,
2511
+ zincrement=zincrement,
2512
+ hincrement=hincrement,
2513
+ atleast=atleast,
2514
+ nextend=nextend,
2515
+ )
2516
+ logger.info("Getting randomline... DONE")
2517
+ return res
2518
+
2519
+ # ----------------------------------------------------------------------------------
2520
+ # Special private functions; these may only live for while
2521
+ # ----------------------------------------------------------------------------------
2522
+
2523
+ def _convert_xtgformat2to1(self) -> None:
2524
+ """Convert arrays from new structure xtgformat=2 to legacy xtgformat=1."""
2525
+ _grid_etc1._convert_xtgformat2to1(self)
2526
+
2527
+ def _convert_xtgformat1to2(self) -> None:
2528
+ """Convert arrays from old structure xtgformat=1 to new xtgformat=2."""
2529
+ _grid_etc1._convert_xtgformat1to2(self)
2530
+
2531
+ def _xtgformat1(self) -> None:
2532
+ """Shortform... arrays from new structure xtgformat=2 to legacy xtgformat=1."""
2533
+ self._convert_xtgformat2to1()
2534
+
2535
+ def _xtgformat2(self) -> None:
2536
+ """Shortform... arrays from old structure xtgformat=1 to new xtgformat=2."""
2537
+ self._convert_xtgformat1to2()