Case And Grid Operations
This page shows Python examples from the case_and_grid_operations folder.
Case Grid Group
case_grid_group.py
1import os
2import rips
3
4resinsight = rips.Instance.find()
5
6test_model_path = "e:/gitroot-second/ResInsight/TestModels"
7
8case_paths = []
9case_paths.append(test_model_path + "/Case_with_10_timesteps/Real0/BRUGGE_0000.EGRID")
10case_paths.append(test_model_path + "/Case_with_10_timesteps/Real10/BRUGGE_0010.EGRID")
11case_paths.append(test_model_path + "/Case_with_10_timesteps/Real30/BRUGGE_0030.EGRID")
12case_paths.append(test_model_path + "/Case_with_10_timesteps/Real40/BRUGGE_0040.EGRID")
13
14for case_path in case_paths:
15 assert os.path.exists(case_path), (
16 "You need to set valid case paths for this script to work"
17 )
18
19case_group = resinsight.project.create_grid_case_group(case_paths=case_paths)
20
21case_group.compute_statistics()
22
23view = case_group.views()[0]
24view.apply_cell_result("DYNAMIC_NATIVE", "PRESSURE_DEV")
Case Grid Group Generated Results
case_grid_group_generated_results.py
1import os
2import rips
3
4resinsight = rips.Instance.find()
5
6# ResInsight includes some test models. Adjust this path to fit your system
7test_model_path = "e:/gitroot-second/ResInsight/TestModels"
8
9case_paths = []
10case_paths.append(test_model_path + "/Case_with_10_timesteps/Real0/BRUGGE_0000.EGRID")
11case_paths.append(test_model_path + "/Case_with_10_timesteps/Real10/BRUGGE_0010.EGRID")
12case_paths.append(test_model_path + "/Case_with_10_timesteps/Real30/BRUGGE_0030.EGRID")
13case_paths.append(test_model_path + "/Case_with_10_timesteps/Real40/BRUGGE_0040.EGRID")
14
15for case_path in case_paths:
16 assert os.path.exists(case_path), (
17 "You need to set valid case paths for this script to work"
18 )
19
20case_group = resinsight.project.create_grid_case_group(case_paths=case_paths)
21
22cases = case_group.descendants(rips.EclipseCase)
23print("Got " + str(len(cases)) + " cases: ")
24
25for case in cases:
26 time_step_info = case.time_steps()
27 porv_results = case.active_cell_property("STATIC_NATIVE", "PORV", 0)
28
29 for time_step_index in range(0, len(time_step_info)):
30 pressure_results = case.active_cell_property(
31 "DYNAMIC_NATIVE", "PRESSURE", time_step_index
32 )
33
34 results = []
35 for pressure, porv in zip(pressure_results, porv_results):
36 results.append(pressure * porv)
37
38 # set the computed values in the case
39 case.set_active_cell_property(
40 results, "GENERATED", "PRESSURE_PORV", time_step_index
41 )
42
43 print(
44 "Case id: " + str(case.id),
45 " Case name: " + case.name,
46 " : Calculation complete",
47 )
48
49
50print("Transferred all results back to ResInsight")
51
52# one of "GENERATED", "DYNAMIC_NATIVE", "STATIC_NATIVE", "IMPORTED"
53# https://api.resinsight.org/en/main/rips.html#result-definition
54property_type = "GENERATED"
55
56property_name = "PRESSURE_PORV"
57
58statistics_case = case_group.create_statistics_case()
59statistics_case.set_source_properties(property_type, [property_name])
60statistics_case.compute_statistics()
61
62view = statistics_case.create_view()
63statistics_property_name = property_name + "_MEAN"
64view.apply_cell_result(
65 result_type=property_type, result_variable=statistics_property_name
66)
Compute Avg Poro For Region
compute_avg_poro_for_region.py
1###########################################################################################
2# This example will calculate the average value of the porosity property for a specified
3# region in the reservoir model. The region is identified by its EQLNUM value.
4###########################################################################################
5
6import rips
7
8resinsight = rips.Instance.find()
9
10cases = resinsight.project.cases()
11
12time_step = 0
13region_number = 2
14
15for case in cases:
16 sum_poro = 0.0
17 cell_cout = 0
18
19 eqlnum = case.active_cell_property("STATIC_NATIVE", "EQLNUM", time_step)
20 poro = case.active_cell_property("STATIC_NATIVE", "PORO", time_step)
21 if len(eqlnum) != len(poro):
22 print("Size of eqlnum and poro is not identical.")
23 break
24
25 for i in range(len(eqlnum)):
26 if eqlnum[i] == region_number:
27 sum_poro += poro[i]
28 cell_cout += 1
29
30 # Calculate the average porosity for the specified region
31 if cell_cout > 0:
32 average_poro = sum_poro / cell_cout
33 print(
34 f"Case {case.id}: Cell count {cell_cout} Average PORO for region {region_number} = {average_poro}"
35 )
Create Corner Point Grid
create_corner_point_grid.py
1######################################################################
2# This script creates a corner point grid from a Eclipse coord, zcorn
3# and actnum configuration.
4######################################################################
5import rips
6from xtgeo.grid3d._egrid import EGrid
7from xtgeo.io._file import FileFormat
8import numpy as np
9
10grid_filepath = "/home/resinsight/testdata/01_drogon_ahm/realization-0/iter-0/eclipse/model/DROGON-0.EGRID"
11
12name = "DROGON-0 from python"
13
14grid = EGrid.from_file(grid_filepath, fileformat=FileFormat.EGRID)
15print("Grid: ", grid)
16print("Grid type: ", type(grid))
17print("coord: ", grid.coord.shape, grid.coord.dtype)
18print("zcorn:", grid.zcorn.shape, grid.zcorn.dtype)
19print("actnum: ", grid.actnum.shape, grid.actnum.dtype)
20
21resinsight = rips.Instance.find()
22
23project = resinsight.project
24
25coord = np.ascontiguousarray(grid.coord, dtype=np.float32)
26zcorn = np.ascontiguousarray(grid.zcorn, dtype=np.float32)
27actnum = np.ascontiguousarray(grid.actnum, dtype=np.int32)
28
29
30print("coordsv: ", len(coord), type(coord[0]))
31print("zcornsv: ", len(zcorn), type(zcorn[0]))
32print("actnumsv: ", len(actnum), type(actnum[0]))
33
34
35print("Grid dimensions: ", grid.dimensions)
36nx = grid.dimensions.ncol
37ny = grid.dimensions.nrow
38nz = grid.dimensions.nlay
39
40project.create_corner_point_grid(name, nx, ny, nz, coord, zcorn, actnum)
Export Corner Point Grid
export_corner_point_grid.py
1######################################################################
2# This script demonstrates how to export corner point grid data from
3# ResInsight cases and recreate new grids from the exported data.
4#
5# This is the inverse operation of create_corner_point_grid.py - it
6# extracts COORD, ZCORN, and ACTNUM arrays from existing Eclipse cases.
7######################################################################
8
9import rips
10
11
12def validate_grid_dimensions(coord_array, zcorn_array, actnum_array, nx, ny, nz):
13 """
14 Validate that the exported arrays match the expected dimensions.
15
16 Args:
17 coord_array: COORD array (coordinate lines)
18 zcorn_array: ZCORN array (corner depths)
19 actnum_array: ACTNUM array (active cell flags)
20 nx, ny, nz: Grid dimensions
21
22 Returns:
23 bool: True if arrays match expected dimensions
24 """
25 total_cells = nx * ny * nz
26 expected_coord_size = (nx + 1) * (ny + 1) * 6 # 6 values per coordinate line
27 expected_zcorn_size = nx * ny * nz * 8 # 8 corner depths per cell
28
29 return (
30 len(actnum_array) == total_cells
31 and len(coord_array) == expected_coord_size
32 and len(zcorn_array) == expected_zcorn_size
33 )
34
35
36def main():
37 # Connect to ResInsight
38 resinsight = rips.Instance.find()
39 if resinsight is None:
40 print("Starting ResInsight...")
41 resinsight = rips.Instance.launch(console=True)
42
43 project = resinsight.project
44 if not project.cases():
45 print("No cases in current project")
46 return
47
48 original_case = project.cases()[0]
49 if original_case is None:
50 print("Failed to load case")
51 return
52
53 print(f"Loaded case: {original_case.name}")
54
55 # Get basic case information
56 cell_count = original_case.cell_count()
57 print("Case information:")
58 print(f" Total cells: {cell_count.reservoir_cell_count}")
59 print(f" Active cells: {cell_count.active_cell_count}")
60
61 # Export corner point grid data
62 print("\nExporting corner point grid data...")
63 zcorn, coord, actnum, nx, ny, nz = original_case.export_corner_point_grid()
64
65 print("Exported arrays:")
66 print(f" ZCORN: {len(zcorn):,} values (corner depths)")
67 print(f" COORD: {len(coord):,} values (coordinate lines)")
68 print(f" ACTNUM: {len(actnum):,} values (active cell flags)")
69
70 # Grid dimensions are now returned directly from the export method!
71 print(f"\nGrid dimensions from export: {nx} x {ny} x {nz} = {nx * ny * nz:,} cells")
72
73 # Validate that the arrays match the expected dimensions
74 if validate_grid_dimensions(coord, zcorn, actnum, nx, ny, nz):
75 print("✓ Array sizes match expected dimensions perfectly")
76 else:
77 print("⚠ Array sizes don't match expected dimensions - this shouldn't happen")
78 return
79
80 # Create a new corner point grid from the exported data
81 print("\nCreating new corner point grid from exported data...")
82 recreated_name = f"{original_case.name}_Recreated"
83 recreated_case = project.create_corner_point_grid(
84 recreated_name, nx, ny, nz, coord, zcorn, actnum
85 )
86
87 if recreated_case is None:
88 print("Failed to create recreated case")
89 return
90
91 print(f"Created recreated case: {recreated_case.name}")
92
93 # Compare the two grids
94 print("\nComparing original and recreated grids:")
95
96 orig_cell_count = original_case.cell_count()
97 recreated_cell_count = recreated_case.cell_count()
98
99 print("Original grid:")
100 print(f" Total cells: {orig_cell_count.reservoir_cell_count:,}")
101 print(f" Active cells: {orig_cell_count.active_cell_count:,}")
102
103 print("Recreated grid:")
104 print(f" Total cells: {recreated_cell_count.reservoir_cell_count:,}")
105 print(f" Active cells: {recreated_cell_count.active_cell_count:,}")
106
107 # Get coordinate ranges for comparison
108 print("\nCoordinate ranges:")
109
110 # Sample some coordinates for comparison
111 orig_bbox = original_case.reservoir_boundingbox()
112 recreated_bbox = recreated_case.reservoir_boundingbox()
113
114 print("Original bounding box:")
115 print(f" X: {orig_bbox.min_x:.2f} to {orig_bbox.max_x:.2f}")
116 print(f" Y: {orig_bbox.min_y:.2f} to {orig_bbox.max_y:.2f}")
117 print(f" Z: {orig_bbox.min_z:.2f} to {orig_bbox.max_z:.2f}")
118
119 print("Recreated bounding box:")
120 print(f" X: {recreated_bbox.min_x:.2f} to {recreated_bbox.max_x:.2f}")
121 print(f" Y: {recreated_bbox.min_y:.2f} to {recreated_bbox.max_y:.2f}")
122 print(f" Z: {recreated_bbox.min_z:.2f} to {recreated_bbox.max_z:.2f}")
123
124
125if __name__ == "__main__":
126 main()
Fault Distance
fault_distance.py
1###################################################################################
2# This example prints the distance to and the name of the fault closest to a point
3###################################################################################
4
5import rips
6
7resinsight = rips.Instance.find()
8if resinsight is None:
9 exit(1)
10
11cases = resinsight.project.cases()
12if len(cases) == 0:
13 exit(1)
14
15case = cases[0]
16print("Using case: " + case.name)
17
18# random test point (positive Z for depth)
19point_x = 5039.84
20point_y = 6303.76
21point_z = 4144.21
22
23print("Looking for closest fault to point %f, %f, %f:" % (point_x, point_y, point_z))
24
25faultname, distance, facename = case.distance_to_closest_fault(
26 point_x, point_y, point_z
27)
28
29if facename == "":
30 print("- No fault found!")
31else:
32 print(
33 "- Distance to closest fault %s is %f, closest face direction is %s"
34 % (faultname, distance, facename)
35 )
Grid Information
grid_information.py
1######################################################################################
2# This example prints information about the grids of all cases in the current project
3######################################################################################
4
5import rips
6
7resinsight = rips.Instance.find()
8
9cases = resinsight.project.cases()
10print("Number of cases found: ", len(cases))
11for case in cases:
12 print(case.name)
13 grids = case.grids()
14 print("Number of grids: ", len(grids))
15 for grid in grids:
16 print("Grid dimensions: ", grid.dimensions())
Import Case Properties
import_case_properties.py
1#######################################################
2#
3# This file shows how to import properties for a
4# grid case created with .ROFFASC files
5#
6# Same procedure can also be used for .GRDECL files
7#
8#######################################################
9
10
11# Access to environment variables and path tools
12import os
13import pathlib
14
15# Load ResInsight Processing Server Client Library
16import rips
17
18# Connect to ResInsight instance
19resinsight = rips.Instance.find()
20
21# This requires the TestModels to be installed with ResInsight (RESINSIGHT_BUNDLE_TESTMODELS):
22resinsight_exe_path = os.environ.get("RESINSIGHT_EXECUTABLE")
23
24# Get the TestModels path from the executable path
25resinsight_install_path = pathlib.PurePath(
26 os.path.dirname(resinsight_exe_path)
27).as_posix()
28
29test_models_path = resinsight_install_path + "/TestModels/"
30
31# Get the .roff case
32roff_case_path = os.path.join(
33 test_models_path, "reek/reek_box_grid_w_out_props.roffasc"
34)
35
36roff_case = resinsight.project.load_case(roff_case_path)
37
38# PORO and EQLNUM should not be among available properties yet
39print("Available properties:")
40for prop in roff_case.available_properties("INPUT_PROPERTY"):
41 print(prop)
42
43# Import properties with file paths
44poro_property_path = os.path.join(
45 test_models_path, "reek/reek_box_PORO_property.roffasc"
46)
47eqlnum_property_path = os.path.join(
48 test_models_path, "reek/reek_box_EQLNUM_property.roffasc"
49)
50
51imported_names = roff_case.import_properties(
52 file_names=[poro_property_path, eqlnum_property_path]
53)
54
55print("Imported properties:")
56for name in imported_names.values:
57 print(name)
58
59# PORO and EQLNUM should now be among available properties
60print("Available properties:")
61for prop in roff_case.available_properties("INPUT_PROPERTY"):
62 print(prop)
Input Prop Test Async
input_prop_test_async.py
1########################################################################################
2# This example generates a derived property in an asynchronous manner
3# Meaning it does not wait for all the data for each stage to be read before proceeding
4########################################################################################
5import rips
6import time
7
8
9# Internal function for creating a result from a small chunk of poro and permx results
10# The return value of the function is a generator for the results rather than the result itself.
11def create_result(poro_chunks, permx_chunks):
12 # Loop through all the chunks of poro and permx in order
13 for poroChunk, permxChunk in zip(poro_chunks, permx_chunks):
14 resultChunk = []
15 # Loop through all the values inside the chunks, in order
16 for poro, permx in zip(poroChunk.values, permxChunk.values):
17 resultChunk.append(poro * permx)
18 # Return a generator object that behaves like a Python iterator
19 yield resultChunk
20
21
22resinsight = rips.Instance.find()
23start = time.time()
24case = resinsight.project.cases()[0]
25
26# Get a generator for the poro results. The generator will provide a chunk each time it is iterated
27poro_chunks = case.active_cell_property_async("STATIC_NATIVE", "PORO", 0)
28# Get a generator for the permx results. The generator will provide a chunk each time it is iterated
29permx_chunks = case.active_cell_property_async("STATIC_NATIVE", "PERMX", 0)
30
31# Send back the result with the result provided by a generator object.
32# Iterating the result generator will cause the script to read from the poro and permx generators
33# And return the result of each iteration
34case.set_active_cell_property_async(
35 create_result(poro_chunks, permx_chunks), "GENERATED", "POROPERMXAS", 0
36)
37
38end = time.time()
39print("Time elapsed: ", end - start)
40print("Transferred all results back")
41view = case.views()[0].apply_cell_result("GENERATED", "POROPERMXAS")
Input Prop Test Sync
input_prop_test_sync.py
1########################################################################################
2# This example generates a derived property in an synchronous manner
3# Meaning it completes reading each result before calculating the derived result
4# See InputPropTestAsync for how to do this asynchronously instead.
5########################################################################################
6import rips
7import time
8import grpc
9
10resinsight = rips.Instance.find()
11start = time.time()
12case = resinsight.project.cases()[0]
13
14# Read poro result into list
15poro_results = case.active_cell_property("STATIC_NATIVE", "PORO", 0)
16# Read permx result into list
17permx_results = case.active_cell_property("STATIC_NATIVE", "PERMX", 0)
18
19# Generate output result
20results = []
21for poro, permx in zip(poro_results, permx_results):
22 results.append(poro * permx)
23
24try:
25 # Send back output result
26 case.set_active_cell_property(results, "GENERATED", "POROPERMXSY", 0)
27except grpc.RpcError as e:
28 print("Exception Received: ", e)
29
30
31end = time.time()
32print("Time elapsed: ", end - start)
33print("Transferred all results back")
34
35view = case.views()[0].apply_cell_result("GENERATED", "POROPERMXSY")
Result Aliases
result_aliases.py
1#######################################################
2#
3# This file shows how to set up an alias name for
4# a result, so that you could access the data
5# using the alias name.
6#
7# This works for both eclipse and roff cases.
8#
9#######################################################
10
11
12# Access to environment variables and path tools
13import os
14import pathlib
15
16# Load ResInsight Processing Server Client Library
17import rips
18
19# Connect to ResInsight instance
20resinsight = rips.Instance.find()
21
22# This requires the TestModels to be installed with ResInsight
23# (RESINSIGHT_BUNDLE_TESTMODELS):
24resinsight_exe_path = os.environ.get("RESINSIGHT_EXECUTABLE")
25
26# Get the TestModels path from the executable path
27resinsight_install_path = pathlib.PurePath(
28 os.path.dirname(resinsight_exe_path)
29).as_posix()
30
31test_models_path = resinsight_install_path + "/TestModels/"
32
33# Get the .roff case
34roff_case_path = os.path.join(test_models_path, "reek/reek_box_grid_w_props.roff")
35
36roff_case = resinsight.project.load_case(roff_case_path)
37
38# Print all available properties
39print("Results on file:")
40for prop in roff_case.available_properties("STATIC_NATIVE"):
41 print(prop)
42
43# The name "DYBDE" should point to the "DEPTH" result
44roff_case.add_result_alias("DEPTH", "DYBDE")
45
46# The name "PERMX" should point to the "BOTTOM" result
47roff_case.add_result_alias("BOTTOM", "PERMX")
48
49# Print all available properties, now with two additional props
50print("Results including aliases:")
51for prop in roff_case.available_properties("STATIC_NATIVE"):
52 print(prop)
53
54real_result = roff_case.grid_property("STATIC_NATIVE", "BOTTOM", 0)
55alias_result = roff_case.grid_property("STATIC_NATIVE", "PERMX", 0)
56
57if real_result[40] == alias_result[40]:
58 print("Result values at index 40 match!")
59
60# Remove our aliases
61roff_case.clear_result_aliases()
62
63# Print all available properties, now just the original ones
64print("Original results:")
65for prop in roff_case.available_properties("STATIC_NATIVE"):
66 print(prop)
67
68try:
69 alias_result = roff_case.grid_property("STATIC_NATIVE", "PERMX", 0)
70except Exception:
71 print("Result PERMX no longer exists!")
Selected Cells
selected_cells.py
1############################################################################
2# This example prints center and corners for the currently selected cells
3# in ResInsight
4############################################################################
5
6import rips
7
8resinsight = rips.Instance.find()
9if resinsight is not None:
10 cases = resinsight.project.cases()
11
12 print("Got " + str(len(cases)) + " cases: ")
13 for case in cases:
14 print(case.name)
15 cells = case.selected_cells()
16 print("Found " + str(len(cells)) + " selected cells")
17
18 time_step_info = case.time_steps()
19
20 for idx, cell in enumerate(cells):
21 print(
22 "Selected cell: [{}, {}, {}] grid: {}".format(
23 cell.ijk.i + 1, cell.ijk.j + 1, cell.ijk.k + 1, cell.grid_index
24 )
25 )
26
27 # Get the grid and dimensions
28 grid = case.grids()[cell.grid_index]
29 dimensions = grid.dimensions()
30
31 # Map ijk to cell index
32 cell_index = (
33 dimensions.i * dimensions.j * cell.ijk.k
34 + dimensions.i * cell.ijk.j
35 + cell.ijk.i
36 )
37
38 # Print the cell center
39 cell_centers = grid.cell_centers()
40 cell_center = cell_centers[cell_index]
41 print(
42 "Cell center: [{}, {}, {}]".format(
43 cell_center.x, cell_center.y, cell_center.z
44 )
45 )
46
47 # Print the cell corners
48 cell_corners = grid.cell_corners()[cell_index]
49 print("Cell corners:")
50 print("c0:\n" + str(cell_corners.c0))
51 print("c1:\n" + str(cell_corners.c1))
52 print("c2:\n" + str(cell_corners.c2))
53 print("c3:\n" + str(cell_corners.c3))
54 print("c4:\n" + str(cell_corners.c4))
55 print("c5:\n" + str(cell_corners.c5))
56 print("c6:\n" + str(cell_corners.c6))
57 print("c7:\n" + str(cell_corners.c7))
58
59 for tidx, timestep in enumerate(time_step_info):
60 # Read the full SOIL result for time step
61 soil_results = case.selected_cell_property(
62 "DYNAMIC_NATIVE", "SOIL", tidx
63 )
64 print(
65 "SOIL: {} ({}.{}.{})".format(
66 soil_results[idx], timestep.year, timestep.month, timestep.day
67 )
68 )
Set Cell Result
set_cell_result.py
1######################################################################
2# This script applies a cell result to the first view in the project
3######################################################################
4import rips
5
6resinsight = rips.Instance.find()
7
8view = resinsight.project.views()[0]
9view.apply_cell_result(result_type="STATIC_NATIVE", result_variable="DX")
Set Flow Diagnostics Result
set_flow_diagnostics_result.py
1######################################################################
2# This script applies a flow diagnostics cell result to the first view in the project
3######################################################################
4
5# Load ResInsight Processing Server Client Library
6import rips
7
8# Connect to ResInsight instance
9resinsight = rips.Instance.find()
10
11view = resinsight.project.view(view_id=1)
12# view.apply_flow_diagnostics_cell_result(result_variable='Fraction',
13# selection_mode='FLOW_TR_INJ_AND_PROD')
14
15# Example of setting individual wells. Commented out because well names are case specific.
16view.apply_flow_diagnostics_cell_result(
17 result_variable="Fraction",
18 selection_mode="FLOW_TR_BY_SELECTION",
19 injectors=["C-1H", "C-2H", "F-2H"],
20 producers=["B-1AH", "B-3H", "D-1H"],
21)
Set Grid Properties
set_grid_properties.py
1######################################################################
2# This script sets values for all grid cells in the first case in the project
3# The script is intended to be used for TEST10K_FLT_LGR_NNC.EGRID
4# This grid case contains one LGR
5######################################################################
6import rips
7
8resinsight = rips.Instance.find()
9
10case = resinsight.project.case(case_id=0)
11grid = case.grid()
12grid_cell_count = grid.cell_count()
13print("total cell count : " + str(grid_cell_count))
14
15values = []
16for i in range(0, grid_cell_count):
17 values.append(i % 2 * 0.75)
18
19# Assign value to IJK grid cell at (31, 53, 21)
20grid = case.grid()
21property_data_index = grid.property_data_index_from_ijk(31, 53, 21)
22values[property_data_index] = 1.5
23
24print("Applying values to main grid")
25case.set_grid_property(values, "STATIC_NATIVE", "MY_DATA", 0)
26
27values_from_ri = case.grid_property("STATIC_NATIVE", "MY_DATA", 0)
28assert values[property_data_index] == values_from_ri[property_data_index]
29
30# Get LGR grid as grid index 1
31grid = case.grid(1)
32grid_cell_count = grid.cell_count()
33print("lgr cell count : " + str(grid_cell_count))
34
35values = []
36for i in range(0, grid_cell_count):
37 values.append(i % 3 * 0.75)
38
39print("Applying values to LGR grid")
40case.set_grid_property(values, "STATIC_NATIVE", "MY_DATA", 0, 1)
41values_from_ri = case.grid_property("STATIC_NATIVE", "MY_DATA", 0, 1)
Soil Average Async
soil_average_async.py
1###########################################################################################
2# This example will asynchronously calculate the average value for SOIL for all time steps
3###########################################################################################
4
5import rips
6import time
7
8resinsight = rips.Instance.find()
9
10start = time.time()
11
12# Get the case with case id 0
13case = resinsight.project.case(case_id=0)
14
15# Get a list of all time steps
16timeSteps = case.time_steps()
17
18averages = []
19for i in range(0, len(timeSteps)):
20 # Get the results from time step i asynchronously
21 # It actually returns a generator object almost immediately
22 result_chunks = case.active_cell_property_async("DYNAMIC_NATIVE", "SOIL", i)
23 mysum = 0.0
24 count = 0
25 # Loop through and append the average. each time we loop resultChunks
26 # We will trigger a read of the input data, meaning the script will start
27 # Calculating averages before the whole resultValue for this time step has been received
28 for chunk in result_chunks:
29 mysum += sum(chunk.values)
30 count += len(chunk.values)
31
32 averages.append(mysum / count)
33
34end = time.time()
35print("Time elapsed: ", end - start)
36print(averages)
Soil Average Sync
soil_average_sync.py
1###########################################################################################
2# This example will synchronously calculate the average value for SOIL for all time steps
3###########################################################################################
4import rips
5import time
6
7resinsight = rips.Instance.find()
8
9start = time.time()
10
11# Get the case with case id 0
12case = resinsight.project.case(case_id=0)
13
14# Get a list of all time steps
15time_steps = case.time_steps()
16
17averages = []
18for i in range(0, len(time_steps)):
19 # Get a list of all the results for time step i
20 results = case.active_cell_property("DYNAMIC_NATIVE", "SOIL", i)
21 mysum = sum(results)
22 averages.append(mysum / len(results))
23
24end = time.time()
25print("Time elapsed: ", end - start)
26print(averages)
Soil Porv Async
soil_porv_async.py
1##############################################################################
2# This example will create a derived result for each time step asynchronously
3##############################################################################
4
5import rips
6import time
7
8
9# Internal function for creating a result from a small chunk of soil and porv results
10# The return value of the function is a generator for the results rather than the result itself.
11def create_result(soil_chunks, porv_chunks):
12 for soil_chunk, porv_chunk in zip(soil_chunks, porv_chunks):
13 resultChunk = []
14 for soil_value, porv_value in zip(soil_chunk.values, porv_chunk.values):
15 resultChunk.append(soil_value * porv_value)
16 # Return a Python generator
17 yield resultChunk
18
19
20resinsight = rips.Instance.find()
21start = time.time()
22case = resinsight.project.cases()[0]
23timeStepInfo = case.time_steps()
24
25# Get a generator for the porv results. The generator will provide a chunk each time it is iterated
26porv_chunks = case.active_cell_property_async("STATIC_NATIVE", "PORV", 0)
27
28# Read the static result into an array, so we don't have to transfer it for each iteration
29# Note we use the async method even if we synchronise here, because we need the values chunked
30# ... to match the soil chunks
31porv_array = []
32for porv_chunk in porv_chunks:
33 porv_array.append(porv_chunk)
34
35for i in range(0, len(timeStepInfo)):
36 # Get a generator object for the SOIL property for time step i
37 soil_chunks = case.active_cell_property_async("DYNAMIC_NATIVE", "SOIL", i)
38 # Create the generator object for the SOIL * PORV derived result
39 result_generator = create_result(soil_chunks, iter(porv_array))
40 # Send back the result asynchronously with a generator object
41 case.set_active_cell_property_async(
42 result_generator, "GENERATED", "SOILPORVAsync", i
43 )
44
45end = time.time()
46print("Time elapsed: ", end - start)
47
48print("Transferred all results back")
49
50view = case.views()[0].apply_cell_result("GENERATED", "SOILPORVAsync")
Soil Porv Sync
soil_porv_sync.py
1##############################################################################
2# This example will create a derived result for each time step synchronously
3##############################################################################
4
5import rips
6import time
7
8resinsight = rips.Instance.find()
9start = time.time()
10case = resinsight.project.cases()[0]
11
12# Read the full porv result
13porv_results = case.active_cell_property("STATIC_NATIVE", "PORV", 0)
14time_step_info = case.time_steps()
15
16for i in range(0, len(time_step_info)):
17 # Read the full SOIl result for time step i
18 soil_results = case.active_cell_property("DYNAMIC_NATIVE", "SOIL", i)
19
20 # Generate the result by looping through both lists in order
21 results = []
22 for soil, porv in zip(soil_results, porv_results):
23 results.append(soil * porv)
24
25 # Send back result
26 case.set_active_cell_property(results, "GENERATED", "SOILPORVSync", i)
27
28end = time.time()
29print("Time elapsed: ", end - start)
30
31print("Transferred all results back")
32
33view = case.views()[0].apply_cell_result("GENERATED", "SOILPORVSync")