├── src └── subsurface │ ├── __init__.py │ ├── multphaseflow │ ├── __init__.py │ ├── misc │ │ ├── __init__.py │ │ ├── system_tools │ │ │ ├── __init__.py │ │ │ └── environ_var.py │ │ ├── ecl_common.py │ │ └── grid │ │ │ ├── __init__.py │ │ │ ├── unstruct.py │ │ │ ├── sector.py │ │ │ └── cornerpoint.py │ └── opm.py │ └── rockphysics │ ├── __init__.py │ ├── standardrp.py │ └── softsandrp.py ├── Example ├── README.md ├── README_11_0.png ├── README_12_0.png ├── README_13_0.png ├── README_14_0.png └── 3WELL.mako ├── tests └── test_import.py ├── pyproject.toml ├── .gitignore ├── README.md └── LICENSE /src/subsurface/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/subsurface/multphaseflow/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Example/README.md: -------------------------------------------------------------------------------- 1 | Here lives the example [notebook](README.ipynb) -------------------------------------------------------------------------------- /src/subsurface/multphaseflow/misc/__init__.py: -------------------------------------------------------------------------------- 1 | """More tools.""" 2 | -------------------------------------------------------------------------------- /src/subsurface/rockphysics/__init__.py: -------------------------------------------------------------------------------- 1 | """Compute elastic properties.""" 2 | -------------------------------------------------------------------------------- /src/subsurface/multphaseflow/misc/system_tools/__init__.py: -------------------------------------------------------------------------------- 1 | """Multiprocessing and environment management.""" 2 | -------------------------------------------------------------------------------- /Example/README_11_0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Python-Ensemble-Toolbox/SimulatorWrap/main/Example/README_11_0.png -------------------------------------------------------------------------------- /Example/README_12_0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Python-Ensemble-Toolbox/SimulatorWrap/main/Example/README_12_0.png -------------------------------------------------------------------------------- /Example/README_13_0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Python-Ensemble-Toolbox/SimulatorWrap/main/Example/README_13_0.png -------------------------------------------------------------------------------- /Example/README_14_0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Python-Ensemble-Toolbox/SimulatorWrap/main/Example/README_14_0.png -------------------------------------------------------------------------------- /tests/test_import.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | 4 | class MyTestCase(unittest.TestCase): 5 | def test_something(self): 6 | self.assertEqual(True, True) # add assertion here 7 | 8 | 9 | if __name__ == '__main__': 10 | unittest.main() 11 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["setuptools>=61.0"] 3 | build-backend = "setuptools.build_meta" 4 | 5 | [project] 6 | name = "subsurface" 7 | version = "0.0.1" 8 | authors = [ 9 | { name="Kristian Fossum", email="krfo@norceresearch.no" }, 10 | ] 11 | description = "A python package containing some usefull simulator wrappers." 12 | readme = "README.md" 13 | requires-python = ">=3.8" 14 | license = {file = "LICENSE"} 15 | dependencies = ["numpy", "scipy","mako","mat73","scikit-learn" 16 | ] 17 | 18 | [project.urls] 19 | Homepage = "https://github.com/Python-Ensemble-Toolbox/SimulatorWrap" 20 | Issues = "https://github.com/Python-Ensemble-Toolbox/SimulatorWrap/ issues" -------------------------------------------------------------------------------- /src/subsurface/multphaseflow/misc/ecl_common.py: -------------------------------------------------------------------------------- 1 | """Common definitions for all import filters 2 | 3 | >>> from .ecl_common import Phase, Prop 4 | """ 5 | 6 | 7 | # Enumeration of the phases that can exist in a simulation. 8 | # 9 | # The names are abbreviations and should really be called oleic, aqueous and 10 | # gaseous, if we wanted to be correct and type more. 11 | # 12 | # The value that is returned is the Eclipse moniker, for backwards 13 | # compatibility with code that uses this directly. 14 | Phase = type('Phase', (object,), { 15 | 'oil': 'OIL', 16 | 'wat': 'WAT', 17 | 'gas': 'GAS', 18 | }) 19 | 20 | 21 | # Properties that can be queried from an output file. 22 | # 23 | # The property forms the first part of a "selector", which is a tuple 24 | # containing the necessary information to setup the name of the property 25 | # to read. 26 | Prop = type('Prop', (object,), { 27 | 'pres': 'P', # pressure 28 | 'sat': 'S', # saturation 29 | 'mole': 'x', # mole fraction 30 | 'dens': 'D', # density 31 | 'temp': 'T', # temperature 32 | 'leak': 'L', # leaky well 33 | }) 34 | -------------------------------------------------------------------------------- /src/subsurface/multphaseflow/misc/grid/__init__.py: -------------------------------------------------------------------------------- 1 | """\ 2 | Generic read module which determines format from extension. 3 | """ 4 | import logging 5 | import os.path as pth 6 | 7 | 8 | # module specific log; add a null handler so that we won't get an 9 | # error if the main program hasn't set up a log 10 | log = logging.getLogger(__name__) # pylint: disable=invalid-name 11 | log.addHandler(logging.NullHandler()) 12 | 13 | 14 | def read_grid(filename, cache_dir=None): 15 | """\ 16 | :param filename: Name of the grid file to read, including path 17 | :type filename: str 18 | :param cache_dir: Path to a directory where a cache of the grid 19 | may be stored to ensure faster read next time. 20 | :type cache_dir: str 21 | """ 22 | # allow shortcut to home directories to be used in paths 23 | fullname = pth.expanduser(filename) 24 | 25 | # split the filename into directory, name and extension 26 | base, ext = pth.splitext(fullname) 27 | 28 | if ext.lower() == '.grdecl': 29 | from misc import grdecl as grdecl 30 | log.info("Reading corner point grid from \"%s\"", fullname) 31 | grid = grdecl.read(fullname) 32 | 33 | elif ext.lower() == '.egrid': 34 | # in case we only have a simulation available, with the binary 35 | # output from the restart, we can read this directly 36 | from misc import ecl as ecl 37 | log.info("Reading binary Eclipse grid from \"%s\"", fullname) 38 | egrid = ecl.EclipseGrid(base) 39 | grid = {'DIMENS': egrid.shape[::-1], 40 | 'COORD': egrid.coord, 41 | 'ZCORN': egrid.zcorn, 42 | 'ACTNUM': egrid.actnum} 43 | 44 | elif ext.lower() == '.pickle': 45 | # direct import of pickled file (should not do this, prefer to read 46 | # it through a cache directory 47 | import pickle 48 | log.info("Reading binary grid dump from \"%s\"", fullname) 49 | with open(fullname, 'rb') as f: 50 | grid = pickle.load(f) 51 | 52 | else: 53 | raise ValueError( 54 | "File format with extension \"{0}\" is unknown".format(ext)) 55 | 56 | return grid 57 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/latest/usage/project/#working-with-version-control 110 | .pdm.toml 111 | .pdm-python 112 | .pdm-build/ 113 | 114 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 115 | __pypackages__/ 116 | 117 | # Celery stuff 118 | celerybeat-schedule 119 | celerybeat.pid 120 | 121 | # SageMath parsed files 122 | *.sage.py 123 | 124 | # Environments 125 | .env 126 | .venv 127 | env/ 128 | venv/ 129 | ENV/ 130 | env.bak/ 131 | venv.bak/ 132 | 133 | # Spyder project settings 134 | .spyderproject 135 | .spyproject 136 | 137 | # Rope project settings 138 | .ropeproject 139 | 140 | # mkdocs documentation 141 | /site 142 | 143 | # mypy 144 | .mypy_cache/ 145 | .dmypy.json 146 | dmypy.json 147 | 148 | # Pyre type checker 149 | .pyre/ 150 | 151 | # pytype static type analyzer 152 | .pytype/ 153 | 154 | # Cython debug symbols 155 | cython_debug/ 156 | 157 | # PyCharm 158 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 159 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 160 | # and can be added to the global gitignore or merged into this file. For a more nuclear 161 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 162 | #.idea/ 163 | -------------------------------------------------------------------------------- /src/subsurface/multphaseflow/misc/grid/unstruct.py: -------------------------------------------------------------------------------- 1 | """\ 2 | Convert cornerpoint grids to unstructured grids 3 | 4 | :example: 5 | import pyresito.grid.unstruct as us 6 | import pyresito.io.grdecl as grdecl 7 | 8 | g = grdecl.read('~/proj/cmgtools/bld/overlap.grdecl') 9 | """ 10 | # pylint: disable=too-few-public-methods, multiple-statements 11 | import numpy as np 12 | 13 | 14 | class Ridge (object): 15 | """A ridge consists of two points, anchored in each their pillar. We only 16 | need to store the z-values, because the x- and y- values are determined by 17 | the pillar themselves. 18 | """ 19 | __slots__ = ['left', 'right'] 20 | 21 | def __init__(self, left, right): 22 | self.left = left 23 | self.right = right 24 | 25 | def is_not_below(self, other): 26 | """Weak ordering of ridges based on vertical placement. 27 | 28 | :param other: Ridge to be compared to this object. 29 | :type other: :class:`Ridge` 30 | :returns: True if no point on self is below any on the other, 31 | None if the ridges cross, and False if there is a point 32 | on the other ridge that is above any on self. 33 | :rtype: Boolean 34 | """ 35 | # test each side separately. if self is at the same level as other, 36 | # this should count positively towards the test (i.e. it is regarded 37 | # as "at least as high"), so use less-or-equal. 38 | left_above = other.left <= self.left 39 | right_above = other.right <= self.right 40 | 41 | # if both sides are at least as high, then self is regarded as at 42 | # least as high as other, and vice versa. if one side is lower and 43 | # one side is higher, then the ridges cross. 44 | if left_above: 45 | return True if right_above else None 46 | else: 47 | return None if right_above else False 48 | 49 | 50 | class Face (object): 51 | """A (vertical) face consists of two ridges, because all of the faces in a 52 | hexahedron can be seen as (possibly degenerate) quadrilaterals. 53 | """ 54 | __slots__ = ['top', 'btm'] 55 | 56 | def __init__(self, top, btm): 57 | self.top = top 58 | self.btm = btm 59 | 60 | def is_above(self, other): 61 | """Weak ordering of faces based on vertical placement. 62 | 63 | :param other: Face to be compared to this object. 64 | :type other: :class:`Face` 65 | :returns: True if all points in face self is above all points in 66 | face other, False otherwise 67 | :rtype: Boolean 68 | """ 69 | # if the bottom of self is aligned with the top of other, then the 70 | # face itself is considered to be above. since the ridge test also 71 | # has an indeterminate result, we test explicitly like this 72 | return True if self.btm.is_not_below(other.top) else False 73 | 74 | 75 | def conv(grid): 76 | """Convert a cornerpoint grid to an unstructured grid. 77 | 78 | :param grid: Cornerpoint grid to be converted. 79 | :type grid: dict, with 'COORD', 'ZCORN', 'ACTNUM' 80 | :returns: Unstructured grid 81 | :rtype: dict 82 | """ 83 | # extract the properties of interest from the cornerpoint grid 84 | zcorn = grid['ZCORN'] 85 | actnum = grid['ACTNUM'] 86 | ni, nj, nk = grid['DIMENS'] 87 | 88 | # zcorn has now dimensionality (k, b, j, f, i, r) and actnum is (k, j, i); 89 | # permute the cubes to get the (b, k)-dimensions varying quickest, to avoid 90 | # page faults when we move along pillars/columns 91 | zcorn = np.transpose(zcorn, axes=[2, 3, 4, 5, 1, 0]) 92 | actnum = np.transpose(actnum, axes=[1, 2, 0]) 93 | 94 | # memory allocation: number of unique cornerpoints along each pillar, and 95 | # the index of each cornerpoint into the global list of vertices 96 | num_cp = np.empty((nj + 1, ni + 1), dtype=np.int32) 97 | ndx_cp = np.empty((nk, 2, nj, 2, ni, 2), dtype=np.int32) 98 | 99 | # each pillar is connected to at most 2*2 columns (front/back, right/left), 100 | # and each column has at most 2*nk (one top and one bottom) corners 101 | corn_z = np.empty((2, 2, 2, nk), dtype=np.float32) 102 | corn_i = np.empty((2, 2, 2, nk), dtype=np.int32) 103 | corn_j = np.empty((2, 2, 2, nk), dtype=np.int32) 104 | corn_a = np.empty((2, 2, 2, nk), dtype=np.bool) 105 | 106 | # get all unique points that are hinged to a certain pillar (p, q) 107 | for q, p in np.ndindex((nj + 1, ni + 1)): 108 | # reset number of corners found for this column 109 | num_corn_z = 0 110 | 111 | for f, r in np.ndindex((2, 2)): # front/back, right/left 112 | # calculate the cell index of the column at this position 113 | j = q - f 114 | i = p - r 115 | 116 | for b in range(2): # bottom/top 117 | 118 | # copy depth values for this corner; notice that we have 119 | # pivoted the zcorn matrix so that values going upwards are in 120 | # last dim. 121 | corn_z[f, r, b, :] = zcorn[j, f, i, r, b, :] 122 | 123 | # same for active numbers, but this is reused for top/bottom; 124 | # if the cell is inactive, then both top and bottom point are. 125 | corn_a[f, r, b, :] = actnum[j, i, :] 126 | 127 | # save the original indices into these auxiliary arrays so that 128 | # we can figure out where each point came from after they are 129 | # sorted 130 | corn_i[f, r, b] = i 131 | corn_j[f, r, b] = j 132 | -------------------------------------------------------------------------------- /Example/3WELL.mako: -------------------------------------------------------------------------------- 1 | <%! 2 | import numpy as np 3 | import datetime as dt 4 | %> 5 | -- *------------------------------------------* 6 | -- * * 7 | -- * base grid model with input parameters * 8 | -- * * 9 | -- *------------------------------------------* 10 | RUNSPEC 11 | 12 | TITLE 13 | 3 WELL MODEL 14 | 15 | DIMENS 16 | -- NDIVIX NDIVIY NDIVIZ 17 | 100 100 1 / 18 | 19 | -- Gradient option 20 | -- AJGRADNT 21 | 22 | -- Gradients readeable 23 | -- UNCODHMD 24 | 25 | --BLACKOIL 26 | OIL 27 | WATER 28 | 29 | METRIC 30 | 31 | TABDIMS 32 | -- NTSFUN NTPVT NSSFUN NPPVT NTFIP NRPVT NTENDP 33 | 1 1 35 30 5 30 1 / 34 | 35 | EQLDIMS 36 | -- NTEQUL NDRXVD NDPRVD 37 | 1 5 100 / 38 | 39 | WELLDIMS 40 | -- NWMAXZ NCWMAX NGMAXZ MWGMAX 41 | 10 1 2 20 / 42 | 43 | VFPPDIMS 44 | -- MXMFLO MXMTHP MXMWFR MXMGFR MXMALQ NMMVFT 45 | 10 10 10 10 1 1 / 46 | 47 | VFPIDIMS 48 | -- MXSFLO MXSTHP NMSVFT 49 | 10 10 1 / 50 | 51 | AQUDIMS 52 | -- MXNAQN MXNAQC NIFTBL NRIFTB NANAQU NCAMAX 53 | 0 0 1 36 2 200/ 54 | 55 | START 56 | 09 FEB 1994 / 57 | 58 | NSTACK 59 | 25 / 60 | 61 | NOECHO 62 | 63 | GRID 64 | INIT 65 | 66 | INCLUDE 67 | '../TRUEPERMX.INC' 68 | / 69 | 70 | 71 | COPY 72 | 'PERMX' 'PERMY' / 73 | 'PERMX' 'PERMZ' / 74 | / 75 | 76 | DX 77 | 10000*10 / 78 | DY 79 | 10000*10 / 80 | DZ 81 | 10000*10 / 82 | 83 | TOPS 84 | 10000*2355 / 85 | 86 | PORO 87 | 10000*0.18 / 88 | 89 | 90 | PROPS =============================================================== 91 | 92 | -- Two-phase (water-oil) rel perm curves 93 | -- Sw Krw Kro Pcow 94 | SWOF 95 | 0.1500 0.0 1.0000 0.0 96 | 0.2000 0.0059 0.8521 0.0 97 | 0.2500 0.0237 0.7160 0.0 98 | 0.3000 0.0533 0.5917 0.0 99 | 0.3500 0.0947 0.4793 0.0 100 | 0.4000 0.1479 0.3787 0.0 101 | 0.4500 0.2130 0.2899 0.0 102 | 0.5000 0.2899 0.2130 0.0 103 | 0.5500 0.3787 0.1479 0.0 104 | 0.6000 0.4793 0.0947 0.0 105 | 0.6500 0.5917 0.0533 0.0 106 | 0.7000 0.7160 0.0237 0.0 107 | 0.7500 0.8521 0.0059 0.0 108 | 0.8000 1.0000 0.0 0.0 109 | / 110 | 111 | --PVCDO 112 | -- REF.PRES. FVF COMPRESSIBILITY REF.VISC. VISCOSIBILITY 113 | -- 234 1.065 6.65e-5 5.0 1.9e-3 / 114 | 115 | -- In a e300 run we must use PVDO 116 | PVDO 117 | 220 1.065 5.0 118 | 240 1.06499 5.0 / 119 | 120 | DENSITY 121 | 912.0 1000.0 0.8266 122 | / 123 | 124 | PVTW 125 | 234.46 1.0042 5.43E-05 0.5 1.11E-04 / 126 | 127 | 128 | -- ROCK COMPRESSIBILITY 129 | -- 130 | -- REF. PRES COMPRESSIBILITY 131 | ROCK 132 | 235 0.00045 / 133 | 134 | 135 | 136 | REGIONS =============================================================== 137 | 138 | ENDBOX 139 | 140 | SOLUTION =============================================================== 141 | 142 | 143 | -- DATUM DATUM OWC OWC GOC GOC RSVD RVVD SOLN 144 | -- DEPTH PRESS DEPTH PCOW DEPTH PCOG TABLE TABLE METH 145 | EQUIL 146 | 2355.00 200.46 3000 0.00 2355.0 0.000 0 0 / 147 | 148 | 149 | RPTSOL 150 | 'PRES' 'SWAT' / 151 | 152 | RPTRST 153 | BASIC=2 / 154 | 155 | 156 | 157 | SUMMARY ================================================================ 158 | 159 | RUNSUM 160 | 161 | EXCEL 162 | 163 | --RPTONLY 164 | FOPT 165 | FGPT 166 | FWPT 167 | FWIT 168 | 169 | WWIR 170 | 'INJ-1' 171 | / 172 | 173 | WOPR 174 | 'PRO-1' 175 | / 176 | 177 | WWPR 178 | 'PRO-1' 179 | / 180 | 181 | SCHEDULE ============================================================= 182 | 183 | 184 | RPTSCHED 185 | 'NEWTON=2' / 186 | 187 | RPTRST 188 | BASIC=2 / 189 | 190 | -- AJGWELLS 191 | -- 'INJ-1' 'WWIR' / 192 | -- 'PRO-1' 'WLPR' / 193 | --/ 194 | 195 | -- AJGPARAM 196 | -- 'PERMX' 'PORO' / 197 | 198 | ------------------- WELL SPECIFICATION DATA -------------------------- 199 | WELSPECS 200 | 'INJ-1' 'G' 1 1 2357 WATER 1* 'STD' 3* / 201 | 'INJ-2' 'G' 100 1 2357 WATER 1* 'STD' 3* / 202 | 'PRO-1' 'G' 100 100 2357 OIL 1* 'STD' 3* / 203 | / 204 | COMPDAT 205 | -- RADIUS SKIN 206 | 'INJ-1' 1 1 1 1 'OPEN' 2* 0.15 1* 5.0 / 207 | 'INJ-2' 100 1 1 1 'OPEN' 2* 0.15 1* 5.0 / 208 | 'PRO-1' 100 100 1 1 'OPEN' 2* 0.15 1* 5.0 / 209 | / 210 | 211 | WCONINJE 212 | --'INJ-1' WATER 'OPEN' BHP 2* 300 / 213 | --'INJ-1' WATER 'OPEN' BHP 2* 250 / 214 | 'INJ-1' WATER 'OPEN' BHP 2* ${injbhp[0]} / 215 | 'INJ-2' WATER 'OPEN' BHP 2* ${injbhp[1]} / 216 | / 217 | 218 | WCONPROD 219 | --'PRO-1' 'OPEN' BHP 5* 100 / 220 | 'PRO-1' 'OPEN' BHP 5* ${prodbhp[0]} / 221 | / 222 | 223 | 224 | --------------------- PRODUCTION SCHEDULE ---------------------------- 225 | 226 | 227 | 228 | DATES 229 | 1 JAN 1995 / 230 | / 231 | 232 | DATES -- Generated : Petrel 233 | 1 JAN 1996 / 234 | / 235 | 236 | DATES -- Generated : Petrel 237 | 1 JAN 1997 / 238 | / 239 | 240 | DATES -- Generated : Petrel 241 | 1 JAN 1998 / 242 | / 243 | 244 | DATES -- Generated : Petrel 245 | 1 JAN 1999 / 246 | / 247 | 248 | 249 | 250 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Subsurface 2 | Repository containing some standard simulation wrappers. For a detailed description of how to build the wrappers, 3 | see the documentation for PET. 4 | 5 | ## Installation 6 | Clone the repository and install it in editable mode by running 7 | ```bash 8 | python3 -m pip install -e . 9 | ``` 10 | 11 | ## Examples 12 | The example demonstrates usage of [OPM-flow](https://opm-project.org/). To reproduce, ensure that OPM-flow is installed and in the path. The full noteboox is [here](https://github.com/Python-Ensemble-Toolbox/SimulatorWrap/tree/main/Example), we employ the [3Spot example](https://github.com/Python-Ensemble-Toolbox/Examples/tree/main/3Spot) as a template for this example. All files are Example folder. 13 | 14 | 15 | ```python 16 | # import the flow class 17 | from subsurface.multphaseflow.opm import flow 18 | # import datatime 19 | import datetime as dt 20 | # import numpy 21 | import numpy as np 22 | ``` 23 | 24 | To initialllize the wrapper such that we get the needed outputs we must specify multiple inputs. This will typically be extracted from a config .toml file. 25 | 26 | 27 | ```python 28 | # a dictionary containing relevant information 29 | input_dict = {'parallel':2, 30 | 'simoptions': [['sim_flag', '--tolerance-mb=1e-5 --parsing-strictness=low']], 31 | 'sim_limit': 4, 32 | 'reportpoint': [dt.datetime(1994,2,9,00,00,00), 33 | dt.datetime(1995,1,1,00,00,00), 34 | dt.datetime(1996,1,1,00,00,00), 35 | dt.datetime(1997,1,1,00,00,00), 36 | dt.datetime(1998,1,1,00,00,00), 37 | dt.datetime(1999,1,1,00,00,00)], 38 | 'reporttype': "dates", 39 | 'datatype': [ 40 | "fopt", 41 | "fgpt", 42 | "fwpt", 43 | "fwit"], 44 | 'runfile':'3well'} 45 | 46 | # name of the runfile 47 | filename = '3WELL' 48 | ``` 49 | 50 | 51 | ```python 52 | # Generate an instance of the simulator class 53 | sim = flow(input_dict=input_dict,filename=filename) 54 | ``` 55 | 56 | 57 | ```python 58 | # Setup simulator 59 | sim.setup_fwd_run(redund_sim=None) 60 | ``` 61 | 62 | The point of the simulator wrapper in PET is to generate the simulation response for an ensemble of parameters. The mako template file needs to render a DATA file for each uncertain parameter. Hence, the syntax of the mako file need to match the test one wants to run. It is up to the user to specify this file. In the 3Spot case, the uncertain parameter consists of the bhp controll for the wells. In the wrapper this is a dictionary with keys matching the variablename in the mako file. 63 | 64 | 65 | ```python 66 | state = {'injbhp':np.array([280,245]), 67 | 'prodbhp':np.array([110])} 68 | ``` 69 | 70 | 71 | ```python 72 | # we can now run the flow simulator 73 | pred = sim.run_fwd_sim(state,member_i=0,del_folder=True) 74 | ``` 75 | 76 | 77 | ```python 78 | pred 79 | ``` 80 | 81 | 82 | 83 | 84 | [{'fopt': array([[0.]]), 85 | 'fgpt': array([[0.]]), 86 | 'fwpt': array([[0.]]), 87 | 'fwit': array([[0.]])}, 88 | {'fopt': array([131.0504], dtype=float32), 89 | 'fgpt': array([0.], dtype=float32), 90 | 'fwpt': array([0.48596448], dtype=float32), 91 | 'fwit': array([242.00461], dtype=float32)}, 92 | {'fopt': array([276.51306], dtype=float32), 93 | 'fgpt': array([0.], dtype=float32), 94 | 'fwpt': array([0.857482], dtype=float32), 95 | 'fwit': array([463.29108], dtype=float32)}, 96 | {'fopt': array([420.74808], dtype=float32), 97 | 'fgpt': array([0.], dtype=float32), 98 | 'fwpt': array([1.1765413], dtype=float32), 99 | 'fwit': array([675.35266], dtype=float32)}, 100 | {'fopt': array([564.2478], dtype=float32), 101 | 'fgpt': array([0.], dtype=float32), 102 | 'fwpt': array([1.4610703], dtype=float32), 103 | 'fwit': array([891.02484], dtype=float32)}, 104 | {'fopt': array([707.78033], dtype=float32), 105 | 'fgpt': array([0.], dtype=float32), 106 | 'fwpt': array([1.720426], dtype=float32), 107 | 'fwit': array([1110.3655], dtype=float32)}] 108 | 109 | 110 | 111 | 112 | ```python 113 | # we can make simple plot using matplotlib 114 | import matplotlib.pyplot as plt 115 | # Display plots inline in Jupyter 116 | %matplotlib inline 117 | ``` 118 | 119 | 120 | ```python 121 | plt.figure(figsize=(10, 6)); 122 | plt.plot(input_dict['reportpoint'],np.concatenate(np.array([el['fopt'].flatten() for el in pred]))); 123 | plt.title('Field Oil Production Total'); 124 | plt.xlabel('Report dates'); 125 | plt.ylabel('STB'); 126 | ``` 127 | 128 |

129 | 130 |


131 | 132 | 133 | ```python 134 | plt.figure(figsize=(10, 6)); 135 | plt.plot(input_dict['reportpoint'],np.concatenate(np.array([el['fgpt'].flatten() for el in pred]))); 136 | plt.title('Field Gas Production Total'); 137 | plt.xlabel('Report dates'); 138 | plt.ylabel('STB'); 139 | ``` 140 | 141 | 142 |

143 | 144 |


145 | 146 | 147 | 148 | ```python 149 | plt.figure(figsize=(10, 6)); 150 | plt.plot(input_dict['reportpoint'],np.concatenate(np.array([el['fwpt'].flatten() for el in pred]))); 151 | plt.title('Field Water Production Total'); 152 | plt.xlabel('Report dates'); 153 | plt.ylabel('STB'); 154 | ``` 155 | 156 | 157 |

158 | 159 |


160 | 161 | 162 | 163 | ```python 164 | plt.figure(figsize=(10, 6)); 165 | plt.plot(input_dict['reportpoint'],np.concatenate(np.array([el['fwit'].flatten() for el in pred]))); 166 | plt.title('Field Water Injection Total'); 167 | plt.xlabel('Report dates'); 168 | plt.ylabel('STB'); 169 | ``` 170 | 171 | 172 |

173 | 174 |


175 | 176 | -------------------------------------------------------------------------------- /src/subsurface/multphaseflow/misc/grid/sector.py: -------------------------------------------------------------------------------- 1 | """\ 2 | Extract a sector from an existing cornerpoint grid. 3 | """ 4 | import argparse 5 | import collections 6 | import logging 7 | import numpy 8 | import re 9 | import sys 10 | 11 | import simulator.multphaseflow.misc.grid as pyr 12 | import simulator.multphaseflow.misc.grdecl as grdecl 13 | 14 | 15 | # add a valid log in case we are not run through the main program which 16 | # sets up one for us 17 | log = logging.getLogger(__name__) # pylint: disable=invalid-name 18 | log.addHandler(logging.NullHandler()) 19 | 20 | # three consecutive integers, separated by comma, and perhaps some spaces 21 | # thrown in for readability, optionally enclosed in parenthesis 22 | tuple_format = re.compile(r'\(?([0-9]+)\ *\,\ *([0-9]+)\ *\,\ *([0-9]+)\)?') 23 | 24 | 25 | def parse_tuple(corner): 26 | """\ 27 | Parse a parenthesized tuple into three constituent coordinates. 28 | 29 | :param corner: Coordinate specification on the format "(i1,j1,k1)" 30 | :type corner: str 31 | :returns: The parsed tuple, converted into zero-based coordinates 32 | and in Python-matrix order: (k, j, i) 33 | :rtype : (int, int, int) 34 | """ 35 | # let the regular expression engine parse the string 36 | match = re.match(tuple_format, corner.strip()) 37 | 38 | # if the string matched, then we know that each of the sub-groups can be 39 | # parsed into strings successfully. group 0 is the entire string, so we 40 | # get natural numbering into the parenthesized expressions. subtract one 41 | # to get zero-based coordinates 42 | if match: 43 | i = int(match.group(1)) - 1 44 | j = int(match.group(2)) - 1 45 | k = int(match.group(3)) - 1 46 | return (k, j, i) 47 | # if we didn't got any valid string, then return a bottom value 48 | else: 49 | return None 50 | 51 | 52 | def sort_tuples(corner, opposite): 53 | """\ 54 | :param corner: Coordinates of one corner 55 | :type corner: (int, int, int) 56 | :param opposite: Coordinates of the opposite corner 57 | :type opposite: (int, int, int) 58 | :returns: The two tuples, but with coordinates interchanged so that 59 | one corner is always in the lower, left, back and the 60 | other is in the upper, right, front 61 | :rtype: ((int, int, int), (int, int, int)) 62 | """ 63 | # pick out the most extreme variant in either direction, into each its own 64 | # variable; this may be the same as the input or not, but at least we know 65 | # for sure when we return from this method 66 | least = (min(corner[0], opposite[0]), 67 | min(corner[1], opposite[1]), 68 | min(corner[2], opposite[2])) 69 | most = (max(corner[0], opposite[0]), 70 | max(corner[1], opposite[1]), 71 | max(corner[2], opposite[2])) 72 | return (least, most) 73 | 74 | 75 | def extract_dimens(least, most): 76 | """\ 77 | Build a new dimension tuple for a submodel 78 | 79 | :param least: Lower, left-most, back corner of submodel, (k1, j1, i1) 80 | :type least: (int, int, int) 81 | :param most: Upper, right-most, front corner of submodel, (k2, j2, i2) 82 | :type most: (int, int, int) 83 | :returns: Dimensions of the submodel 84 | :rtype: numpy.ndarray((3,)) 85 | """ 86 | # split the corners into constituents 87 | k1, j1, i1 = least 88 | k2, j2, i2 = most 89 | 90 | # make an array out of the cartesian distance of the two corners 91 | sector_dimens = numpy.array([i2-i1+1, j2-j1+1, k2-k1+1], dtype=numpy.int32) 92 | return sector_dimens 93 | 94 | 95 | def extract_coord(coord, least, most): 96 | """\ 97 | Extract the coordinate pillars for a submodel 98 | 99 | :param coord: Coordinate pillars for the entire grid 100 | :type coord: numpy.ndarray((nj+1, ni+1, 2, 3)) 101 | :param least: Lower, left-most, back corner of submodel, (k1, j1, i1) 102 | :type least: (int, int, int) 103 | :param most: Upper, right-most, front corner of submodel, (k2, j2, i2) 104 | :type most: (int, int, int) 105 | :returns: Coordinate pilars for the submodel 106 | :rtype: numpy.ndarray((j2-j1+2, i2-i1+2, 2, 3)) 107 | """ 108 | # split the corners into constituents 109 | k1, j1, i1 = least 110 | k2, j2, i2 = most 111 | 112 | # add one to get the pillar on the other side of the element, so that 113 | # we include the last element, add one more since Python indexing is 114 | # end-exclusive 115 | sector_coord = coord[j1:(j2+2), i1:(i2+2), :, :] 116 | return sector_coord 117 | 118 | 119 | def extract_zcorn(zcorn, least, most): 120 | """\ 121 | Extract the hinge depth values for a submodel 122 | 123 | :param zcorn: Hinge depth values for the entire grid 124 | :type zcorn: numpy.ndarray((nk, 2, nj, 2, ni, 2)) 125 | :param least: Lower, left-most, back corner of submodel, (k1, j1, i1) 126 | :type least: (int, int, int) 127 | :param most: Upper, right-most, front corner of submodel, (k2, j2, i2) 128 | :type most: (int, int, int) 129 | :returns: Hinge depth values for the submodel 130 | :rtype: numpy.ndarray((k2-k1+1, 2, j2-j1+1, 2, i2-i1+1)) 131 | """ 132 | # split the corners into constituents 133 | k1, j1, i1 = least 134 | k2, j2, i2 = most 135 | 136 | # add one since Python-indexing is end-exclusive, and we want to include 137 | # the element in the opposite corner. all eight hinges are returned for 138 | # each element (we only select in every other dimension) 139 | sector_zcorn = zcorn[k1:(k2+1), :, j1:(j2+1), :, i1:(i2+1), :] 140 | return sector_zcorn 141 | 142 | 143 | def extract_cell_prop(prop, least, most): 144 | """\ 145 | Extract the property values for a submodel 146 | 147 | :param prop: Property values for each cell in the the entire grid 148 | :type prop: numpy.ndarray((nk, nj, ni)) 149 | :param least: Lower, left-most, back corner of submodel, (k1, j1, i1) 150 | :type least: (int, int, int) 151 | :param most: Upper, right-most, front corner of submodel, (k2, j2, i2) 152 | :type most: (int, int, int) 153 | :returns: Property values for each cell in the submodel 154 | :rtype: numpy.ndarray((k2-k1+1, j2-j1+1, i2-i1+1)) 155 | """ 156 | # split the corners into constituents 157 | k1, j1, i1 = least 158 | k2, j2, i2 = most 159 | 160 | # add one since Python-indexing is end-exclusive, and we want to include 161 | # the element in the opposite corner. 162 | sector_prop = prop[k1:(k2+1), j1:(j2+1), i1:(i2+1)] 163 | return sector_prop 164 | 165 | 166 | def extract_grid(grid, least, most): 167 | """\ 168 | Extract a submodel from a full grid 169 | 170 | :param grid: Attributes of the full grid, like COORD, ZCORN, ACTNUM 171 | :type grid: dict 172 | :param least: Lower, left-most, back corner of submodel, (k1, j1, i1) 173 | :type least: (int, int, int) 174 | :param most: Upper, right-most, front corner of submodel, (k2, j2, i2) 175 | :type most: (int, int, int) 176 | :returns: Attributes of the sector model 177 | :rtype: dict 178 | """ 179 | # create a new grid and fill extract standard properties 180 | sector = collections.OrderedDict() 181 | sector['DIMENS'] = extract_dimens(least, most) 182 | sector['COORD'] = extract_coord(grid['COORD'], least, most) 183 | sector['ZCORN'] = extract_zcorn(grid['ZCORN'], least, most) 184 | sector['ACTNUM'] = extract_cell_prop(grid['ACTNUM'], least, most) 185 | 186 | # then extract all extra cell properties, such as PORO, PERMX that 187 | # may have been added 188 | for prop_name in grid: 189 | # ignore the standard properties; they have already been converted 190 | # by specialized methods above 191 | prop_upper = prop_name.upper() 192 | std_prop = ((prop_upper == 'DIMENS') or (prop_upper == 'COORD') or 193 | (prop_upper == 'ZCORN') or (prop_upper == 'ACTNUM')) 194 | # use the generic method to convert this property 195 | if not std_prop: 196 | sector[prop_name] = extract_cell_prop(grid[prop_name], least, most) 197 | 198 | return sector 199 | 200 | 201 | def main(*args): 202 | """Read a data file to see if it parses OK.""" 203 | # setup simple logging where we prefix each line with a letter code 204 | logging.basicConfig(level=logging.INFO, 205 | format="%(levelname).1s: %(message).76s") 206 | 207 | # parse command-line arguments 208 | parser = argparse.ArgumentParser() 209 | parser.add_argument("infile", metavar="infile.grdecl", help="Input model") 210 | parser.add_argument("outfile", metavar="outfile", 211 | help="Output sector model") 212 | parser.add_argument("first", metavar="i1,j1,k1", type=parse_tuple, 213 | help="A corner of the sector model (one-based)") 214 | parser.add_argument("last", metavar="i2,j2,k2", type=parse_tuple, 215 | help="The opposite corner of the sector (one-based)") 216 | parser.add_argument("--dialect", choices=['ecl', 'cmg'], default='ecl') 217 | parser.add_argument("--verbose", action='store_true') 218 | parser.add_argument("--quiet", action='store_true') 219 | cmd_args = parser.parse_args(*args) 220 | 221 | # adjust the verbosity of the program 222 | if cmd_args.verbose: 223 | logging.getLogger(__name__).setLevel(logging.DEBUG) 224 | if cmd_args.quiet: 225 | logging.getLogger(__name__).setLevel(logging.NOTSET) 226 | 227 | # read the input file 228 | log.info('Reading full grid') 229 | grid = pyr.read_grid(cmd_args.infile) 230 | 231 | # get the two opposite corners that defines the submodel 232 | log.info('Determining scope of sector model') 233 | least, most = sort_tuples(cmd_args.first, cmd_args.last) 234 | log.info('Sector model is (%d, %d, %d)-(%d, %d, %d)', 235 | least[2]+1, least[1]+1, least[0]+1, 236 | most[2]+1, most[1]+1, most[0]+1) 237 | 238 | # extract the data for the submodel into a new grid 239 | log.info('Extracting sector model from full grid') 240 | submodel = extract_grid(grid, least, most) 241 | 242 | # write this grid to output 243 | log.info('Writing sector model to disk') 244 | grdecl.write(cmd_args.outfile, submodel, cmd_args.dialect, 245 | multi_file=True) 246 | 247 | 248 | # if this module is called as a standalone program, then pass all the 249 | # arguments, except the program name 250 | if __name__ == "__main__": 251 | main(sys.argv[1:]) 252 | -------------------------------------------------------------------------------- /src/subsurface/multphaseflow/opm.py: -------------------------------------------------------------------------------- 1 | """Wrap OPM-flow""" 2 | # External imports 3 | from subprocess import call, DEVNULL, run 4 | import os,sys 5 | import shutil 6 | import re 7 | import time 8 | from datetime import timedelta 9 | 10 | # Internal imports 11 | from subsurface.multphaseflow.eclipse import eclipse 12 | from misc.system_tools.environ_var import OPMRunEnvironment 13 | 14 | 15 | class flow(eclipse): 16 | """ 17 | Class for running OPM flow with Eclipse input files. Inherits eclipse parent class for setting up and running 18 | simulations, and reading the results. 19 | """ 20 | 21 | def __init__(self,input_file=None,initialize_parent=True): 22 | if initialize_parent: 23 | super().__init__(input_file) 24 | else: 25 | self.file = input_file['filename'] 26 | self.options = input_file 27 | 28 | def call_sim(self, folder=None, wait_for_proc=False): 29 | """ 30 | Call OPM flow simulator via shell. 31 | 32 | Parameters 33 | ---------- 34 | folder : str 35 | Folder with runfiles. 36 | 37 | wait_for_proc : bool 38 | Boolean determining if we wait for the process to be done or not. 39 | 40 | Changelog 41 | --------- 42 | - ST 18/10-18 43 | """ 44 | # Filename 45 | if folder is not None: 46 | filename = folder + self.file 47 | else: 48 | filename = self.file 49 | 50 | success = True 51 | #print(filename) 52 | try: 53 | with OPMRunEnvironment(filename, 'PRT', ['End of simulation', 'NOSIM']): 54 | com = [] 55 | if self.options['mpi']: 56 | com.extend(self.options['mpi'].split()) 57 | com.append(self.options['sim_path'] + 'flow') 58 | if self.options['parsing-strictness']: 59 | com.extend(['--parsing-strictness=' + self.options['parsing-strictness']]) 60 | com.extend(['--output-dir=' + folder, * 61 | self.options['sim_flag'].split(), filename + '.DATA']) 62 | if 'sim_limit' in self.options: 63 | call(com, stdout=DEVNULL, timeout=self.options['sim_limit']) 64 | else: 65 | call(com, stdout=DEVNULL) 66 | raise ValueError # catch errors in run_sim 67 | except Exception as e: 68 | print('\nError in the OPM run.') # add rerun? 69 | if not os.path.exists('Crashdump'): 70 | shutil.copytree(folder, 'Crashdump') 71 | success = False 72 | 73 | return success 74 | 75 | def check_sim_end(self, finished_member=None): 76 | """ 77 | Check in RPT file for "End of simulation" to see if OPM flow is done. 78 | 79 | Changelog 80 | --------- 81 | - ST 19/10-18 82 | """ 83 | # Initialize output 84 | # member = None 85 | # 86 | # # Search for output.dat file 87 | # for file in os.listdir('En_' + str(finished_member)): # Search within a specific En_folder 88 | # if file.endswith('PRT'): # look in PRT file 89 | # with open('En_' + str(finished_member) + os.sep + file, 'r') as fid: 90 | # for line in fid: 91 | # if re.search('End of simulation', line): 92 | # # TODO: not do time.sleep() 93 | # # time.sleep(0.1) 94 | # member = finished_member 95 | 96 | return finished_member 97 | 98 | @staticmethod 99 | def SLURM_HPC_run(n_e, venv,filename, **kwargs): 100 | """ 101 | HPC run manager for SLURM. 102 | 103 | This function will start num_runs of sim.call_sim() using job arrays in SLURM. 104 | """ 105 | # Extract the filename from the kwargs 106 | filename_str = f'"{filename.upper()}"' if filename is not None else "" 107 | 108 | # Extract mpi flag from kwargs 109 | mpi = kwargs.get("mpi", None) 110 | mpi_str = f'"{mpi}"' if mpi is not None else '"mpirun --bind-to none -np 1"' 111 | 112 | # set number of tasks to the number following -np in mpi_str (default is 1) 113 | n_tasks = re.search(r"-np (\d+)", mpi_str).group(1) 114 | 115 | # extract the sim_limit from kwargs. Default is 1 hour 116 | sim_limit = kwargs.get("sim_limit", None) 117 | sim_limit_str = f'--time={str(timedelta(seconds=sim_limit))}' if sim_limit is not None else "--time=01:00:00" 118 | 119 | # extract estimated memory requirement (Gigabyte) for a job 120 | mem = str(kwargs.get("mem", "4G")) 121 | 122 | # extract opm simulator version 123 | opm_ver = kwargs.get("opm_ver", "") # e.g., "/2025.04-foss-2024a" (remember the leading /) 124 | 125 | # extract Python version 126 | python_ver = kwargs.get("python_ver", "") # e.g., "/3.12.3-GCCcore-13.3.0" (remember the leading /) 127 | 128 | diff_ne = n_e[-1] - n_e[0] 129 | 130 | slurm_script = f"""#!/bin/bash 131 | #SBATCH --partition=comp 132 | #SBATCH --job-name=EnDA 133 | #SBATCH --array=0-{diff_ne} 134 | #SBATCH {sim_limit_str} 135 | #SBATCH --mem={mem} 136 | #SBATCH --ntasks={n_tasks} 137 | #SBATCH --cpus-per-task=2 138 | #SBATCH --export=ALL 139 | #SBATCH --output=/dev/null 140 | 141 | # OPTIONAL: load modules here 142 | module load Python{python_ver} 143 | export LMOD_DISABLE_SAME_NAME_AUTOSWAP=no 144 | module load opm-simulators{opm_ver} 145 | 146 | source {venv} 147 | 148 | # Set folder based on SLURM_ARRAY_TASK_ID 149 | folder="En_$(( {n_e[0]} + SLURM_ARRAY_TASK_ID ))/" 150 | 151 | python -m subsurface.multphaseflow.opm "$folder" {filename_str} {mpi_str} 152 | """ 153 | script_name = "submit_test_parallel_mpi.sh" 154 | with open(script_name, "w") as f: 155 | f.write(slurm_script) 156 | 157 | # Make it executable (optional): 158 | os.chmod(script_name, 0o755) 159 | 160 | # print(f"Created SLURM script: {script_name}") 161 | # print(f"Submitting array job with {num_runs} tasks...") 162 | 163 | # Submit the script to SLURM 164 | cmd = ["sbatch", script_name] 165 | result = run(cmd, capture_output=True, text=True) 166 | 167 | # remove script file 168 | os.remove(script_name) 169 | 170 | # Extract the job ID from the output 171 | match = re.search(r"Submitted batch job (\d+)", result.stdout) 172 | if match: 173 | return match.group(1) # Return the main job ID 174 | else: 175 | print("Failed to extract Job ID from sbatch output.") 176 | return None 177 | 178 | @staticmethod 179 | def SLURM_ARRAY_HPC_run(n_e, venv, filename, **kwargs): 180 | """ 181 | HPC run manager for Slurm array jobs. 182 | Each ensemble member runs independently in its own task. 183 | 184 | Parameters 185 | ---------- 186 | n_e : list[int] 187 | Indices of ensemble members to simulate. 188 | venv : str 189 | Path to Python virtual environment activate script. 190 | filename : str 191 | Simulation input file. 192 | kwargs : dict 193 | Extra simulation options. Recognized: 194 | - sim_limit (float seconds or str HH:MM:SS) 195 | - mem (default "4G") 196 | - cpus_per_task (default 2) 197 | """ 198 | 199 | # Start and end indices for the array 200 | start_idx = n_e[0] 201 | end_idx = n_e[-1] 202 | num_tasks = end_idx - start_idx 203 | 204 | # Extract options 205 | sim_limit = kwargs.get("sim_limit", None) 206 | if sim_limit is not None: 207 | if isinstance(sim_limit, (int, float)): 208 | from datetime import timedelta 209 | sim_limit_str = f'--time={str(timedelta(seconds=sim_limit))}' 210 | else: 211 | sim_limit_str = f'--time={sim_limit}' 212 | else: 213 | sim_limit_str = "--time=02:00:00" 214 | 215 | mem = kwargs.get("mem", "4G") 216 | cpus_per_task = kwargs.get("cpus_per_task", 1) 217 | 218 | slurm_script = f"""#!/bin/bash 219 | #SBATCH --job-name=EnDA_array 220 | #SBATCH --partition=comp 221 | #SBATCH --array=0-{num_tasks} 222 | #SBATCH --cpus-per-task={cpus_per_task} 223 | #SBATCH --mem={mem} 224 | #SBATCH {sim_limit_str} 225 | #SBATCH --output=logs/job_%A_%a.out 226 | #SBATCH --error=logs/job_%A_%a.err 227 | 228 | module load Python 229 | export LMOD_DISABLE_SAME_NAME_AUTOSWAP=no 230 | module load opm-simulators 231 | source {venv} 232 | 233 | IDX=$(( {start_idx} + SLURM_ARRAY_TASK_ID )) 234 | FOLDER="En_$IDX/" 235 | 236 | python -m subsurface.multphaseflow.opm "$FOLDER" {filename} "" 237 | """ 238 | 239 | script_name = "submit_array.sh" 240 | with open(script_name, "w") as f: 241 | f.write(slurm_script) 242 | 243 | os.chmod(script_name, 0o755) 244 | 245 | result = run(["sbatch", script_name], capture_output=True, text=True) 246 | 247 | os.remove(script_name) 248 | 249 | match = re.search(r"Submitted batch job (\d+)", result.stdout) 250 | if match: 251 | return match.group(1) 252 | else: 253 | print("Job submission failed:", result.stderr) 254 | return None 255 | 256 | 257 | def are_jobs_done(self, job_id): 258 | """Check if all job array tasks are completed using sacct.""" 259 | check_cmd = ["sacct", "-j", f"{job_id}", "--format=JobID,State", "--noheader"] 260 | 261 | # print(check_cmd) 262 | 263 | check_result = run(check_cmd, capture_output=True, text=True) 264 | 265 | while not len(check_result.stdout): # if spinning up 266 | time.sleep(1) 267 | check_result = run(check_cmd, capture_output=True, text=True) 268 | 269 | # print(check_result.stdout) 270 | 271 | return_states = [] 272 | 273 | job_states = check_result.stdout.strip().split("\n") 274 | for job in job_states: 275 | parts = job.split() 276 | if len(parts) >= 2: 277 | state = parts[1] 278 | if state not in ["COMPLETED", "FAILED", "CANCELLED"]: 279 | return False # A job is still running or pendin 280 | else: 281 | if state == "FAILED" or state == "CANCELLED": 282 | return_states.append(False) 283 | else: 284 | return_states.append(True) 285 | 286 | return return_states 287 | 288 | def wait_for_jobs(self,job_id,wait_time=10): 289 | """Wait until all job array tasks are completed.""" 290 | #print(f"Waiting for job array {job_id} to complete...") 291 | 292 | val = self.are_jobs_done(job_id) 293 | while not val: 294 | time.sleep(wait_time) # Wait for 10 seconds before checking again 295 | val = self.are_jobs_done(job_id) 296 | 297 | return val 298 | 299 | #print(f"All jobs in array {job_id} are completed.") 300 | 301 | 302 | 303 | class ebos(eclipse): 304 | """ 305 | Class for running OPM ebos with Eclipse input files. Inherits eclipse parent class for setting up and running 306 | simulations, and reading the results. 307 | """ 308 | 309 | def call_sim(self, folder=None, wait_for_proc=False): 310 | """ 311 | Call OPM flow simulator via shell. 312 | 313 | Parameters 314 | ---------- 315 | folder : str 316 | Folder with runfiles. 317 | 318 | wait_for_proc : bool 319 | Determines whether to wait for the process to be done or not. 320 | 321 | Changelog 322 | --------- 323 | - RJL 27/08-19 324 | """ 325 | # Filename 326 | if folder is not None: 327 | filename = folder + self.file 328 | else: 329 | filename = self.file 330 | 331 | # Run simulator 332 | if 'sim_path' not in self.options.keys(): 333 | self.options['sim_path'] = '' 334 | 335 | with OPMRunEnvironment(filename, 'OUT', 'Timing receipt'): 336 | with open(filename+'.OUT', 'w') as f: 337 | call([self.options['sim_path'] + 'ebos', '--output-dir=' + folder, 338 | *self.options['sim_flag'].split(), filename + '.DATA'], stdout=f) 339 | 340 | def check_sim_end(self, finished_member=None): 341 | """ 342 | Check in RPT file for "End of simulation" to see if OPM ebos is done. 343 | 344 | Changelog 345 | --------- 346 | - RJL 27/08-19 347 | """ 348 | # Initialize output 349 | # member = None 350 | # 351 | # # Search for output.dat file 352 | # for file in os.listdir('En_' + str(finished_member)): # Search within a specific En_folder 353 | # if file.endswith('OUT'): # look in OUT file 354 | # with open('En_' + str(finished_member) + os.sep + file, 'r') as fid: 355 | # for line in fid: 356 | # if re.search('Timing receipt', line): 357 | # # TODO: not do time.sleep() 358 | # # time.sleep(0.1) 359 | # member = finished_member 360 | 361 | return finished_member 362 | 363 | 364 | if __name__ == "__main__": 365 | import sys 366 | if len(sys.argv) != 4: 367 | print("Usage: python -m subsurface.multphaseflow.opm ") 368 | sys.exit(1) 369 | 370 | folder = sys.argv[1] 371 | filename = sys.argv[2] 372 | mpi = sys.argv[3] 373 | options = {} 374 | options['sim_path'] = '' 375 | options['sim_flag'] = '' 376 | options['mpi'] = mpi 377 | options['parsing-strictness'] = '' 378 | options['filename'] = filename 379 | 380 | sim = flow(input_file=options,initialize_parent=False) 381 | success = sim.call_sim(folder=folder) 382 | if success: 383 | sys.exit(0) 384 | else: 385 | sys.exit(1) # ensure that slurm catch the error 386 | #print("Success!" if success else "Failed.") 387 | -------------------------------------------------------------------------------- /src/subsurface/multphaseflow/misc/system_tools/environ_var.py: -------------------------------------------------------------------------------- 1 | """Descriptive description.""" 2 | 3 | import os 4 | import re 5 | import sys 6 | import multiprocessing.context as ctx 7 | import platform 8 | 9 | 10 | class OpenBlasSingleThread: 11 | """ 12 | A context manager class to set OpenBLAS multi threading environment variable to 1 (i.e., single threaded). The 13 | class is used in a 'with'-statement to ensure that everything inside the statement is run single threaded, 14 | and outside the statement is run using whatever the environment variable was set before the 'with'-statement. 15 | The environment variable setting threading in OpenBLAS is OMP_NUM_THREADS. 16 | 17 | Example 18 | ------- 19 | 20 | >>> from system_tools.environ_var import OpenBlasSingleThread 21 | ... import ctypes 22 | ... import multiprocessing as mp 23 | ... 24 | ... def justdoit(): 25 | ... # Load OpenBLAS library and print number of threads 26 | ... openblas_lib = ctypes.cdll.LoadLibrary('/scratch/openblas/lib/libopenblas.so') 27 | ... print(openblas_lib.openblas_get_num_threads()) 28 | ... 29 | ... if __name__ == "__main__": 30 | ... # Load OpenBLAS library and print number of threads before the with-statement 31 | ... openblas_lib = ctypes.cdll.LoadLibrary('/scratch/openblas/lib/libopenblas.so') 32 | ... print(openblas_lib.openblas_get_num_threads()) 33 | ... 34 | ... # Run a Process inside the with-statement with the OpenBlasSingleThread class. 35 | ... with OpenBlasSingleThread (): 36 | ... p = mp.Process (target=justdoit) 37 | ... p.start () 38 | ... p.join () 39 | ... 40 | ... # Load OpenBLAS library and print number of threads before the with-statement 41 | ... openblas_lib = ctypes.cdll.LoadLibrary('/scratch/openblas/lib/libopenblas.so') 42 | ... print(openblas_lib.openblas_get_num_threads()) 43 | """ 44 | 45 | def __init__(self): 46 | """ 47 | Init. the class with no inputs. Use this to initialize internal variables for storing number of threads an 48 | the Process context manager before the change to single thread. 49 | 50 | Parameters 51 | ---------- 52 | num_threads: 53 | String with number of OpenBLAS threads before change to single 54 | threaded (it is the content of OMP_NUM_THREADS) 55 | ctx: 56 | The context variable from Process (default is 'fork' context, but 57 | we want to use 'spawn') 58 | 59 | Changelog 60 | --------- 61 | - ST 31/10-17 62 | """ 63 | self.num_threads = '' 64 | self.ctx = None 65 | 66 | def __enter__(self): 67 | """ 68 | Method that is run when class is initiated by a 'with'-statement 69 | 70 | Changelog 71 | --------- 72 | - ST 31/10-17 73 | """ 74 | # Save OMP_NUM_THREADS environment variable to restore later 75 | if 'OMP_NUM_THREADS' in os.environ: 76 | self.num_threads = os.environ['OMP_NUM_THREADS'] 77 | else: 78 | self.num_threads = '' 79 | 80 | # Set OMP_NUM_THREADS to 1 to ensure single threaded OpenBLAS 81 | os.environ['OMP_NUM_THREADS'] = '1' 82 | 83 | # Save Process context variable to restore later 84 | self.ctx = ctx._default_context 85 | 86 | # Change context to 'spawn' to ensure that any use of Process inside the 'with'-statement will initialize 87 | # with the newly set OMP_NUM_THREADS=1 environment variable. (The default, 'fork', context only copy its 88 | # parent environment variables without taking into account changes made after a Python program is 89 | # initialized) 90 | ctx._default_context = (ctx.DefaultContext(ctx._concrete_contexts['spawn'])) 91 | 92 | # Return self 93 | return self 94 | 95 | def __exit__(self, exc_typ, exc_val, exc_trb): 96 | """ 97 | Method that is run when 'with'-statement closes. Here, we reset OMP_NUM_THREADS and Process context to what 98 | is was set to before the 'with'-statement. Input here in this method are required to work in 'with'-statement. 99 | 100 | Changelog 101 | --------- 102 | - ST 31/10-17 103 | """ 104 | # Check if there was any OMP_NUM_THREADS at all before the with-statement, and reset it thereafter. 105 | if len(self.num_threads): 106 | os.environ['OMP_NUM_THREADS'] = self.num_threads 107 | else: 108 | os.environ.unsetenv('OMP_NUM_THREADS') 109 | 110 | # Reset Process context 111 | ctx._default_context = self.ctx 112 | 113 | # Return False (exit 0?) 114 | return False 115 | 116 | 117 | class CmgRunEnvironment: 118 | """ 119 | A context manager class to run CMG simulators with correct environmental variables. 120 | """ 121 | 122 | def __init__(self, root, simulator, version, license): 123 | """ 124 | We initialize the context manager by setting up correct paths and environment variable names that we set in 125 | __enter__. 126 | 127 | Parameters 128 | ---------- 129 | root : str 130 | Root folder where CMG simulator(s) are installed. 131 | 132 | simulator : str 133 | Simulator name. 134 | 135 | version : str 136 | Version of the simulator. 137 | 138 | license : str 139 | License server name. 140 | 141 | Changelog 142 | --------- 143 | - ST 25/10-18 144 | 145 | Notes 146 | ----- 147 | 'version' is the release version of CMG, e.g., 2017.101.G. 148 | """ 149 | # In 150 | self.root = root 151 | self.sim = simulator 152 | self.ver = version 153 | self.lic = license 154 | 155 | # Internal 156 | self.ctx = None 157 | self.path = '' 158 | self.ld_path = '' 159 | 160 | # Check system platform. 161 | # TODO: Figure out paths in other systems (read Windows...) and remove assertion. 162 | assert (platform.system() == 'Linux'), \ 163 | 'Sorry, we have only set up paths for Linux systems... But hey, maybe you can implemented it for your ' \ 164 | 'system? :)' 165 | 166 | # Base path to simulator folders 167 | self.path_base = self.root + self.ver + os.sep + self.sim + os.sep + self.ver[:-3] + os.sep + \ 168 | 'linux_x64' + os.sep 169 | 170 | # Path to exe file 171 | self.path_exe = self.path_base + 'exe' 172 | 173 | # Path to libraries 174 | self.path_lib = self.path_base + 'lib' 175 | 176 | def __enter__(self): 177 | """ 178 | Method that is run when class is initiated by a 'with'-statement 179 | 180 | Changelog 181 | --------- 182 | - ST 25/10-18 183 | """ 184 | # Append if environment variable already exist, or generate it if not. 185 | # We also save all environment variables that we intend to alter, so we can restore them when closing the 186 | # context manager class 187 | # PATH 188 | if 'PATH' in os.environ: 189 | self.path = os.environ['PATH'] 190 | os.environ['PATH'] = self.path_exe + os.pathsep + os.environ['PATH'] 191 | else: 192 | self.path = '' 193 | os.environ['PATH'] = self.path_exe 194 | 195 | # LD_LIBRARY_PATH 196 | if 'LD_LIBRARY_PATH' in os.environ: 197 | self.ld_path = os.environ['LD_LIBRARY_PATH'] 198 | os.environ['LD_LIBRARY_PATH'] = self.path_lib + \ 199 | os.pathsep + os.environ['LD_LIBRARY_PATH'] 200 | else: 201 | self.ld_path = '' 202 | os.environ['LD_LIBRARY_PATH'] = self.path_lib 203 | 204 | # Create environment variable for CMG license server 205 | os.environ['CMG_LIC_HOST'] = self.lic 206 | 207 | # Save Process context variable to restore later 208 | self.ctx = ctx._default_context 209 | 210 | # Change context to 'spawn' to ensure that any use of Process inside the 'with'-statement will initialize 211 | # with the newly set environment variables. (The default, 'fork', context only copy its 212 | # parent environment variables without taking into account changes made after a Python program is 213 | # initialized) 214 | ctx._default_context = (ctx.DefaultContext(ctx._concrete_contexts['spawn'])) 215 | 216 | # Return self 217 | return self 218 | 219 | def __exit__(self, exc_typ, exc_val, exc_trb): 220 | """ 221 | Method that is run when 'with'-statement closes. Here, we reset environment variables and Process context to 222 | what is was set to before the 'with'-statement. Input here in this method are required to work in 223 | 'with'-statement. 224 | 225 | Changelog 226 | --------- 227 | - ST 25/10-18 228 | """ 229 | # Reset PATH and LD_LIBRARY_PATH to what they were before our intervention. If they were not set we delete 230 | # them from the environment variables 231 | if len(self.path): 232 | os.environ['PATH'] = self.path 233 | else: 234 | os.environ.unsetenv('PATH') 235 | 236 | if len(self.ld_path): 237 | os.environ['LD_LIBRARY_PATH'] = self.ld_path 238 | else: 239 | os.environ.unsetenv('LD_LIBRARY_PATH') 240 | 241 | # We unset the CMG license server path 242 | os.environ.unsetenv('CMG_LIC_HOST') 243 | 244 | # Reset Process context 245 | ctx._default_context = self.ctx 246 | 247 | # Return False (exit 0?) 248 | return False 249 | 250 | 251 | class OPMRunEnvironment: 252 | """ 253 | A context manager class to run OPM simulators with correct environmental variables. 254 | """ 255 | 256 | def __init__(self, filename, suffix, matchstring): 257 | """ 258 | 259 | - filename: OPM run file, needed to check for errors (string) 260 | - suffix: What file to search for complete sign 261 | - matchstring: what is the complete sign 262 | 263 | Changelog 264 | --------- 265 | - KF 30/10-19 266 | """ 267 | self.filename = filename 268 | self.suffix = suffix 269 | if type(matchstring) != list: 270 | self.mstring = list(matchstring) 271 | else: 272 | self.mstring = matchstring 273 | 274 | def __enter__(self): 275 | """ 276 | Method that is run when class is initiated by a 'with'-statement 277 | 278 | Changelog 279 | --------- 280 | - KF 30/10-19 281 | """ 282 | # Append if environment variable already exist, or generate it if not. 283 | # We also save all environment variables that we intend to alter, so we can restore them when closing the 284 | # context manager class 285 | 286 | # Save Process context variable to restore later 287 | self.ctx = ctx._default_context 288 | 289 | # Change context to 'spawn' to ensure that any use of Process inside the 'with'-statement will initialize 290 | # with the newly set environment variables. (The default, 'fork', context only copy its 291 | # parent environment variables without taking into account changes made after a Python program is 292 | # initialized) 293 | ctx._default_context = (ctx.DefaultContext(ctx._concrete_contexts['spawn'])) 294 | 295 | # Return self 296 | return self 297 | 298 | def __exit__(self, exc_typ, exc_val, exc_trb): 299 | """ 300 | Method that is run when 'with'-statement closes. Here, we reset environment variables and Process context to 301 | what it was set to before the 'with'-statement. Input here in this method are required to work in 302 | 'with'-statement. 303 | 304 | Changelog 305 | --------- 306 | - ST 25/10-18 307 | """ 308 | # Reset PATH and LD_LIBRARY_PATH to what they were before our intervention. If they were not set we delete 309 | # them from the environment variables 310 | 311 | # Reset Process context 312 | ctx._default_context = self.ctx 313 | 314 | member = False 315 | 316 | with open(self.filename + '.' + self.suffix, 'r') as fid: 317 | for line in fid: 318 | if any([re.search(elem, line) for elem in self.mstring]): 319 | # TODO: not do time.sleep() 320 | # time.sleep(0.1) 321 | member = True 322 | if member == False: 323 | return False 324 | return True 325 | 326 | 327 | class FlowRockRunEnvironment: 328 | """ 329 | A context manager class to run flowRock simulators with correct environmental variables. 330 | """ 331 | 332 | def __init__(self, filename): 333 | """ 334 | 335 | - filename: dummy run file 336 | 337 | Changelog 338 | --------- 339 | - KF 30/10-19 340 | """ 341 | self.filename = filename 342 | 343 | def __enter__(self): 344 | """ 345 | Method that is run when class is initiated by a 'with'-statement 346 | 347 | Changelog 348 | --------- 349 | - KF 30/10-19 350 | """ 351 | # Append if environment variable already exist, or generate it if not. 352 | # We also save all environment variables that we intend to alter, so we can restore them when closing the 353 | # context manager class 354 | 355 | # Save Process context variable to restore later 356 | self.ctx = ctx._default_context 357 | 358 | # Change context to 'spawn' to ensure that any use of Process inside the 'with'-statement will initialize 359 | # with the newly set environment variables. (The default, 'fork', context only copy its 360 | # parent environment variables without taking into account changes made after a Python program is 361 | # initialized) 362 | ctx._default_context = (ctx.DefaultContext(ctx._concrete_contexts['spawn'])) 363 | 364 | # Return self 365 | return self 366 | 367 | def __exit__(self, exc_typ, exc_val, exc_trb): 368 | """ 369 | Method that is run when 'with'-statement closes. Here, we reset environment variables and Process context to 370 | what is was set to before the 'with'-statement. Input here in this method are required to work in 371 | 'with'-statement. 372 | 373 | Changelog 374 | --------- 375 | - ST 25/10-18 376 | """ 377 | # Reset PATH and LD_LIBRARY_PATH to what they were before our intervention. If they were not set we delete 378 | # them from the environment variables 379 | 380 | # Reset Process context 381 | ctx._default_context = self.ctx 382 | 383 | member = False 384 | 385 | if len(self.filename.split(os.sep)) == 1: 386 | if self.filename in os.listdir(): 387 | member = True 388 | else: 389 | if self.filename.split(os.sep)[1] in os.listdir(self.filename.split(os.sep)[0]): 390 | member = True 391 | 392 | if member == False: 393 | sys.exit(1) 394 | 395 | return False 396 | 397 | 398 | class EclipseRunEnvironment: 399 | """ 400 | A context manager class to run eclipse simulators with correct environmental variables. 401 | """ 402 | 403 | def __init__(self, filename): 404 | """ 405 | input 406 | filename: eclipse run file, needed to check for errors (string) 407 | 408 | Changelog 409 | --------- 410 | - KF 30/10-19 411 | """ 412 | self.filename = filename 413 | 414 | def __enter__(self): 415 | """ 416 | Method that is run when class is initiated by a 'with'-statement 417 | 418 | Changelog 419 | --------- 420 | - KF 30/10-19 421 | """ 422 | # Append if environment variable already exist, or generate it if not. 423 | # We also save all environment variables that we intend to alter, so we can restore them when closing the 424 | # context manager class 425 | 426 | # Save Process context variable to restore later 427 | self.ctx = ctx._default_context 428 | 429 | # Change context to 'spawn' to ensure that any use of Process inside the 'with'-statement will initialize 430 | # with the newly set environment variables. (The default, 'fork', context only copy its 431 | # parent environment variables without taking into account changes made after a Python program is 432 | # initialized) 433 | ctx._default_context = (ctx.DefaultContext(ctx._concrete_contexts['spawn'])) 434 | 435 | # Return self 436 | return self 437 | 438 | def __exit__(self, exc_typ, exc_val, exc_trb): 439 | """ 440 | Method that is run when 'with'-statement closes. Here, we reset environment variables and Process context to 441 | what is was set to before the 'with'-statement. Input here in this method are required to work in 442 | 'with'-statement. 443 | 444 | Changelog 445 | --------- 446 | - ST 25/10-18 447 | """ 448 | # Reset PATH and LD_LIBRARY_PATH to what they were before our intervention. If they were not set we delete 449 | # them from the environment variables 450 | 451 | # Reset Process context 452 | ctx._default_context = self.ctx 453 | 454 | error_dict = {} 455 | 456 | with open(self.filename + '.ECLEND', 'r') as f: 457 | txt = [value.strip() for value in (f.read()).split('\n')] 458 | 459 | # Search for the text Error Summary which starts the error summary section 460 | for j in range(0, len(txt)): 461 | if txt[j] == 'Error summary': 462 | for k in range(1, 6): 463 | tmp_line = txt[j + k].split(' ') 464 | # store the error statistics as elements in a dictionary 465 | error_dict[tmp_line[0]] = float(tmp_line[-1]) 466 | # If there are no errors the run was a success. If 'Error summary' cannot be found the run has 467 | # not finished. 468 | if len(error_dict) > 0: 469 | if error_dict['Errors'] > 0: 470 | print('\n\033[1;31mERROR: RUN has failed with {} errors!\033[1;m'.format( 471 | error_dict['Errors'])) 472 | sys.exit(1) 473 | 474 | # Return False (exit 0?) 475 | return False 476 | -------------------------------------------------------------------------------- /src/subsurface/multphaseflow/misc/grid/cornerpoint.py: -------------------------------------------------------------------------------- 1 | """Common functionality for visualization of corner-point grids. 2 | 3 | import pyresito.grid.cornerpoint as cp 4 | """ 5 | import itertools as it 6 | import logging 7 | import numpy as np 8 | import numpy.ma as ma 9 | 10 | 11 | # add a valid log in case we are not run through the main program which 12 | # sets up one for us 13 | log = logging.getLogger(__name__) # pylint: disable=invalid-name 14 | log.addHandler(logging.NullHandler()) 15 | 16 | 17 | def scatter(cell_field): 18 | """\ 19 | Duplicate all items in every dimension. 20 | 21 | Use this method to duplicate values associated with each cell to 22 | each of the corners in the cell. 23 | 24 | :param cell_field: Property per cell in the grid 25 | :type cell_field: :class:`numpy.ndarray`, shape = (nk, nj, ni) 26 | :return: Property per corner in the cube 27 | :rtype: :class:`numpy.ndarray`, shape = (nk, 2, nj, 2, ni, 2) 28 | 29 | >>> scatter(np.array([[[1, 2], 30 | [3, 4]], 31 | [[5, 6], 32 | [7, 8]]])) 33 | 34 | array([[[[[[1, 1], [2, 2]], 35 | [[1, 1], [2, 2]]], 36 | [[[3, 3], [4, 4]], 37 | [[3, 3], [4, 4]]]], 38 | 39 | [[[[1, 1], [2, 2]], 40 | [[1, 1], [2, 2]]], 41 | [[[3, 3], [4, 4]], 42 | [[3, 3], [4, 4]]]]], 43 | 44 | [[[[[5, 5], [6, 6]], 45 | [[5, 5], [6, 6]]], 46 | [[[7, 7], [8, 8]], 47 | [[7, 7], [8, 8]]]], 48 | 49 | [[[[5, 5], [6, 6]], 50 | [[5, 5], [6, 6]]], 51 | [[[7, 7], [8, 8]], 52 | [[7, 7], [8, 8]]]]]]) 53 | """ 54 | # get the dimensions of the cube in easily understood aliases 55 | nk, nj, ni = cell_field.shape # pylint: disable=invalid-name 56 | 57 | # create an extra dimension so that we can duplicate individual values 58 | flat = np.reshape(cell_field, (nk, nj, ni, 1)) 59 | 60 | # duplicate along each of the axis 61 | dup_i = np.tile(flat, (1, 1, 1, 2)) 62 | dup_j = np.tile(dup_i, (1, 1, 2, 1)) 63 | dup_k = np.tile(dup_j, (1, 2, 1, 1)) 64 | 65 | # reformat to a cube with the appropriate dimensions 66 | corn_field = np.reshape(dup_k, (nk, 2, nj, 2, ni, 2)) 67 | return corn_field 68 | 69 | 70 | def inner_dup(pillar_field): 71 | """Duplicate all inner items in both dimensions. 72 | 73 | Use this method to duplicate values associated with each pillar to 74 | the corners on each side(s) of the pillar; four corners for all 75 | interior pillars, two corners for all pillars on the rim and only 76 | one (element) corner for those pillars that are on the grid corners. 77 | 78 | :param pillar_field: Property per pillar in the grid 79 | :type pillar_field: :class:`numpy.ndarray`, shape=(m+1, n+1) 80 | :returns: Property per corner in a grid plane 81 | :rtype: :class:`numpy.ndarray`, shape=(2*m, 2*n)) 82 | 83 | >>> inner_dup(np.array ([[1, 2, 3], 84 | [4, 5, 6], 85 | [7, 8, 9]])) 86 | array([[1, 2, 2, 3], 87 | [4, 5, 5, 6], 88 | [4, 5, 5, 6], 89 | [7, 8, 8, 9]]) 90 | """ 91 | # extract the inner horizontal part of the plane 92 | horz_part = pillar_field[:, 1:-1] 93 | 94 | # tile it to a separate plane 95 | horz_dupd = np.tile(horz_part, (2, 1, 1)) 96 | 97 | # shift the tile to the end so it can be rolled 98 | # into the second dimension 99 | horz_shft = np.transpose(horz_dupd, (1, 2, 0)) 100 | 101 | # roll this into the second dimension 102 | horz_roll = np.reshape(horz_shft, 103 | (horz_shft.shape[0], 104 | horz_shft.shape[1] * 2)) 105 | 106 | # add back the first and last column 107 | horz = np.column_stack([pillar_field[:, 0], 108 | horz_roll, 109 | pillar_field[:, -1]]) 110 | 111 | # extract the inner vertical part of the plane 112 | vert_part = horz[1:-1, :] 113 | 114 | # tile it to a separate plane 115 | vert_dupd = np.tile(vert_part, (1, 1, 2)) 116 | 117 | # roll this into the first dimension 118 | vert_roll = np.reshape(vert_dupd, 119 | (vert_dupd.shape[1] * 2, 120 | vert_dupd.shape[2] // 2)) 121 | 122 | # add back the first and last row 123 | result = np.vstack([horz[0, :], 124 | vert_roll, 125 | horz[-1, :]]) 126 | return result 127 | 128 | 129 | def elem_vtcs_ndcs(nk, nj, ni): # pylint: disable=invalid-name 130 | """List zcorn indices used by every element in an nk*nj*ni grid 131 | 132 | :param nk: Number of layers in Z direction 133 | :type nk: int 134 | :param nj: Number of elements in the Y direction 135 | :type nj: int 136 | :param ni: Number of elements in the X direction 137 | :type ni: int 138 | :returns: Zero-based indices for the hexahedral element corners 139 | :rtype: :class:`numpy.ndarray`, shape=(nk*nj*ni, 8), dtype=int 140 | """ 141 | # hex_perm is the order a hexahedron should be specified to the 142 | # gridding engine (it is the same for VTK and Ensight Gold formats) 143 | # relative to the order they are in the Eclipse format. the latter 144 | # four is listed first because we turn the z order around with a 145 | # transform. 146 | # local indices: 0, 1, 2, 3, 4, 5, 6, 7 147 | hex_perm = np.array([4, 5, 7, 6, 0, 1, 3, 2], dtype=int) 148 | 149 | # kji is the global (k, j, i) index for every element; we tile 150 | # this into 8 corners per element, with 3 indices per corner; 151 | # this this matrix contains repeats of 8 identical permutations 152 | # of the values 0..(ni-1), 0..(nj-1) and 0..(nk-1) 153 | kji = np.array(list(it.product(range(nk), 154 | range(nj), 155 | range(ni)))) 156 | kji = np.reshape(np.tile(kji, [1, hex_perm.shape[0]]), [-1, 3]) 157 | 158 | # bfr is the local (bottom, front, right) index for every corner; 159 | # this is a block of 8 local corners which are picked out of the 160 | # zcorn matrix to then correspond with the gridding engines order. 161 | # we tile this block for every element 162 | bfr = np.array(list(it.product([0, 1], repeat=3)))[hex_perm, :] 163 | bfr = np.tile(bfr, [nk*nj*ni, 1]) 164 | 165 | # calculate running number for every corner, combining the element 166 | # indices kji with the local corner indices bfr. the zcorn hypercube 167 | # has dimensions nk * 2 * nj * 2 * ni * 2; the indexing is simply a 168 | # flattened view of this hypercube. 169 | ndx = (((2*kji[:, 0] + bfr[:, 0]) * 2*nj + 170 | (2*kji[:, 1] + bfr[:, 1])) * 2*ni + 171 | 2*kji[:, 2] + bfr[:, 2]) 172 | 173 | # we then collect the indices so that we get 8 of them (all those that 174 | # belongs to the same element) on a row 175 | ndx = np.reshape(ndx, [-1, hex_perm.shape[0]]) 176 | return ndx 177 | 178 | 179 | # pylint: disable=invalid-name, multiple-statements, too-many-locals 180 | def corner_coordinates(coord, zcorn): 181 | """Generate (x, y, z) coordinates for each corner-point. 182 | 183 | :param coord: Pillar geometrical information 184 | :type coord: :class:`numpy.ndarray`, shape=(nj+1, ni+1, 2, 3) 185 | :param zcorn: Depth values along each pillar 186 | :type zcorn: :class:`numpy.ndarray`, shape=(nk, 2, nj, 2, ni, 2) 187 | :returns: Coordinate values for each corner 188 | :rtype: :class:`numpy.ndarray`, shape=(3, nk*2*nj*2*ni*2) 189 | """ 190 | # indices to treat the pillar matrix as a record 191 | X = 0 192 | Y = 1 193 | Z = 2 194 | START = 0 195 | END = 1 196 | 197 | # calculate depth derivatives for the pillar slope 198 | dx = coord[:, :, END, X] - coord[:, :, START, X] 199 | dy = coord[:, :, END, Y] - coord[:, :, START, Y] 200 | dz = coord[:, :, END, Z] - coord[:, :, START, Z] 201 | 202 | # make the pillar information compatible with a plane of corners, 203 | # having a singleton dimension at the front (instead tiling 2*nk) 204 | x0 = inner_dup(coord[:, :, START, X])[None, :, :] 205 | y0 = inner_dup(coord[:, :, START, Y])[None, :, :] 206 | z0 = inner_dup(coord[:, :, START, Z])[None, :, :] 207 | dxdz = inner_dup(dx / dz)[None, :, :] 208 | dydz = inner_dup(dy / dz)[None, :, :] 209 | 210 | # infer the grid size from the dimensions of coord 211 | nj = coord.shape[0] - 1 212 | ni = coord.shape[1] - 1 213 | 214 | # make the formal dimensions of the depths compatible with the plane 215 | # of vectors created from the pillars; notice that the first dimension 216 | # is not singular 217 | z = np.reshape(zcorn, (-1, nj*2, ni*2)) 218 | 219 | # calculate the point in the plane where the horizon intersect with the 220 | # pillar; we get the (x, y)-coordinates for each corner. notice that the 221 | # difference z - z0 is for each point, whereas dz is for the pillar! 222 | x = (z - z0) * dxdz + x0 223 | y = (z - z0) * dydz + y0 224 | 225 | # reformat the coordinates into the final coordinates 226 | xyz = np.vstack([np.reshape(x, (1, -1)), 227 | np.reshape(y, (1, -1)), 228 | np.reshape(z, (1, -1))]) 229 | return xyz 230 | 231 | 232 | # Enumeration of the dimensions in a point tuple 233 | Dim = type('Dim', (), { 234 | 'X': 0, 235 | 'Y': 1, 236 | 'Z': 2, 237 | }) 238 | 239 | 240 | # Enumeration of the faces of a hexahedron. The contents are the local 241 | # indices in each row of 8 corners that are set up for the elements by 242 | # the elem_vtcs_ndcs function. (The indices here are the numbers that 243 | # are in the comment "local indices" above the hex_perm selector) 244 | Face = type('Face', (), { 245 | 'DOWN': np.array([0, 1, 2, 3]), 246 | 'UP': np.array([4, 5, 6, 7]), 247 | 'FRONT': np.array([4, 7, 3, 0]), 248 | 'BACK': np.array([5, 6, 2, 1]), 249 | 'LEFT': np.array([7, 6, 2, 3]), 250 | 'RIGHT': np.array([4, 5, 1, 0]), 251 | 'ALL': np.array([0, 1, 2, 3, 4, 5, 6, 7]), 252 | }) 253 | 254 | 255 | def cp_cells(grid, face): 256 | """ 257 | Make a cell array from a cornerpoint grid. The cells will be in the 258 | same order as the Cartesian enumeration of the grid. 259 | 260 | :param grid: Pillar coordinates and corner depths 261 | :type grid: dict, with 'coord' and 'zcorn' properties 262 | :param face: Which face that should be extracted, e.g. Face.UP 263 | :type face: Face enum 264 | :returns: Set of geometrical objects that can be sent to rendering 265 | :rtype: dict with 'points', shape (nverts, 3), and 'cells', shape 266 | (nelems, ncorns), where ncorns is either 8 (hexahedron 267 | volume or 4 (quadrilateral face), depending on the face 268 | parameter. 269 | """ 270 | src = {} 271 | 272 | log.debug("Generating points for corner depths") 273 | # notice that VTK wants shape (nverts, 3), where as the code sets up 274 | # for Ensight format which is (3, nverts). 275 | src['points'] = corner_coordinates(grid['COORD'], 276 | grid['ZCORN']).T.copy() 277 | 278 | # order of the dimensions are different from the structure to the call 279 | ni, nj, nk = grid['DIMENS'] 280 | 281 | # extract only the columns of the face we want to show. the shape was 282 | # originally (nelem, 8). copy is necessary to get a contiguous array 283 | # for VTK 284 | log.debug("Generating cells") 285 | src['cells'] = elem_vtcs_ndcs(nk, nj, ni)[:, face].copy() 286 | return src 287 | 288 | 289 | def cell_filter(grid, func): 290 | """Create a filter for a specific grid. 291 | 292 | :param grid: Grid structure that should be filtered 293 | :type grid: dict 294 | :param func: Lambda function that takes i, j, k indices (one-based) 295 | and returns boolean for whether the cells should be 296 | included or not. The function should be vectorized. 297 | :type func: Callable[(int, int, int), bool] 298 | 299 | >>> layr = cell_filter (grid, lamba i, j, k: np.greater_equal (k, 56)) 300 | """ 301 | # extract the dimensions; notice that the i-dimensions is first 302 | # in this list, since it is directly from the grid 303 | ni, nj, nk = grid['DIMENS'] # pylint: disable=invalid-name 304 | 305 | # setup a grid of the i, j and k address for each of the cells; 306 | # notice that now the order of the dimensions are swapped so that 307 | # they fit with the memory layout of a loaded Numpy array 308 | kji = np.mgrid[1:(nk+1), 1:(nj+1), 1:(ni+1)] 309 | 310 | # call the filter function on all these addresses, and simply 311 | # return the boolean array of those 312 | filter_flags = func(kji[2], kji[1], kji[0]) 313 | masked = filter_flags.astype(np.bool) 314 | 315 | # get the mask of active cells, and combine this with the masked 316 | # cells from the filter, giving us a flag for all visible nodes 317 | active = grid['ACTNUM'] 318 | visible = np.logical_and(active, masked) 319 | 320 | return visible 321 | 322 | 323 | def face_coords(grid): 324 | """Get (x, y, z) coordinates for each corner-point. 325 | 326 | :param grid: Cornerpoint-grid 327 | :type grid: dict 328 | :returns: Coordinate values for each corner. Use the Face enum to index 329 | the first dimension, k, j, i coordinates to index the next 330 | three, and Dim enum to index the last dimension. 331 | Note that the first point in a face is not necessarily the 332 | point that is closest to the origin of the grid. 333 | :rtype: :class:`numpy.ndarray`, shape = (8, nk, nj, ni, 3) 334 | 335 | >>> import numpy as np 336 | >>> import pyresito.io.ecl as ecl 337 | >>> import pyresito.grid.cornerpoint as cp 338 | >>> case = ecl.EclipseCase ("FOO") 339 | >>> coord_fijkd = cp.face_coords (case.grid ()) 340 | >>> # get the midpoint of the upper face in each cell 341 | >>> up_mid = np.average (coord_fijkd [cp.Face.UP, :, :, :, :], axis = 0) 342 | """ 343 | # get coordinates in native corner-point format 344 | xyz = corner_coordinates(grid['COORD'], grid['ZCORN']) 345 | 346 | # get extent of grid 347 | ni, nj, nk = grid['DIMENS'] 348 | 349 | # break up the latter dimension into a many-dimensional hypercube; this 350 | # is an inexpensive operation since it won't have to reshuffle the memory 351 | xyz = np.reshape(xyz, (3, nk, 2, nj, 2, ni, 2)) 352 | 353 | # move all the dimensions local within an element to the front 354 | xyz = np.transpose(xyz, (2, 4, 6, 1, 3, 5, 0)) 355 | 356 | # coalesce the local dimensions so that they end up in one dimension 357 | # which can be indexed by the Face enum to extract a certain field 358 | xyz = np.reshape(xyz, (8, nk, nj, ni, 3)) 359 | 360 | return xyz 361 | 362 | 363 | def horizon(grid, layer=0, top=True): 364 | """Extract the points that are in a certain horizon and average them so 365 | that the result is per cell and not per pillar. 366 | 367 | :param grid: Grid structure 368 | :type grid: dict 369 | :param layer: The K index of the horizon. Default is the layer at the top. 370 | :type layer: int 371 | :param top: Whether the top face should be exported. If this is False, 372 | then the bottom face is exported instead. 373 | :type top: bool 374 | :returns: Depth at the specified horizon for each cell center 375 | :rtype: :class:`numpy.ma.array`, shape = (nk, nj, ni), 376 | dtype = numpy.float64 377 | """ 378 | # get the dimensions of the grid. notice that this array is always given 379 | # in Fortran order (since Eclipse works that way) and not in native order 380 | num_i, num_j, _ = grid['DIMENS'] 381 | 382 | # zcorn is nk * (up,down) * nj * (front,back) * ni * (left,right). we first 383 | # project the particular layer and face that we want to work with, ending 384 | # up with four corners for each cell. 385 | vertical = 0 if top else 1 386 | corners = grid['ZCORN'][layer, vertical, :, :, :, :] 387 | 388 | # move the second and fourth dimension (front/back and left/right) to the 389 | # back and collapse them into one dimension, meaning that we get 390 | # (nj, ni, 4). then take the average across this last dimension, ending up 391 | # with an (nj, ni) grid, which is what we return 392 | heights = np.average(np.reshape(np.transpose( 393 | corners, axes=(0, 2, 1, 3)), (num_j, num_i, 2*2)), axis=2) 394 | 395 | # if there are any inactive elements, then mask out the elevation at that 396 | # spot (it is not really a part of the grid) 397 | actnum = grid['ACTNUM'][layer, :, :] 398 | return ma.array(data=heights, mask=np.logical_not(actnum)) 399 | 400 | 401 | def _reduce_corners(plane, red_op): 402 | """ 403 | :param plane: Z-coordinates for a specific horizon in the grid 404 | :type plane: :class:`numpy.ndarray`, shape = (nj, 2, ni, 2) 405 | :param red_op: How coordinates are merged (reduction operator): either 406 | numpy.minimum or np.maximum, depending on top or bottom 407 | :type red_op: :class:`numpy.ufunc` 408 | :returns: Extremal value of each point around the corners. 409 | :rtype: :class:`numpy.ndarray`, shape = (nj+1, ni+1) 410 | 411 | >> plane = np.reshape (np.arange (36) + 1, (3, 2, 3, 2)) 412 | >> _reduce_corners (plane, np.minimum) 413 | """ 414 | # constants 415 | NORTH = 1 416 | SOUTH = 0 417 | EAST = 1 418 | WEST = 0 419 | 420 | # get dimensions of the domain 421 | nj, _, ni, _ = plane.shape 422 | 423 | # allocate output memory for all pillars 424 | out = np.empty((nj + 1, ni + 1), dtype=np.float64) 425 | 426 | # views into the original plane, getting a specific corner in every cell. 427 | # these views then have dimensions (nj, ni) 428 | nw = plane[:, NORTH, :, WEST] 429 | ne = plane[:, NORTH, :, EAST] 430 | sw = plane[:, SOUTH, :, WEST] 431 | se = plane[:, SOUTH, :, EAST] 432 | 433 | # four corners of the output grid only have a single value. the views have 434 | # indices 0..n-1, the output array have indices 0..n 435 | out[0, 0] = sw[0, 0] 436 | out[nj, 0] = nw[nj-1, 0] 437 | out[0, ni] = se[0, ni-1] 438 | out[nj, ni] = ne[nj-1, ni-1] 439 | 440 | # four edges contains values from two windows; first two horizontal edges, 441 | # (varying along i), then two vertical edges (varying along j). recall that 442 | # *ranges* in Python have inclusive start, exclusive end. 443 | out[0, 1:ni] = red_op(sw[0, 1:ni], se[0, 0:ni-1]) 444 | out[nj, 1:ni] = red_op(nw[nj-1, 1:ni], ne[nj-1, 0:ni-1]) 445 | out[1:nj, 0] = red_op(nw[0:nj-1, 0], sw[1:nj, 0]) 446 | out[1:nj, ni] = red_op(ne[0:nj-1, ni-1], se[1:nj, ni-1]) 447 | 448 | # interior have two nested reduction operations 449 | out[1:nj, 1:ni] = red_op( 450 | red_op(nw[0:nj-1, 1:ni], sw[1:nj, 1:ni]), 451 | red_op(ne[0:nj-1, 0:ni-1], se[1:nj, 0:ni-1])) 452 | 453 | return out 454 | 455 | 456 | def horizon_pillars(grid, layer=0, top=True): 457 | """Extract heights where a horizon crosses the pillars. 458 | 459 | :param grid: Grid structure, containing both COORD and ZCORN properties. 460 | :type grid: dict 461 | :param layer: The K index of the horizon. Default is the layer at the top. 462 | :type layer: int 463 | :param top: Whether the top face should be exported. If this false is 464 | False, then the bottom face is exported instead. 465 | :type top: bool 466 | :returns: Heights of the horizon at each pillar, in the same format as 467 | the COORD matrix. 468 | :rtype: :class:`numpy.ndarray`, shape = (nj+1, ni+1, 2, 3) 469 | """ 470 | # NumPy's average operations finds the average within arrays, but we want 471 | # an operation that can take the average across two arrays 472 | def avg_op(a, b): 473 | return 0.5 * (a + b) 474 | 475 | # zcorn is nk * (up,down) * nj * (front,back) * ni * (left,right). we first 476 | # project the particular layer and face that we want to work with, ending 477 | # up with four corners for each cell. take the average of the heights that 478 | # are hinged up on each pillar to get a "smooth" surface. (this will not be 479 | # the same surface that the cornerpoint grid was created from). 480 | vertical = 0 if top else 1 481 | points = _reduce_corners(grid['ZCORN'][layer, vertical, :, :, :, :], 482 | avg_op) 483 | return points 484 | 485 | 486 | def snugfit(grid): 487 | """Create coordinate pillars that matches exactly the top and bottom 488 | horizon of the grid cells. 489 | 490 | This version assumes that the pillars in the grid are all strictly 491 | vertical, i.e. the x- and y-coordinates will not be changed. 492 | 493 | :param grid: Grid structure, containing both COORD and ZCORN properties. 494 | :type grid: dict 495 | :returns: Pillar coordinates, in the same format as the COORD matrix. 496 | Note that a new matrix is returned, the original grid is not 497 | altered/updated. 498 | :rtype: :class:`numpy.ndarray`, shape = (nj+1, ni+1, 2, 3) 499 | """ 500 | # placement in the plane of each pillar is unchanged 501 | x = grid['COORD'][:, :, 0, 0] 502 | y = grid['COORD'][:, :, 0, 1] 503 | 504 | # get implicit dimension of grid 505 | njp1, nip1 = x.shape 506 | 507 | # get new top and bottom from the z-coordinates; smaller z is shallower 508 | top = _reduce_corners(grid['ZCORN'][0, 0, :, :, :, :], np.minimum) 509 | btm = _reduce_corners(grid['ZCORN'][-1, 1, :, :, :, :], np.maximum) 510 | 511 | # combine coordinates to a pillar grid with new z-coordinates 512 | coord = np.reshape(np.dstack(( 513 | x.ravel(), y.ravel(), top.ravel(), 514 | x.ravel(), y.ravel(), btm.ravel())), (njp1, nip1, 2, 3)) 515 | 516 | return coord 517 | 518 | 519 | def bounding_box(corn, filtr): 520 | """\ 521 | Bounding box of the grid. This function will always assume that the grid 522 | is aligned with the geographical axes. 523 | 524 | :param corn: Coordinate values for each corner. This matrix can be 525 | constructed with the `corner_coordinates` function. 526 | :type corn: :class:`numpy.ndarray`, shape=(3, nk*2*nj*2*ni*2) 527 | :param filtr: Active corners; use scatter of ACTNUM if no filtering 528 | :type filtr: :class:`numpy.ndarray`, shape = (nk, 2, nj, 2, ni, 2), 529 | dtype = numpy.bool 530 | :return: Bottom front right corner and top back left corner. Since 531 | the matrix is returned with C ordering, it is specified the 532 | opposite way of what is natural for mathematical matrices. 533 | :rtype: :class:`numpy.ndarray`, shape = (2, 3), dtype = np.float64 534 | 535 | >>> corn = corner_coordinates(grid['COORD'], grid['ZCORN']) 536 | >>> bbox = bounding_box(corn, scatter(grid['ACTNUM'])) 537 | >>> p, q = bbox[0, :], bbox[1, :] 538 | >>> diag = np.sqrt(np.dot(q - p, q - p)) 539 | """ 540 | # scatter the filter mask from each cell to its corners 541 | mask = np.logical_not(filtr).ravel() 542 | 543 | # build arrays of each separate coordinate based on its inclusion 544 | x_vals = ma.array(data=corn[0, :], mask=mask) 545 | y_vals = ma.array(data=corn[1, :], mask=mask) 546 | z_vals = ma.array(data=corn[2, :], mask=mask) 547 | 548 | # construct bounding box that includes all coordinates in visible grid 549 | bbox = np.array([[np.min(x_vals), np.min(y_vals), np.min(z_vals)], 550 | [np.max(x_vals), np.max(y_vals), np.max(z_vals)]], 551 | dtype=corn.dtype) 552 | return bbox 553 | 554 | 555 | def mass_center(corn, filtr): 556 | """\ 557 | Mass center of the grid. This function will always assume that the density 558 | is equal throughout the field. 559 | 560 | :param corn: Coordinate values for each corner. This matrix can be 561 | constructed with the `corner_coordinates` function. 562 | :type corn: :class:`numpy.ndarray`, shape=(3, nk*2*nj*2*ni*2) 563 | :param filtr: Active corners; use scatter of ACTNUM if no filtering 564 | :type filtr: :class:`numpy.ndarray`, shape = (nk, 2, nj, 2, ni, 2), 565 | dtype = numpy.bool 566 | :return: Center of mass. This should be the focal point of the grid. 567 | :rtype: :class:`numpy.ndarray`, shape = (3,), dtype = np.float64 568 | 569 | >>> corn = cp.corner_coordinates(grid['COORD'], grid['ZCORN']) 570 | >>> focal_point = cp.mass_center(corn, cp.scatter(grid['ACTNUM'])) 571 | """ 572 | # scatter the filter mask from each cell to its corners 573 | mask = np.logical_not(filtr).ravel() 574 | 575 | # build arrays of each separate coordinate based on its inclusion 576 | x_vals = ma.array(data=corn[0, :], mask=mask) 577 | y_vals = ma.array(data=corn[1, :], mask=mask) 578 | z_vals = ma.array(data=corn[2, :], mask=mask) 579 | 580 | # use this as a coarse approximation to find the element center 581 | center = np.array([np.average(x_vals), 582 | np.average(y_vals), 583 | np.average(z_vals)], dtype=corn.dtype) 584 | return center 585 | -------------------------------------------------------------------------------- /src/subsurface/rockphysics/standardrp.py: -------------------------------------------------------------------------------- 1 | """Descriptive description.""" 2 | 3 | __author__ = 'TM' 4 | 5 | # standardrp.py 6 | import numpy as np 7 | import sys 8 | import multiprocessing as mp 9 | # internal load 10 | from misc.system_tools.environ_var import OpenBlasSingleThread # Single threaded OpenBLAS runs 11 | 12 | 13 | class elasticproperties: 14 | """ 15 | Calculate elastic properties from standard 16 | rock-physics models, specifically following Batzle 17 | and Wang, Geophysics, 1992, for fluid properties, and 18 | Report 1 in Abul Fahimuddin's thesis at Universty of 19 | Bergen (2010) for other properties. 20 | 21 | Examples 22 | -------- 23 | >>> porosity = 0.2 24 | ... pressure = 5 25 | ... phases = ["Oil","Water"] 26 | ... saturations = [0.3, 0.5] 27 | ... 28 | ... satrock = Elasticproperties() 29 | ... satrock.calc_props(phases, saturations, pressure, porosity) 30 | """ 31 | 32 | def __init__(self, input_dict): 33 | self.dens = None 34 | self.bulkmod = None 35 | self.shearmod = None 36 | self.bulkvel = None 37 | self.shearvel = None 38 | self.bulkimp = None 39 | self.shearimp = None 40 | # The overburden for each grid cell must be 41 | # specified as values on an .npz-file whose 42 | # name is given in input_dict. 43 | self.input_dict = input_dict 44 | self._extInfoInputDict() 45 | 46 | def _extInfoInputDict(self): 47 | # The key word for the file name in the 48 | # dictionary must read "overburden" 49 | if 'overburden' in self.input_dict: 50 | obfile = self.input_dict['overburden'] 51 | npzfile = np.load(obfile) 52 | # The values of overburden must have been 53 | # stored on file using: 54 | # np.savez(, 55 | # obvalues=) 56 | self.overburden = npzfile['obvalues'] 57 | npzfile.close() 58 | if 'baseline' in self.input_dict: 59 | self.baseline = self.input_dict['baseline'] # 4D baseline 60 | if 'parallel' in self.input_dict: 61 | self.parallel = self.input_dict['parallel'] 62 | 63 | def _filter(self): 64 | bulkmod = self.bulkimp 65 | self.bulkimp = bulkmod.flatten() 66 | 67 | def setup_fwd_run(self, state): 68 | """ 69 | Setup the input parameters to be used in the PEM simulator. Parameters can be a an ensemble or a single array. 70 | State is set as an attribute of the simulator, and the correct value is determined in self.pem.calc_props() 71 | 72 | Parameters 73 | ---------- 74 | state : dict 75 | Dictionary of input parameters or states. 76 | 77 | Changelog 78 | --------- 79 | - KF 11/12-2018 80 | """ 81 | # self.inv_state = {} 82 | # list_pem_param =[el for el in [foo for foo in self.pem['garn'].keys()] + [foo for foo in self.filter.keys()] + 83 | # [foo for foo in self.__dict__.keys()]] 84 | 85 | # list_tot_param = state.keys() 86 | # for param in list_tot_param: 87 | # if param in list_pem_param or (param.split('_')[-1] in ['garn', 'rest']): 88 | # self.inv_state[param] = state[param] 89 | 90 | pass 91 | 92 | def calc_props(self, phases, saturations, pressure, 93 | porosity, dens = None, wait_for_proc=None, ntg=None, Rs=None, press_init=None, ensembleMember=None): 94 | ### 95 | # This doesn't initialize for models with no uncertainty 96 | ### 97 | # # if some PEM properties have uncertainty, set the correct value 98 | # if ensembleMember is not None: 99 | # for pem_state in self.__dict__.keys(): # loop over all possible pem vaules 100 | # if pem_state is not 'inv_state': # do not alter the ensemble 101 | # if type(eval('self.{}'.format(pem_state))) is dict: 102 | # for el in eval('self.{}'.format(pem_state)).keys(): 103 | # if type(eval('self.{}'.format(pem_state))[el]) is dict: 104 | # for param in eval('self.{}'.format(pem_state))[el].keys(): 105 | # if param in self.inv_state: 106 | # eval('self.{}'.format(pem_state))[el][param]=\ 107 | # self.inv_state[param][:, ensembleMember] 108 | # elif param + '_' + el in self.inv_state: 109 | # eval('self.{}'.format(pem_state))[el][param] = \ 110 | # self.inv_state[param+'_' + el][:, ensembleMember] 111 | # else: 112 | # if el in self.inv_state: 113 | # eval('self.{}'.format(pem_state))[el] = self.inv_state[el][:,ensembleMember] 114 | # else: 115 | # if pem_state in self.inv_state: 116 | # setattr(self,pem_state, self.inv_state[pem_state][:,ensembleMember]) 117 | 118 | # Check if the inputs are given as a list (more 119 | # than one phase) or a single input (single 120 | # phase). If single phase input, make the input a 121 | # list with a single entry (s.t. it can be used 122 | # directly with the methods below) 123 | # 124 | if not isinstance(phases, list): 125 | phases = [phases] 126 | if not isinstance(saturations, list): 127 | saturations = [saturations] 128 | if not isinstance(pressure, list) and \ 129 | type(pressure).__module__ != 'numpy': 130 | pressure = [pressure] 131 | if not isinstance(porosity, list) and \ 132 | type(porosity).__module__ != 'numpy': 133 | porosity = [porosity] 134 | # 135 | # Load "overburden" into local variable to 136 | # comply with remaining code parts 137 | overburden = self.overburden 138 | 139 | if press_init is None: 140 | p_init = self.p_init 141 | else: 142 | p_init = press_init 143 | # 144 | poverburden = self.overburden 145 | 146 | # debug 147 | self.pressure = pressure 148 | self.peff = poverburden - pressure 149 | self.porosity = porosity 150 | 151 | # Check that no. of phases is equal to no. of 152 | # entries in saturations list 153 | # 154 | assert (len(saturations) == len(phases)) 155 | # 156 | # Make saturation a Numpy array (so that we 157 | # can easily access the values for each 158 | # phase at one grid cell) 159 | # 160 | # Transpose makes it a no. grid cells x phases 161 | # array 162 | saturations = np.array(saturations).T 163 | # 164 | # Check if we actually inputted saturation values 165 | # for a single grid cell. If yes, we redefine 166 | # saturations to get it on the correct form (no. 167 | # grid cells x phases array). 168 | # 169 | if saturations.ndim == 1: 170 | saturations = \ 171 | np.array([[x] for x in saturations]).T 172 | # 173 | # Loop over all grid cells and calculate the 174 | # various saturated properties 175 | # 176 | self.phases = phases 177 | 178 | self.dens = np.zeros(len(saturations[:, 0])) 179 | self.bulkmod = np.zeros(len(saturations[:, 0])) 180 | self.shearmod = np.zeros(len(saturations[:, 0])) 181 | self.bulkvel = np.zeros(len(saturations[:, 0])) 182 | self.shearvel = np.zeros(len(saturations[:, 0])) 183 | self.bulkimp = np.zeros(len(saturations[:, 0])) 184 | self.shearimp = np.zeros(len(saturations[:, 0])) 185 | 186 | if ntg is None: 187 | ntg = [None for _ in range(len(saturations[:, 0]))] 188 | if Rs is None: 189 | Rs = [None for _ in range(len(saturations[:, 0]))] 190 | if p_init is None: 191 | p_init = [None for _ in range(len(saturations[:, 0]))] 192 | 193 | for i in range(len(saturations[:, 0])): 194 | # 195 | # Calculate fluid properties 196 | # 197 | # set Rs if needed 198 | densf, bulkf = \ 199 | self._fluidprops(self.phases, 200 | saturations[i, :], pressure[i], Rs[i]) 201 | # 202 | denss, bulks, shears = \ 203 | self._solidprops(porosity[i], ntg[i], i) 204 | # 205 | # Calculate dry rock moduli 206 | # 207 | 208 | bulkd, sheard = \ 209 | self._dryrockmoduli(porosity[i], 210 | overburden[i], 211 | pressure[i], bulks, 212 | shears, i, ntg[i], p_init[i], denss, Rs[i], self.phases) 213 | # ------------------------------- 214 | # Calculate saturated properties 215 | # ------------------------------- 216 | # 217 | # Density 218 | # 219 | self.dens[i] = (porosity[i]*densf + (1-porosity[i])*denss) 220 | # 221 | # Moduli 222 | # 223 | self.bulkmod[i] = \ 224 | bulkd + (1 - bulkd/bulks)**2 / \ 225 | (porosity[i]/bulkf + 226 | (1-porosity[i])/bulks - 227 | bulkd/(bulks**2)) 228 | self.shearmod[i] = sheard 229 | 230 | # Velocities (due to bulk/shear modulus being 231 | # in MPa, we multiply by 1000 to get m/s 232 | # instead of km/s) 233 | # 234 | self.bulkvel[i] = \ 235 | 1000*np.sqrt((abs(self.bulkmod[i]) + 236 | 4*self.shearmod[i]/3)/(self.dens[i])) 237 | self.shearvel[i] = \ 238 | 1000*np.sqrt(self.shearmod[i] / 239 | (self.dens[i])) 240 | # 241 | # Impedances (m/s)*(Kg/m3) 242 | # 243 | self.bulkimp[i] = self.dens[i] * \ 244 | self.bulkvel[i] 245 | self.shearimp[i] = self.dens[i] * \ 246 | self.shearvel[i] 247 | 248 | def getMatchProp(self, petElProp): 249 | if petElProp.lower() == 'density': 250 | self.match_prop = self.getDens() 251 | elif petElProp.lower() == 'bulk_modulus': 252 | self.match_prop = self.getBulkMod() 253 | elif petElProp.lower() == 'shear_modulus': 254 | self.match_prop = self.getShearMod() 255 | elif petElProp.lower() == 'bulk_velocity': 256 | self.match_prop = self.getBulkVel() 257 | elif petElProp.lower() == 'shear_velocity': 258 | self.match_prop = self.getShearVel() 259 | elif petElProp.lower() == "bulk_impedance": 260 | self.match_prop = self.getBulkImp() 261 | elif petElProp.lower() == 'shear_impedance': 262 | self.match_prop = self.getShearImp() 263 | else: 264 | print("\nError in getMatchProp method") 265 | print("No model output type selected for " 266 | "data match.") 267 | print("Legal model output types are " 268 | "(case insensitive):") 269 | print("Density, bulk modulus, shear " 270 | "modulus, bulk velocity,") 271 | print("shear velocity, bulk impedance, " 272 | "shear impedance") 273 | sys.exit(1) 274 | return self.match_prop 275 | 276 | def getDens(self): 277 | return self.dens 278 | 279 | def getBulkMod(self): 280 | return self.bulkmod 281 | 282 | def getShearMod(self): 283 | return self.shearmod 284 | 285 | def getBulkVel(self): 286 | return self.bulkvel 287 | 288 | def getShearVel(self): 289 | return self.shearvel 290 | 291 | def getBulkImp(self): 292 | return self.bulkimp 293 | 294 | def getShearImp(self): 295 | return self.shearimp 296 | 297 | def getOverburdenP(self): 298 | return self.overburden 299 | 300 | def getPressure(self): 301 | return self.pressure 302 | 303 | def getPeff(self): 304 | return self.peff 305 | 306 | def getPorosity(self): 307 | return self.porosity 308 | # 309 | # =================================================== 310 | # Fluid properties start 311 | # =================================================== 312 | # 313 | def _fluidprops(self, fphases, fsats, fpress, Rs=None): 314 | # 315 | # Calculate fluid density and bulk modulus 316 | # 317 | # 318 | # Input 319 | # fphases - fluid phases present; Oil 320 | # and/or Water and/or Gas 321 | # fsats - fluid saturation values for 322 | # fluid phases in "fphases" 323 | # fpress - fluid pressure value (MPa) 324 | # Rs - Gas oil ratio. Default value None 325 | 326 | # 327 | # Output 328 | # fdens - density of fluid mixture for 329 | # pressure value "fpress" inherited 330 | # from phaseprops) 331 | # fbulk - bulk modulus of fluid mixture for 332 | # pressure value "fpress" (unit 333 | # inherited from phaseprops) 334 | # 335 | # ----------------------------------------------- 336 | # 337 | fdens = 0.0 338 | fbinv = 0.0 339 | 340 | for i in range(len(fphases)): 341 | # 342 | # Calculate mixture properties by summing 343 | # over individual phase properties 344 | # 345 | pdens, pbulk = self._phaseprops(fphases[i], 346 | fpress, Rs) 347 | fdens = fdens + fsats[i]*abs(pdens) 348 | fbinv = fbinv + fsats[i]/abs(pbulk) 349 | fbulk = 1.0/fbinv 350 | # 351 | return fdens, fbulk 352 | # 353 | # --------------------------------------------------- 354 | # 355 | 356 | def _phaseprops(self, fphase, press, Rs=None): 357 | # 358 | # Calculate properties for a single fluid phase 359 | # 360 | # 361 | # Input 362 | # fphase - fluid phase; Oil, Water or Gas 363 | # press - fluid pressure value (MPa) 364 | # 365 | # Output 366 | # pdens - phase density of fluid phase 367 | # "fphase" for pressure value 368 | # "press" (kg/m³) 369 | # pbulk - bulk modulus of fluid phase 370 | # "fphase" for pressure value 371 | # "press" (MPa) 372 | # 373 | # ----------------------------------------------- 374 | # 375 | if fphase.lower() == "oil": 376 | coeffsrho = np.array([0.8, 829.9]) 377 | coeffsbulk = np.array([10.42, 995.79]) 378 | elif fphase.lower() == "wat": 379 | coeffsrho = np.array([0.3, 1067.3]) 380 | coeffsbulk = np.array([9.0, 2807.6]) 381 | elif fphase.lower() == "gas": 382 | coeffsrho = np.array([4.7, 13.4]) 383 | coeffsbulk = np.array([2.75, 0.0]) 384 | else: 385 | print("\nError in phaseprops method") 386 | print("Illegal fluid phase name.") 387 | print("Legal fluid phase names are (case " 388 | "insensitive): Oil, Wat, and Gas.") 389 | sys.exit(1) 390 | # 391 | # Assume simple linear pressure dependencies. 392 | # Coefficients are inferred from 393 | # plots in Batzle and Wang, Geophysics, 1992, 394 | # (where I set the temperature to be 100 degrees 395 | # Celsius, Note also that they give densities in 396 | # g/cc). The resulting straight lines do not fit 397 | # the data extremely well, but they should 398 | # be sufficiently accurate for the purpose of 399 | # this project. 400 | # 401 | pdens = coeffsrho[0]*press + coeffsrho[1] 402 | pbulk = coeffsbulk[0]*press + coeffsbulk[1] 403 | # 404 | return pdens, pbulk 405 | 406 | # 407 | # ======================= 408 | # Fluid properties end 409 | # ======================= 410 | # 411 | 412 | # 413 | # ========================= 414 | # Solid properties start 415 | # ========================= 416 | # 417 | def _solidprops(self, poro, ntg=None, ind=None): 418 | # 419 | # Calculate bulk and shear solid rock (mineral) 420 | # moduli by averaging Hashin-Shtrikman bounds 421 | # 422 | # 423 | # Input 424 | # poro -porosity 425 | # 426 | # Output 427 | # denss - solid rock density (kg/m³) 428 | # bulks - solid rock bulk modulus (unit 429 | # inherited from hashinshtr) 430 | # shears - solid rock shear modulus (unit 431 | # inherited from hashinshtr) 432 | # 433 | # ----------------------------------------------- 434 | # 435 | # From PetroWiki (kg/m³) 436 | # 437 | densc = 2540 438 | densq = 2650 439 | # 440 | # From "Step 1" of "recipe" in Report 1 in Abul 441 | # Fahimuddin's thesis. 442 | # 443 | vclay = 0.7 - 1.58*poro 444 | # 445 | # Calculate solid rock (mineral) density. (Note 446 | # that this is often termed \rho_dry, and not 447 | # \rho_s) 448 | # 449 | denss = densq + vclay*(densc - densq) 450 | # 451 | # Calculate lower and upper bulk and shear 452 | # Hashin-Shtrikman bounds 453 | # 454 | bulkl, bulku, shearl, shearu = \ 455 | self._hashinshtr(vclay) 456 | # 457 | # Calculate bulk and shear solid rock (mineral) 458 | # moduli as arithmetic means of the respective 459 | # bounds 460 | # 461 | bulkb = np.array([bulkl, bulku]) 462 | shearb = np.array([shearl, shearu]) 463 | bulks = np.mean(bulkb) 464 | shears = np.mean(shearb) 465 | # 466 | return denss, bulks, shears 467 | # 468 | # --------------------------------------------------- 469 | # 470 | 471 | def _hashinshtr(self, vclay): 472 | # 473 | # Calculate lower and upper, bulk and shear, 474 | # Hashin-Shtrikman bounds, utilizing that they 475 | # all have the common mathematical form, 476 | # 477 | # f = a + b/((1/c) + d*(1/e)). 478 | # 479 | # 480 | # Input 481 | # vclay - "volume of clay" 482 | # 483 | # Output 484 | # bulkl - lower bulk Hashin-Shtrikman 485 | # bound (MPa) 486 | # bulku - upper bulk Hashin-Shtrikman 487 | # bound (MPa) 488 | # shearl - lower shear Hashin-Shtrikman 489 | # bound (MPa) 490 | # shearu - upper shear Hashin-Shtrikman 491 | # bound (MPa) 492 | # 493 | # ----------------------------------------------- 494 | # 495 | # From table 1 in Report 1 in Abul Fahimuddin's 496 | # thesis (he used GPa, I use MPa), ("c" for clay 497 | # and "q" for quartz.): 498 | # 499 | bulkc = 14900 500 | bulkq = 37000 501 | shearc = 1950 502 | shearq = 44000 503 | # 504 | # Calculate quantities common for both bulk and 505 | # shear formulas 506 | # 507 | lb = 1 - vclay 508 | ub = vclay 509 | le = bulkc + 4*shearc/3 510 | ue = bulkq + 4*shearq/3 511 | # 512 | # Calculate quantities common only for bulk 513 | # formulas 514 | # 515 | bld = vclay 516 | bud = 1 - vclay 517 | blc = bulkq - bulkc 518 | buc = bulkc - bulkq 519 | # 520 | # Calculate quantities common only for shear 521 | # formulas 522 | # 523 | sld = 2*vclay*(bulkc + 2*shearc)/(5*shearc) 524 | sud = 2*(1 - vclay)*(bulkq + 2*shearq)/(5*shearq) 525 | slc = shearq - shearc 526 | suc = shearc - shearq 527 | # 528 | # Calculate bounds utilizing generic formula; 529 | # f = a + b/((1/c) + d*(1/e)). 530 | # 531 | # Lower bulk 532 | # 533 | bulkl = self._genhashinshtr(bulkc, lb, blc, bld, 534 | le) 535 | # 536 | # Upper bulk 537 | # 538 | bulku = self._genhashinshtr(bulkq, ub, buc, bud, 539 | ue) 540 | # 541 | # Lower shear 542 | # 543 | shearl = self._genhashinshtr(shearc, lb, slc, 544 | sld, le) 545 | # 546 | # Upper shear 547 | # 548 | shearu = self._genhashinshtr(shearq, ub, suc, 549 | sud, ue) 550 | # 551 | return bulkl, bulku, shearl, shearu 552 | 553 | # 554 | # --------------------------------------------------- 555 | # 556 | def _genhashinshtr(self, a, b, c, d, e): 557 | # 558 | # Calculate arbitrary Hashin-Shtrikman bound, 559 | # which has the generic form 560 | # 561 | # f = a + b/((1/c) + d*(1/e)) 562 | # 563 | # both for lower and upper bulk and shear bounds 564 | # 565 | # 566 | # Input 567 | # a - see above formula 568 | # b - see above formula 569 | # c - see above formula 570 | # d - see above formula 571 | # e - see above formula 572 | # 573 | # Output 574 | # f - Bulk or shear Hashin-Shtrikman bound 575 | # value 576 | # 577 | # ----------------------------------------------- 578 | # 579 | cinv = 1/c 580 | einv = 1/e 581 | f = a + b/(cinv + d*einv) 582 | # 583 | return f 584 | # 585 | # ======================= 586 | # Solid properties end 587 | # ======================= 588 | # 589 | 590 | # 591 | # ============================ 592 | # Dry rock properties start 593 | # ============================ 594 | # 595 | def _dryrockmoduli(self, poro, poverb, pfluid, bulks, shears, ind=None, ntg=None, p_init=None, denss=None, Rs=None, phases=None): 596 | # 597 | # 598 | # Calculate bulk and shear dry rock moduli, 599 | # utilizing that they have the common 600 | # mathematical form, 601 | # 602 | # -- -- ^(-1) 603 | # |(poro/poroc) 1 - (poro/poroc)| 604 | # f = |------------ + ----------------| - z. 605 | # | a + z b + z | 606 | # --. -- 607 | # 608 | # 609 | # Input 610 | # poro - porosity 611 | # poverb - overburden pressure (MPa) 612 | # pfluid - fluid pressure (MPa) 613 | # bulks - bulk solid (mineral) rock bulk 614 | # modulus (MPa) 615 | # shears - solid rock (mineral) shear 616 | # modulus (MPa) 617 | # 618 | # Output 619 | # bulkd - dry rock bulk modulus (unit 620 | # inherited from hertzmindlin and 621 | # variable; bulks) 622 | # sheard - dry rock shear modulus (unit 623 | # inherited from hertzmindlin and 624 | # variable; shears) 625 | # 626 | # ----------------------------------------------- 627 | # 628 | # Calculate Hertz-Mindlin moduli 629 | # 630 | bulkhm, shearhm = self._hertzmindlin(poverb, 631 | pfluid) 632 | # 633 | # From table 1 in Report 1 in Abul Fahimuddin's 634 | # thesis (I assume \phi_max in that 635 | # table corresponds to \phi_c in his formulas): 636 | # 637 | poroc = 0.4 638 | # 639 | # Calculate input common to both bulk and 640 | # shear formulas 641 | # 642 | poratio = poro/poroc 643 | # 644 | # Calculate input to bulk formula 645 | # 646 | ba = bulkhm 647 | bb = bulks 648 | bz = 4*shearhm/3 649 | # 650 | # Calculate input to shear formula 651 | # 652 | sa = shearhm 653 | sb = shears 654 | sz = (shearhm/6)*((9*bulkhm + 8*shearhm) / 655 | (bulkhm + 2*shearhm)) 656 | # 657 | # Calculate moduli 658 | # 659 | bulkd = self._gendryrock(poratio, ba, bb, bz) 660 | sheard = self._gendryrock(poratio, sa, sb, sz) 661 | # 662 | return bulkd, sheard 663 | # 664 | # --------------------------------------------------- 665 | # 666 | 667 | def _hertzmindlin(self, poverb, pfluid): 668 | # 669 | # Calculate bulk and shear Hertz-Mindlin moduli 670 | # utilizing that they have the common 671 | # mathematical form, 672 | # 673 | # f = max*(peff/pref)^kappa. 674 | # 675 | # 676 | # Input 677 | # poverb - overburden pressure 678 | # pfluid - fluid pressure 679 | # 680 | # Output 681 | # bulkhm - Hertz-Mindlin bulk modulus 682 | # (MPa) 683 | # shearhm - Hertz-Mindlin shear modulus 684 | # (MPa) 685 | # 686 | # ----------------------------------------------- 687 | # 688 | # From table 1 in Report 1 in Abul Fahimuddin's 689 | # thesis (he used GPa for the moduli, I use MPa 690 | # also for them): 691 | # 692 | bulkmax = 3310 693 | shearmax = 2840 694 | pref = 8.8 695 | kappa = 0.233 696 | # 697 | # Calculate moduli 698 | # 699 | peff = poverb - pfluid 700 | if peff < 0: 701 | print("\nError in _hertzmindlin method") 702 | print("Negative effective pressure (" + str(peff) + 703 | "). Setting effective pressure to 0.01") 704 | peff = 0.01 705 | # sys.exit(1) 706 | common = (peff/pref)**kappa 707 | bulkhm = bulkmax*common 708 | shearhm = shearmax*common 709 | # 710 | return bulkhm, shearhm 711 | # 712 | # --------------------------------------------------- 713 | # 714 | 715 | def _gendryrock(self, q, a, b, z): 716 | # 717 | # Calculate arbitrary dry rock moduli, which has 718 | # the generic form 719 | # 720 | # -- -- ^(-1) 721 | # | q 1 - q | 722 | # f = |------------ + ----------------| - z, 723 | # | a + z b + z | 724 | # --. -- 725 | # 726 | # both for bulk and shear moduli 727 | # 728 | # 729 | # Input 730 | # q - see above formula 731 | # a - see above formula 732 | # b - see above formula 733 | # z - see above formula 734 | # 735 | # Output 736 | # f - Bulk or shear dry rock modulus value 737 | # 738 | # ----------------------------------------------- 739 | # 740 | afrac = q/(a + z) 741 | bfrac = (1 - q)/(b + z) 742 | f = 1/(afrac + bfrac) - z 743 | # 744 | return f 745 | # =========================== 746 | # Dry rock properties end 747 | # =========================== 748 | 749 | 750 | if __name__ == '__main__': 751 | # 752 | # Example input with two phases and three grid cells 753 | # 754 | porosity = [0.34999999, 0.34999999, 0.34999999] 755 | # pressure = [ 29.29150963, 29.14003944, 28.88845444] 756 | pressure = [29.3558, 29.2625, 29.3558] 757 | # pressure = [ 25.0, 25.0, 25.0] 758 | phases = ["Oil", "Wat"] 759 | # saturations = [[0.72783828, 0.66568458, 0.58033288], 760 | # [0.27216172, 0.33431542, 0.41966712]] 761 | saturations = [[0.6358, 0.5755, 0.6358], 762 | [0.3641, 0.4245, 0.3641]] 763 | # saturations = [[0.4, 0.5, 0.6], 764 | # [0.6, 0.5, 0.4]] 765 | petElProp = "bulk velocity" 766 | input_dict = {} 767 | input_dict['overburden'] = 'overb.npz' 768 | 769 | print("\nInput:") 770 | print("porosity, pressure:", porosity, pressure) 771 | print("phases, saturations:", phases, saturations) 772 | print("petElProp:", petElProp) 773 | print("input_dict:", input_dict) 774 | 775 | satrock = elasticproperties(input_dict) 776 | 777 | print("overburden:", satrock.overburden) 778 | 779 | satrock.calc_props(phases, saturations, pressure, 780 | porosity) 781 | 782 | print("\nOutput from calc_props:") 783 | print("Density:", satrock.getDens()) 784 | print("Bulk modulus:", satrock.getBulkMod()) 785 | print("Shear modulus:", satrock.getShearMod()) 786 | print("Bulk velocity:", satrock.getBulkVel()) 787 | print("Shear velocity:", satrock.getShearVel()) 788 | print("Bulk impedance:", satrock.getBulkImp()) 789 | print("Shear impedance:", satrock.getShearImp()) 790 | 791 | satrock.getMatchProp(petElProp) 792 | 793 | print("\nOutput from getMatchProp:") 794 | print("Model output selected for data match:", 795 | satrock.match_prop) 796 | -------------------------------------------------------------------------------- /src/subsurface/rockphysics/softsandrp.py: -------------------------------------------------------------------------------- 1 | """Descriptive description.""" 2 | 3 | __author__ = {'TM', 'TB', 'ML'} 4 | 5 | # standardrp.py 6 | import numpy as np 7 | import sys 8 | import multiprocessing as mp 9 | from CoolProp.CoolProp import PropsSI # http://coolprop.org/#high-level-interface-example 10 | import CoolProp.CoolProp as CP 11 | # Density of carbon dioxide at 100 bar and 25C # Smeaheia 37 degrees C 12 | #rho_co2 = PropsSI('D', 'T', 298.15, 'P', 100e5, 'CO2') 13 | from numpy.random import poisson 14 | 15 | # internal load 16 | from misc.system_tools.environ_var import OpenBlasSingleThread # Single threaded OpenBLAS runs 17 | 18 | 19 | class elasticproperties: 20 | """ 21 | Calculate elastic properties from standard 22 | rock-physics models, specifically following Batzle 23 | and Wang, Geophysics, 1992, for fluid properties, and 24 | Report 1 in Abul Fahimuddin's thesis at Universty of 25 | Bergen (2010) for other properties. 26 | 27 | Example 28 | ------- 29 | >>> porosity = 0.2 30 | ... pressure = 5 31 | ... phases = ["Oil","Water"] 32 | ... saturations = [0.3, 0.5] 33 | ... 34 | ... satrock = Elasticproperties() 35 | ... satrock.calc_props(phases, saturations, pressure, porosity) 36 | """ 37 | 38 | def __init__(self, input_dict): 39 | self.dens = None 40 | self.bulkmod = None 41 | self.shearmod = None 42 | self.bulkvel = None 43 | self.shearvel = None 44 | self.bulkimp = None 45 | self.shearimp = None 46 | # The overburden for each grid cell must be 47 | # specified as values on an .npz-file whose 48 | # name is given in input_dict. 49 | self.input_dict = input_dict 50 | self._extInfoInputDict() 51 | 52 | def _extInfoInputDict(self): 53 | # The key word for the file name in the 54 | # dictionary must read "overburden" 55 | if 'overburden' in self.input_dict: 56 | obfile = self.input_dict['overburden'] 57 | npzfile = np.load(obfile) 58 | # The values of overburden must have been 59 | # stored on file using: 60 | # np.savez(, 61 | # obvalues=) 62 | self.overburden = npzfile['obvalues'] 63 | npzfile.close() 64 | #else: 65 | # # Norne litho pressure equation in Bar 66 | # P_litho = -49.6 + 0.2027 * Z + 6.127e-6 * Z ** 2 # Using e-6 for scientific notation 67 | # # Convert reservoir pore pressure from Bar to MPa 68 | # P_litho *= 0.1 69 | # self.overburden = P_litho 70 | 71 | if 'baseline' in self.input_dict: 72 | self.baseline = self.input_dict['baseline'] # 4D baseline 73 | if 'parallel' in self.input_dict: 74 | self.parallel = self.input_dict['parallel'] 75 | 76 | def _filter(self): 77 | bulkmod = self.bulkimp 78 | self.bulkimp = bulkmod.flatten() 79 | 80 | def setup_fwd_run(self, state): 81 | """ 82 | Setup the input parameters to be used in the PEM simulator. Parameters can be an ensemble or a single array. 83 | State is set as an attribute of the simulator, and the correct value is determined in self.pem.calc_props() 84 | 85 | Parameters 86 | ---------- 87 | state : dict 88 | Dictionary of input parameters or states. 89 | 90 | Changelog 91 | --------- 92 | - KF 11/12-2018 93 | """ 94 | # self.inv_state = {} 95 | # list_pem_param =[el for el in [foo for foo in self.pem['garn'].keys()] + [foo for foo in self.filter.keys()] + 96 | # [foo for foo in self.__dict__.keys()]] 97 | 98 | # list_tot_param = state.keys() 99 | # for param in list_tot_param: 100 | # if param in list_pem_param or (param.split('_')[-1] in ['garn', 'rest']): 101 | # self.inv_state[param] = state[param] 102 | 103 | pass 104 | 105 | def calc_props(self, phases, saturations, pressure, 106 | porosity, dens = None, wait_for_proc=None, ntg=None, Rs=None, press_init=None, ensembleMember=None): 107 | ### 108 | 109 | # 110 | if not isinstance(phases, list): 111 | phases = [phases] 112 | if not isinstance(saturations, list): 113 | saturations = [saturations] 114 | if not isinstance(pressure, list) and \ 115 | type(pressure).__module__ != 'numpy': 116 | pressure = [pressure] 117 | if not isinstance(porosity, list) and \ 118 | type(porosity).__module__ != 'numpy': 119 | porosity = [porosity] 120 | # 121 | # Load "overburden" pressures into local variable to 122 | # comply with remaining code parts 123 | poverburden = self.overburden 124 | 125 | # debug 126 | self.pressure = pressure 127 | self.peff = poverburden - pressure 128 | self.porosity = porosity 129 | 130 | if press_init is None: 131 | p_init = self.p_init 132 | else: 133 | p_init = press_init 134 | 135 | # Average number of contacts that each grain has with surrounding grains 136 | coordnumber = self._coordination_number() 137 | 138 | # porosity value separating the porous media's mechanical and acoustic behaviour 139 | phicritical = self._critical_porosity() 140 | 141 | 142 | # Check that no. of phases is equal to no. of 143 | # entries in saturations list 144 | # 145 | assert (len(saturations) == len(phases)) 146 | # 147 | # Make saturation a Numpy array (so that we 148 | # can easily access the values for each 149 | # phase at one grid cell) 150 | # 151 | # Transpose makes it a no. grid cells x phases 152 | # array 153 | saturations = np.array(saturations).T 154 | # 155 | # Check if we actually inputted saturation values 156 | # for a single grid cell. If yes, we redefine 157 | # saturations to get it on the correct form (no. 158 | # grid cells x phases array). 159 | # 160 | if saturations.ndim == 1: 161 | saturations = \ 162 | np.array([[x] for x in saturations]).T 163 | # 164 | # Loop over all grid cells and calculate the 165 | # various saturated properties 166 | # 167 | self.phases = phases 168 | 169 | self.dens = np.zeros(len(saturations[:, 0])) 170 | self.bulkmod = np.zeros(len(saturations[:, 0])) 171 | self.shearmod = np.zeros(len(saturations[:, 0])) 172 | self.bulkvel = np.zeros(len(saturations[:, 0])) 173 | self.shearvel = np.zeros(len(saturations[:, 0])) 174 | self.bulkimp = np.zeros(len(saturations[:, 0])) 175 | self.shearimp = np.zeros(len(saturations[:, 0])) 176 | 177 | if ntg is None: 178 | ntg = [None for _ in range(len(saturations[:, 0]))] 179 | if Rs is None: 180 | Rs = [None for _ in range(len(saturations[:, 0]))] 181 | if p_init is None: 182 | p_init = [None for _ in range(len(saturations[:, 0]))] 183 | 184 | 185 | if dens is not None: 186 | assert (len(dens) == len(phases)) 187 | # Transpose makes it a no. grid cells x phases array 188 | dens = np.array(dens).T 189 | 190 | # 191 | denss, bulks, shears = self._solidprops_Johansen() 192 | 193 | for i in range(len(saturations[:, 0])): 194 | # 195 | # Calculate fluid properties 196 | # 197 | if dens is None: 198 | densf_SI = self._fluid_densSIprop(self.phases, 199 | saturations[i, :], pressure[i]) 200 | bulkf_Brie = self._fluidprops_Brie(self.phases, saturations[i, :], pressure[i], densf_SI) 201 | densf, bulkf = \ 202 | self._fluidprops_Wood(self.phases, 203 | saturations[i, :], pressure[i], Rs[i]) 204 | else: 205 | densf = self._fluid_dens(saturations[i, :], dens[i, :]) 206 | 207 | bulkf = self._fluidprops_Brie(self.phases, saturations[i, :], pressure[i], densf) 208 | # 209 | #denss, bulks, shears = \ 210 | # self._solidprops(porosity[i], ntg[i], i) 211 | 212 | # 213 | # Calculate dry rock moduli 214 | # 215 | 216 | #bulkd, sheard = \ 217 | # self._dryrockmoduli(porosity[i], 218 | # overburden[i], 219 | # pressure[i], bulks, 220 | # shears, i, ntg[i], p_init[i], denss, Rs[i], self.phases) 221 | # 222 | peff = self._effective_pressure(poverburden[i], pressure[i]) 223 | 224 | 225 | bulkd, sheard = \ 226 | self._dryrockmoduli_Smeaheia(coordnumber, phicritical, porosity[i], peff, bulks, shears) 227 | 228 | # ------------------------------- 229 | # Calculate saturated properties 230 | # ------------------------------- 231 | # 232 | # Density (kg/m3) 233 | # 234 | self.dens[i] = (porosity[i]*densf + 235 | (1-porosity[i])*denss) 236 | # 237 | # Moduli (MPa) 238 | # 239 | self.bulkmod[i] = \ 240 | bulkd + (1 - bulkd/bulks)**2 / \ 241 | (porosity[i]/bulkf + 242 | (1-porosity[i])/bulks - 243 | bulkd/(bulks**2)) 244 | self.shearmod[i] = sheard 245 | # 246 | # Velocities (km/s) 247 | # 248 | self.bulkvel[i] = \ 249 | np.sqrt((abs(self.bulkmod[i]) + 250 | 4*self.shearmod[i]/3)/(self.dens[i])) 251 | self.shearvel[i] = \ 252 | np.sqrt(self.shearmod[i] / 253 | (self.dens[i])) 254 | # 255 | # convert from (km/s) to (m/s) 256 | # 257 | self.bulkvel[i] *= 1000 258 | self.shearvel[i] *= 1000 259 | # 260 | # Impedance (m/s)*(kg/m3) 261 | # 262 | self.bulkimp[i] = self.dens[i] * \ 263 | self.bulkvel[i] 264 | self.shearimp[i] = self.dens[i] * \ 265 | self.shearvel[i] 266 | 267 | 268 | 269 | def getMatchProp(self, petElProp): 270 | if petElProp.lower() == 'density': 271 | self.match_prop = self.getDens() 272 | elif petElProp.lower() == 'bulk_modulus': 273 | self.match_prop = self.getBulkMod() 274 | elif petElProp.lower() == 'shear_modulus': 275 | self.match_prop = self.getShearMod() 276 | elif petElProp.lower() == 'bulk_velocity': 277 | self.match_prop = self.getBulkVel() 278 | elif petElProp.lower() == 'shear_velocity': 279 | self.match_prop = self.getShearVel() 280 | elif petElProp.lower() == "bulk_impedance": 281 | self.match_prop = self.getBulkImp() 282 | elif petElProp.lower() == 'shear_impedance': 283 | self.match_prop = self.getShearImp() 284 | else: 285 | print("\nError in getMatchProp method") 286 | print("No model output type selected for " 287 | "data match.") 288 | print("Legal model output types are " 289 | "(case insensitive):") 290 | print("Density, bulk modulus, shear " 291 | "modulus, bulk velocity,") 292 | print("shear velocity, bulk impedance, " 293 | "shear impedance") 294 | sys.exit(1) 295 | return self.match_prop 296 | 297 | def getDens(self): 298 | return self.dens 299 | 300 | def getBulkMod(self): 301 | return self.bulkmod 302 | 303 | def getShearMod(self): 304 | return self.shearmod 305 | 306 | def getBulkVel(self): 307 | return self.bulkvel 308 | 309 | def getShearVel(self): 310 | return self.shearvel 311 | 312 | def getBulkImp(self): 313 | return self.bulkimp 314 | 315 | def getShearImp(self): 316 | return self.shearimp 317 | 318 | def getOverburdenP(self): 319 | return self.overburden 320 | 321 | def getPressure(self): 322 | return self.pressure 323 | 324 | def getPeff(self): 325 | return self.peff 326 | 327 | def getPorosity(self): 328 | return self.porosity 329 | # 330 | # =================================================== 331 | # Fluid properties start 332 | # =================================================== 333 | # 334 | def _fluid_densSIprop(self, phases, fsats, press, t= 37, CO2 = None): 335 | 336 | conv2Pa = 1e6 # MPa to Pa 337 | ta = t + 273.15 # absolute temp in K 338 | # fluid densities 339 | fdens = 0.0 340 | 341 | for i in range(len(phases)): 342 | # 343 | # Calculate mixture properties by summing 344 | # over individual phase properties 345 | # 346 | 347 | var = phases[i] 348 | if var == 'GAS' and CO2 is None: 349 | pdens = PropsSI('D', 'T', ta, 'P', press * conv2Pa, 'Methane') 350 | elif var == 'GAS' and CO2 is True: 351 | pdens = PropsSI('D', 'T', ta, 'P', press * conv2Pa, 'CO2') 352 | elif var == 'OIL': 353 | CP.get_global_param_string('predefined_mixtures').split(',')[0:6] 354 | #pdens = CP.PropsSI('D', 'T', ta, 'P', press * conv2Pa, 'Ekofisk.mix') 355 | pdens = CP.PropsSI('D', 'T', ta, 'P', press * conv2Pa, 'butane') 356 | elif var == 'WAT': 357 | pdens = PropsSI('D', 'T|liquid', ta, 'P', press * conv2Pa, 'Water') 358 | 359 | fdens = fdens + fsats[i] * abs(pdens) 360 | 361 | return fdens 362 | 363 | def _fluidprops_Wood(self, fphases, fsats, fpress, Rs=None): 364 | # 365 | # Calculate fluid density and bulk modulus 366 | # 367 | # 368 | # Input 369 | # fphases - fluid phases present; Oil 370 | # and/or Water and/or Gas 371 | # fsats - fluid saturation values for 372 | # fluid phases in "fphases" 373 | # fpress - fluid pressure value (MPa) 374 | # Rs - Gas oil ratio. Default value None 375 | 376 | # 377 | # Output 378 | # fdens - density of fluid mixture for 379 | # pressure value "fpress" inherited 380 | # from phaseprops) 381 | # fbulk - bulk modulus of fluid mixture for 382 | # pressure value "fpress" (unit 383 | # inherited from phaseprops) 384 | # 385 | # ----------------------------------------------- 386 | # 387 | fdens = 0.0 388 | fbinv = 0.0 389 | 390 | for i in range(len(fphases)): 391 | # 392 | # Calculate mixture properties by summing 393 | # over individual phase properties 394 | # 395 | pdens, pbulk = self._phaseprops(fphases[i], 396 | fpress, Rs) 397 | fdens = fdens + fsats[i]*abs(pdens) 398 | fbinv = fbinv + fsats[i]/abs(pbulk) 399 | fbulk = 1.0/fbinv 400 | # 401 | return fdens, fbulk 402 | # 403 | # --------------------------------------------------- 404 | # 405 | 406 | def _fluid_dens(self, fsatsp, fdensp): 407 | fdens = sum(fsatsp * fdensp) 408 | return fdens 409 | 410 | def _fluidprops_Brie(self, fphases, fsats, fpress, fdens, Rs=None, e = 5): 411 | # 412 | # Calculate fluid density and bulk modulus BRIE et al. 1995 413 | # Assumes two phases liquid and gas 414 | # 415 | # Input 416 | # fphases - fluid phases present; Oil 417 | # and/or Water and/or Gas 418 | # fsats - fluid saturation values for 419 | # fluid phases in "fphases" 420 | # fdens - fluid density for given pressure and temperature 421 | # fpress - fluid pressure value (MPa) 422 | # Rs - Gas oil ratio. Default value None 423 | # e - Brie's exponent (e= 5 Utsira sand filled with brine and CO2 424 | # Figure 7 in Carcione et al. 2006 "Physics and Seismic Modeling 425 | # for Monitoring CO 2 Storage" 426 | 427 | # 428 | # Output 429 | # fbulk - bulk modulus of fluid mixture for 430 | # pressure value "fpress" (unit 431 | # inherited from phaseprops) 432 | # 433 | # ----------------------------------------------- 434 | # 435 | 436 | 437 | for i in range(len(fphases)): 438 | # 439 | if fphases[i].lower() in ["oil", "wat"]: 440 | fsatsl = fsats[i] 441 | pbulkl = self._phaseprops_Smeaheia(fphases[i], fpress, fdens, Rs) 442 | elif fphases[i].lower() in ["gas"]: 443 | pbulkg = self._phaseprops_Smeaheia(fphases[i], fpress, fdens, Rs) 444 | 445 | 446 | fbulk = (pbulkl - pbulkg) * (fsatsl)**e + pbulkg 447 | 448 | # 449 | return fbulk 450 | # 451 | # --------------------------------------------------- 452 | # 453 | @staticmethod 454 | def pseudo_p_t(pres, t, gs): 455 | """Calculate the pseudoreduced temperature and pressure according to Thomas et al. 1970. 456 | 457 | Parameters 458 | ---------- 459 | pres : float or array-like 460 | Pressure in MPa 461 | t : float or array-like 462 | Temperature in °C 463 | gs : float 464 | Gas gravity 465 | 466 | Returns 467 | ------- 468 | float or array-like 469 | Ta: absolute temperature 470 | Ppr:pseudoreduced pressure 471 | Tpr:pseudoreduced temperature 472 | """ 473 | 474 | # convert the temperature to absolute temperature 475 | ta = t + 273.15 476 | p_pr = pres / (4.892 - 0.4048 * gs) 477 | t_pr = ta / (94.72 + 170.75 * gs) 478 | return ta, p_pr, t_pr 479 | # 480 | # --------------------------------------------------- 481 | # 482 | @staticmethod 483 | def dz_dp(p_pr, t_pr): 484 | """Values for dZ/dPpr obtained from equation 10b in Batzle and Wang (1992). 485 | """ 486 | # analytic 487 | dz_dp = (0.03 + 0.00527 * (3.5 - t_pr) ** 3) + 0.109 * (3.85 - t_pr) ** 2 * 1.2 * p_pr ** 0.2 * -( 488 | 0.45 + 8 * (0.56 - 1 / t_pr) ** 2) / t_pr * np.exp( 489 | -(0.45 + 8 * (0.56 - 1 / t_pr) ** 2) * p_pr ** 1.2 / t_pr) 490 | 491 | # numerical approximation 492 | # dzdp= 1.938783*P_pr**0.2*(1 - 0.25974025974026*T_pr)**2*(-8*(0.56 - 1/T_pr)**2 - 0.45)* 493 | # np.exp(P_pr**1.2*(-8*(0.56 - 1/T_pr)**2 - 0.45)/T_pr)/T_pr + 0.22595125*(1 - 0.285714285714286*T_pr)**3 494 | # + 0.03 495 | return dz_dp 496 | # 497 | #----------------------------------------------------------- 498 | # 499 | def _phaseprops_Smeaheia(self, fphase, press, fdens, Rs=None, t = 37, CO2 = True): 500 | # 501 | # Calculate properties for a single fluid phase 502 | # 503 | # 504 | # Input 505 | # fphase - fluid phase; Oil, Water or Gas 506 | # press - fluid pressure value (MPa) 507 | # fdens - fluid density (kg/m3) 508 | # t - temperature in degrees C 509 | # 510 | # Output 511 | # pbulk - bulk modulus of fluid phase 512 | # "fphase" for pressure value 513 | # "press" (MPa) 514 | # 515 | # ----------------------------------------------- 516 | # References 517 | # ---------- 518 | # Xu, H. (2006). Calculation of CO2 acoustic properties using Batzle-Wang equations. Geophysics, 71(2), F21-F23. 519 | # """ 520 | 521 | if fphase.lower() == "wat": # refers to pure water or brine 522 | #Compute the bulk modulus of pure water as a function of temperature and pressure 523 | #using Batzle and Wang (1992). 524 | if np.any(press > 100): 525 | print('pressures above about 100 MPa-> inaccurate estimations of water velocity') 526 | w = np.array([[1.40285e+03, 1.52400e+00, 3.43700e-03, -1.19700e-05], 527 | [4.87100e+00, -1.11000e-02, 1.73900e-04, -1.62800e-06], 528 | [-4.78300e-02, 2.74700e-04, -2.13500e-06, 1.23700e-08], 529 | [1.48700e-04, -6.50300e-07, -1.45500e-08, 1.32700e-10], 530 | [-2.19700e-07, 7.98700e-10, 5.23000e-11, -4.61400e-13]]) 531 | v_w = sum(w[i, j] * t ** i * press ** j for i in range(5) for j in range(4)) # m/s 532 | K_w = fdens * v_w ** 2 * 1e-6 533 | if CO2 is True: # refers to brine 534 | salinity = 35000 / 1000000 535 | s1 = 1170 - 9.6 * t + 0.055 * t ** 2 - 8.5e-5 * t ** 3 + 2.6 * press - 0.0029 * t * press - 0.0476 * press ** 2 536 | s15 = 780 - 10 * press + 0.16 * press ** 2 537 | s2 = -820 538 | v_b = v_w + s1 * salinity + s15 * salinity ** 1.5 + s2 * salinity ** 2 539 | x = 300 * press - 2400 * press * salinity + t * (80 + 3 * t - 3300 * salinity - 13 * press + 47 * press * salinity) 540 | rho_b = fdens + salinity * (0.668 + 0.44 * salinity + 1e-6 * x) 541 | pbulk = rho_b * v_b ** 2 * 1e-6 542 | else: 543 | pbulk = K_w 544 | 545 | elif fphase.lower() == "gas" and CO2 is True: # refers to CO2 546 | R = 8.3145 # J.mol-1K-1 gas constant for CO2 547 | gs = 1.5189 # Specific gravity #https://www.engineeringtoolbox.com/specific-gravities-gases-d_334.html 548 | ta, p_pr, t_pr = self.pseudo_p_t(press, t, gs) 549 | 550 | E = 0.109 * (3.85 - t_pr) ** 2 * np.exp(-(0.45 + 8 * (0.56 - 1 / t_pr) ** 2) * p_pr ** 1.2 / t_pr) 551 | Z = (0.03 + 0.00527 * (3.5 - t_pr) ** 3) * p_pr + (0.642 * t_pr - 0.007 * t_pr ** 4 - 0.52) + E 552 | rho = 28.8 * gs * press / (Z * R * ta) # g/cm3 553 | 554 | r_0 = 0.85 + 5.6 / (p_pr + 2) + 27.1 / (p_pr + 3.5) ** 2 - 8.7 * np.exp(-0.65 * (p_pr + 1)) 555 | dz_dp = self.dz_dp(p_pr, t_pr) 556 | pbulk = press / (1 - p_pr * dz_dp / Z) * r_0 557 | 558 | #pbulk_test = self.test_new_implementation(press) 559 | #print(np.max(pbulk-pbulk_test)) 560 | 561 | elif fphase.lower() == "gas": # refers to Methane 562 | gs = 0.5537 #https://www.engineeringtoolbox.com/specific-gravities-gases-d_334.html 563 | R = 8.3145 # J.mol-1K-1 gas constant 564 | ta, p_pr, t_pr = self.pseudo_p_t(press, t, gs) 565 | E = 0.109 * (3.85 - t_pr) ** 2 * np.exp(-(0.45 + 8 * (0.56 - 1 / t_pr) ** 2) * p_pr ** 1.2 / t_pr) 566 | Z = (0.03 + 0.00527 * (3.5 - t_pr) ** 3) * p_pr + (0.642 * t_pr - 0.007 * t_pr ** 4 - 0.52) + E 567 | rho = 28.8 * gs * press / (Z * R * ta) # g/cm3 568 | 569 | r_0 = 0.85 + 5.6 / (p_pr + 2) + 27.1 / (p_pr + 3.5) ** 2 - 8.7 * np.exp(-0.65 * (p_pr + 1)) 570 | dz_dp = self.dz_dp(p_pr, t_pr) 571 | pbulk = press / (1 - p_pr * dz_dp / Z) * r_0 572 | 573 | elif fphase.lower() == "oil": #pure oil 574 | # Estimate the oil bulk modulus at specific temperature and pressure. 575 | v = 2096 * (fdens / (2600 - fdens)) ** 0.5 - 3.7 * t + 4.64 * press + 0.0115 * ( 576 | 4.12 * (1080 / fdens - 1) ** 0.5 - 1) * t * press 577 | pbulk = fdens * v ** 2 578 | 579 | 580 | # 581 | return pbulk 582 | 583 | # 584 | def test_new_implementation(self, press): 585 | # Values from .DATA file for Smeaheia (converted to MPa) 586 | press_range = np.array( 587 | [0.101, 0.885, 1.669, 2.453, 3.238, 4.022, 4.806, 5.590, 6.2098, 7.0899, 7.6765, 8.2630, 8.8495, 9.4359, 588 | 10.0222, 10.6084, 11.1945, 14.7087, 17.6334, 20.856, 23.4695, 27.5419]) # Example pressures in MPa 589 | Bo_values = np.array( 590 | [1.07365, 0.11758, 0.05962, 0.03863, 0.02773, 0.02100, 0.01639, 0.01298, 0.010286, 0.007578, 0.005521, 591 | 0.003314, 0.003034, 0.002919, 0.002851, 0.002802, 0.002766, 0.002648, 0.002599, 0.002566, 0.002546, 592 | 0.002525]) # Example formation volume factors in m^3/kg 593 | 594 | # Calculate numerical derivative of Bo with respect to Pressure 595 | dBo_dP = - np.gradient(Bo_values, press_range) 596 | # Calculate isothermal compressibility (van der Waals) 597 | compressibility = (1 / Bo_values) * dBo_dP # Resulting array of compressibility values 598 | bulk_mod = 1 / compressibility 599 | 600 | # Find the index of the closest pressure value in b 601 | closest_index = (np.abs(press_range - press)).argmin() 602 | 603 | # Extract the corresponding value from a 604 | pbulk_test = bulk_mod[closest_index] 605 | return pbulk_test 606 | 607 | def _phaseprops(self, fphase, press, Rs=None): 608 | # 609 | # Calculate properties for a single fluid phase 610 | # 611 | # 612 | # Input 613 | # fphase - fluid phase; Oil, Water or Gas 614 | # press - fluid pressure value (MPa) 615 | # 616 | # Output 617 | # pdens - phase density of fluid phase 618 | # "fphase" for pressure value 619 | # "press" (kg/m³) 620 | # pbulk - bulk modulus of fluid phase 621 | # "fphase" for pressure value 622 | # "press" (MPa) 623 | # 624 | # ----------------------------------------------- 625 | # 626 | if fphase.lower() == "oil": 627 | coeffsrho = np.array([0.8, 829.9]) 628 | coeffsbulk = np.array([10.42, 995.79]) 629 | elif fphase.lower() == "wat": 630 | coeffsrho = np.array([0.3, 1067.3]) 631 | coeffsbulk = np.array([9.0, 2807.6]) 632 | elif fphase.lower() == "gas": 633 | coeffsrho = np.array([4.7, 13.4]) 634 | coeffsbulk = np.array([2.75, 0.0]) 635 | else: 636 | print("\nError in phaseprops method") 637 | print("Illegal fluid phase name.") 638 | print("Legal fluid phase names are (case " 639 | "insensitive): Oil, Wat, and Gas.") 640 | sys.exit(1) 641 | # 642 | # Assume simple linear pressure dependencies. 643 | # Coefficients are inferred from 644 | # plots in Batzle and Wang, Geophysics, 1992, 645 | # (where I set the temperature to be 100 degrees 646 | # Celsius, Note also that they give densities in 647 | # g/cc). The resulting straight lines do not fit 648 | # the data extremely well, but they should 649 | # be sufficiently accurate for the purpose of 650 | # this project. 651 | # 652 | pdens = coeffsrho[0]*press + coeffsrho[1] 653 | pbulk = coeffsbulk[0]*press + coeffsbulk[1] 654 | # 655 | return pdens, pbulk 656 | 657 | # 658 | # ======================= 659 | # Fluid properties end 660 | # ======================= 661 | # 662 | 663 | # 664 | # ========================= 665 | # Solid properties start 666 | # ========================= 667 | # 668 | def _solidprops_Johansen(self): 669 | # 670 | # Calculate bulk and shear solid rock (mineral) 671 | # moduli by averaging Hashin-Shtrikman bounds 672 | # 673 | # 674 | # Input 675 | # poro -porosity 676 | # 677 | # Output 678 | # denss - solid rock density (kg/m³) 679 | # bulks - solid rock bulk modulus (unit MPa) 680 | # shears - solid rock shear modulus (unit MPa) 681 | # 682 | # ----------------------------------------------- 683 | # 684 | # 685 | # Solid rock (mineral) density. (Note 686 | # that this is often termed \rho_dry, and not 687 | # \rho_s) 688 | 689 | denss = 2650 # Density of mineral/solid rock kg/m3 690 | 691 | # 692 | bulks = 37 # (GPa) 693 | shears = 44 # (GPa) 694 | bulks *= 1000 # Convert from GPa to MPa 695 | shears *= 1000 696 | # 697 | return denss, bulks, shears 698 | # 699 | # 700 | # ======================= 701 | # Solid properties end 702 | # ======================= 703 | # 704 | def _coordination_number(self): 705 | # Applies for granular media 706 | # Average number of contacts that each grain has with surrounding grains 707 | # Coordnumber = 6; simple cubic packing 708 | # Coordnumber = 12; hexagonal close packing 709 | # Needed for Hertz-Mindlin model 710 | # Smeaheia number (Tuhin) 711 | coordnumber = 9 712 | 713 | return coordnumber 714 | # 715 | def _critical_porosity(self): 716 | # For most porous media there exists a critical porosity 717 | # phi_critical, that seperates their mechanical and acoustic behaviour into two domains. 718 | # For porosities below phi_critical the mineral grains are oad bearing, for values above the grains are 719 | # suspended in the fluids which are load-bearing 720 | # Needed for Hertz-Mindlin model 721 | # Smeaheia number (Tuhin) 722 | phicritical = 0.36 723 | 724 | return phicritical 725 | # 726 | def _effective_pressure(self, poverb, pfluid): 727 | 728 | # Input 729 | # poverb - overburden pressure (MPa) 730 | # pfluid - fluid pressure (MPa) 731 | 732 | peff = poverb - pfluid 733 | 734 | if peff < 0: 735 | print("\nError in _hertzmindlin method") 736 | print("Negative effective pressure (" + str(peff) + 737 | "). Setting effective pressure to 0.01") 738 | peff = 0.01 739 | 740 | 741 | 742 | return peff 743 | 744 | # ============================ 745 | # Dry rock properties start 746 | # ============================ 747 | # 748 | def _dryrockmoduli_Smeaheia(self, coordnumber, phicritical, poro, peff, bulks, shears): 749 | # 750 | # 751 | # Calculate bulk and shear dry rock moduli, 752 | 753 | # 754 | # Input 755 | # poro - porosity 756 | # peff - effective pressure overburden - fluid pressure (MPa) 757 | # bulks - bulk solid (mineral) rock bulk 758 | # modulus (MPa) 759 | # shears - solid rock (mineral) shear 760 | # modulus (MPa) 761 | # 762 | # Output 763 | # bulkd - dry rock bulk modulus (unit 764 | # inherited from hertzmindlin and 765 | # variable; bulks) 766 | # sheard - dry rock shear modulus (unit 767 | # inherited from hertzmindlin and 768 | # variable; shears) 769 | # 770 | # ----------------------------------------------- 771 | # 772 | # Calculate Hertz-Mindlin moduli 773 | # 774 | bulkhm, shearhm = self._hertzmindlin_Mavko(peff, bulks, shears, coordnumber, phicritical) 775 | # 776 | bulkd = 1 / ((poro / phicritical) / (bulkhm + 4 / 3 * shearhm) + 777 | (1 - poro / phicritical) / (bulks + 4 / 3 * shearhm)) - 4 / 3 * shearhm 778 | 779 | psi = (9 * bulkhm + 8 * shearhm) / (bulkhm + 2 * shearhm) 780 | 781 | sheard = 1 / ((poro / phicritical) / (shearhm + 1 / 6 * psi * shearhm) + 782 | (1 - poro / phicritical) / (shears + 1 / 6 * psi * shearhm)) - 1 / 6 * psi * shearhm 783 | 784 | #return K_dry, G_dry 785 | return bulkd, sheard 786 | 787 | 788 | # 789 | # --------------------------------------------------- 790 | # 791 | 792 | def _hertzmindlin_Mavko(self, peff, bulks, shears, coordnumber, phicritical): 793 | # 794 | # Calculate bulk and shear Hertz-Mindlin moduli 795 | # adapted from Tuhins kode and "The rock physics handbook", pp247 796 | # 797 | # 798 | # Input 799 | # p_eff - effective pressure 800 | # bulks - bulk solid (mineral) rock bulk 801 | # modulus (MPa) 802 | # shears - solid rock (mineral) shear 803 | # modulus (MPa) 804 | # coordnumber - average number of contacts that each grain has with surrounding grains 805 | # phicritical - critical porosity 806 | # 807 | # Output 808 | # bulkhm - Hertz-Mindlin bulk modulus 809 | # (MPa) 810 | # shearhm - Hertz-Mindlin shear modulus 811 | # (MPa) 812 | # 813 | # ----------------------------------------------- 814 | # 815 | 816 | 817 | poisson = (3 * bulks - 2 * shears) / (6 * bulks + 2 * shears) 818 | 819 | bulkhm = ((coordnumber ** 2 * (1 - phicritical) ** 2 * shears ** 2 * peff) / 820 | (18 * np.pi ** 2 * (1 - poisson) ** 2)) ** (1 / 3) 821 | shearhm = (5 - 4 * poisson) / (10 - 5 * poisson) * \ 822 | ((3 * coordnumber ** 2 * (1 - phicritical) ** 2 * shears ** 2 * peff) / 823 | (2 * np.pi ** 2 * (1 - poisson) ** 2)) ** (1 / 3) 824 | 825 | 826 | 827 | # 828 | return bulkhm, shearhm 829 | 830 | 831 | # =========================== 832 | # Dry rock properties end 833 | # =========================== 834 | 835 | 836 | if __name__ == '__main__': 837 | # 838 | # Example input with two phases and three grid cells 839 | # 840 | porosity = [0.34999999, 0.34999999, 0.34999999] 841 | # pressure = [ 29.29150963, 29.14003944, 28.88845444] 842 | pressure = [29.3558, 29.2625, 29.3558] 843 | # pressure = [ 25.0, 25.0, 25.0] 844 | phases = ["Oil", "Wat"] 845 | # saturations = [[0.72783828, 0.66568458, 0.58033288], 846 | # [0.27216172, 0.33431542, 0.41966712]] 847 | saturations = [[0.6358, 0.5755, 0.6358], 848 | [0.3641, 0.4245, 0.3641]] 849 | # saturations = [[0.4, 0.5, 0.6], 850 | # [0.6, 0.5, 0.4]] 851 | petElProp = "bulk velocity" 852 | input_dict = {} 853 | input_dict['overburden'] = 'overb.npz' 854 | 855 | print("\nInput:") 856 | print("porosity, pressure:", porosity, pressure) 857 | print("phases, saturations:", phases, saturations) 858 | print("petElProp:", petElProp) 859 | print("input_dict:", input_dict) 860 | 861 | satrock = elasticproperties(input_dict) 862 | 863 | print("overburden:", satrock.overburden) 864 | 865 | satrock.calc_props(phases, saturations, pressure, 866 | porosity) 867 | 868 | print("\nOutput from calc_props:") 869 | print("Density:", satrock.getDens()) 870 | print("Bulk modulus:", satrock.getBulkMod()) 871 | print("Shear modulus:", satrock.getShearMod()) 872 | print("Bulk velocity:", satrock.getBulkVel()) 873 | print("Shear velocity:", satrock.getShearVel()) 874 | print("Bulk impedance:", satrock.getBulkImp()) 875 | print("Shear impedance:", satrock.getShearImp()) 876 | 877 | satrock.getMatchProp(petElProp) 878 | 879 | print("\nOutput from getMatchProp:") 880 | print("Model output selected for data match:", 881 | satrock.match_prop) 882 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------