Python Examples

This pages is created based on the content in the PythonExamples folder located inside the rips module, made available online for convenience.

All Cases

###################################################################################
# This example will connect to ResInsight, retrieve a list of cases and print info
#
###################################################################################

# Import the ResInsight Processing Server Module
import rips

# Connect to ResInsight
resinsight = rips.Instance.find()
if resinsight is not None:
    # Get a list of all cases
    cases = resinsight.project.cases()

    print("Got " + str(len(cases)) + " cases: ")
    for case in cases:
        print("Case id: " + str(case.id))
        print("Case name: " + case.name)
        print("Case type: " + case.__class__.__name__)
        print("Case file name: " + case.file_path)
        print("Case reservoir bounding box:", case.reservoir_boundingbox())

        timesteps = case.time_steps()
        for t in timesteps:
            print("Year: " + str(t.year))
            print("Month: " + str(t.month))

        if isinstance(case, rips.EclipseCase):
            print("Getting coarsening info for case: ", case.name, case.id)
            coarsening_info = case.coarsening_info()
            if coarsening_info:
                print("Coarsening information:")

            for c in coarsening_info:
                print(
                    "[{}, {}, {}] - [{}, {}, {}]".format(
                        c.min.x, c.min.y, c.min.z, c.max.x, c.max.y, c.max.z
                    )
                )

All Simulation Wells

###################################################################################
# This example will connect to ResInsight, retrieve a list of
# simulation wells and print info
###################################################################################

# Import the ResInsight Processing Server Module
import rips

# Connect to ResInsight
resinsight = rips.Instance.find()
if resinsight is not None:
    # Get a list of all wells
    cases = resinsight.project.cases()

    for case in cases:
        print("Case id: " + str(case.id))
        print("Case name: " + case.name)

        timesteps = case.time_steps()
        sim_wells = case.simulation_wells()
        for sim_well in sim_wells:
            print("Simulation well: " + sim_well.name)

            for tidx, timestep in enumerate(timesteps):
                status = sim_well.status(tidx)
                cells = sim_well.cells(tidx)
                print(
                    "timestep: "
                    + str(tidx)
                    + " type: "
                    + status.well_type
                    + " open: "
                    + str(status.is_open)
                    + " cells:"
                    + str(len(cells))
                )

All Wells

###################################################################################
# This example will connect to ResInsight, retrieve a list of wells and print info
#
###################################################################################

# Import the ResInsight Processing Server Module
import rips

# Connect to ResInsight
resinsight = rips.Instance.find()
if resinsight is not None:
    # Get a list of all wells
    wells = resinsight.project.well_paths()

    print("Got " + str(len(wells)) + " wells: ")
    for well in wells:
        print("Well name: " + well.name)

Alter Wbs Plot

# Load ResInsight Processing Server Client Library
import rips
import tempfile

# Connect to ResInsight instance
resinsight = rips.Instance.find()

# Get the project
project = resinsight.project

# Find all the well bore stability plots in the project
wbsplots = project.descendants(rips.WellBoreStabilityPlot)

# Chose a sensible output folder
dirname = tempfile.gettempdir()

# Loop through all Well Bore Stability plots
for wbsplot in wbsplots:
    # Set depth type a parameter and export snapshot
    wbsplot.depth_type = "TRUE_VERTICAL_DEPTH_RKB"

    # Example of setting parameters for existing plots
    params = wbsplot.parameters()
    params.user_poisson_ratio = 0.12345
    params.update()
    wbsplot.update()
    wbsplot.export_snapshot(export_folder=dirname)

Case Grid Group

import os
import rips

resinsight = rips.Instance.find()

test_model_path = "e:/gitroot-second/ResInsight/TestModels"

case_paths = []
case_paths.append(test_model_path + "/Case_with_10_timesteps/Real0/BRUGGE_0000.EGRID")
case_paths.append(test_model_path + "/Case_with_10_timesteps/Real10/BRUGGE_0010.EGRID")
case_paths.append(test_model_path + "/Case_with_10_timesteps/Real30/BRUGGE_0030.EGRID")
case_paths.append(test_model_path + "/Case_with_10_timesteps/Real40/BRUGGE_0040.EGRID")

for case_path in case_paths:
    assert os.path.exists(
        case_path
    ), "You need to set valid case paths for this script to work"

case_group = resinsight.project.create_grid_case_group(case_paths=case_paths)

case_group.compute_statistics()

view = case_group.views()[0]
view.apply_cell_result("DYNAMIC_NATIVE", "PRESSURE_DEV")

Case Grid Group Generated Results

import os
import rips

resinsight = rips.Instance.find()

# ResInsight includes some test models. Adjust this path to fit your system
test_model_path = "e:/gitroot-second/ResInsight/TestModels"

case_paths = []
case_paths.append(test_model_path + "/Case_with_10_timesteps/Real0/BRUGGE_0000.EGRID")
case_paths.append(test_model_path + "/Case_with_10_timesteps/Real10/BRUGGE_0010.EGRID")
case_paths.append(test_model_path + "/Case_with_10_timesteps/Real30/BRUGGE_0030.EGRID")
case_paths.append(test_model_path + "/Case_with_10_timesteps/Real40/BRUGGE_0040.EGRID")

for case_path in case_paths:
    assert os.path.exists(
        case_path
    ), "You need to set valid case paths for this script to work"

case_group = resinsight.project.create_grid_case_group(case_paths=case_paths)

cases = case_group.descendants(rips.EclipseCase)
print("Got " + str(len(cases)) + " cases: ")

for case in cases:
    time_step_info = case.time_steps()
    porv_results = case.active_cell_property("STATIC_NATIVE", "PORV", 0)

    for time_step_index in range(0, len(time_step_info)):
        pressure_results = case.active_cell_property(
            "DYNAMIC_NATIVE", "PRESSURE", time_step_index
        )

        results = []
        for pressure, porv in zip(pressure_results, porv_results):
            results.append(pressure * porv)

        # set the computed values in the case
        case.set_active_cell_property(
            results, "GENERATED", "PRESSURE_PORV", time_step_index
        )

    print(
        "Case id: " + str(case.id),
        "  Case name: " + case.name,
        " : Calculation complete",
    )


print("Transferred all results back to ResInsight")

# one of "GENERATED", "DYNAMIC_NATIVE", "STATIC_NATIVE", "IMPORTED"
# https://api.resinsight.org/en/main/rips.html#result-definition
property_type = "GENERATED"

property_name = "PRESSURE_PORV"

statistics_case = case_group.create_statistics_case()
statistics_case.set_source_properties(property_type, [property_name])
statistics_case.compute_statistics()

view = statistics_case.create_view()
statistics_property_name = property_name + "_MEAN"
view.apply_cell_result(
    result_type=property_type, result_variable=statistics_property_name
)

Case Info Streaming Example

###############################################################################
# This example will get the cell info for the active cells for the first case
###############################################################################

# Import the ResInsight Processing Server Module
import rips

# Connect to ResInsight
resinsight = rips.Instance.find()

# Get the first case. This will fail if you haven't loaded any cases
case = resinsight.project.cases()[0]

# Get the cell count object
cell_counts = case.cell_count()
print("Number of active cells: " + str(cell_counts.active_cell_count))
print("Total number of reservoir cells: " + str(cell_counts.reservoir_cell_count))

# Get information for all active cells
active_cell_infos = case.cell_info_for_active_cells()

# A simple check on the size of the cell info
assert cell_counts.active_cell_count == len(active_cell_infos)

# Print information for the first active cell
print("First active cell: ")
print(active_cell_infos[0])

Cell Result Data

######################################################################
# This script retrieves cell result data and alters it
######################################################################
import rips

resinsight = rips.Instance.find()

view = resinsight.project.views()[0]
results = view.cell_result_data()
print("Number of result values: ", len(results))

newresults = []
for i in range(0, len(results)):
    newresults.append(results[i] * -1.0)
view.set_cell_result_data(newresults)

Command Example

###############################################################################
# This example will show setting time step, window size and export snapshots and properties
###############################################################################
import os
import tempfile
import rips

# Load instance
resinsight = rips.Instance.find()

# Set window sizes
resinsight.set_main_window_size(width=800, height=500)
resinsight.set_plot_window_size(width=1000, height=1000)


# Retrieve first case
case = resinsight.project.cases()[0]

# Get a view
view1 = case.views()[0]

# Clone the view
view2 = view1.clone()

# Set the time step for view1 only
view1.set_time_step(time_step=2)

# Set cell result to SOIL
view1.apply_cell_result(result_type="DYNAMIC_NATIVE", result_variable="SOIL")


# Create a temporary directory which will disappear at the end of this script
# If you want to keep the files, provide a good path name instead of tmpdirname
with tempfile.TemporaryDirectory(prefix="rips") as tmpdirname:
    print("Temporary folder: ", tmpdirname)

    # Set export folder for snapshots and properties
    resinsight.set_export_folder(export_type="SNAPSHOTS", path=tmpdirname)
    resinsight.set_export_folder(export_type="PROPERTIES", path=tmpdirname)

    # Export all snapshots
    resinsight.project.export_snapshots()

    assert len(os.listdir(tmpdirname)) > 0

    # Export properties in the view
    view1.export_property()

    # Check that the exported file exists
    expected_file_name = case.name + "-" + str("3D_View") + "-" + "T2" + "-SOIL"
    full_path = tmpdirname + "/" + expected_file_name

    # Print contents of temporary folder
    print(os.listdir(tmpdirname))

    assert os.path.exists(full_path)

Create And Export Stim Plan Model

# Load ResInsight Processing Server Client Library
import rips
import tempfile
from os.path import expanduser
from pathlib import Path

# Connect to ResInsight instance
resinsight = rips.Instance.find()
# Example code
project = resinsight.project

# Look for input files in the home directory of the user
home_dir = expanduser("~")
elastic_properties_file_path = (Path(home_dir) / "elastic_properties.csv").as_posix()
print("Elastic properties file path:", elastic_properties_file_path)

facies_properties_file_path = (Path(home_dir) / "facies_id.roff").as_posix()
print("Facies properties file path:", facies_properties_file_path)

# Find a case
cases = resinsight.project.cases()
case = cases[1]

# Use the last time step
time_steps = case.time_steps()
time_step = time_steps[len(time_steps) - 1]


# Create stim plan model template
fmt_collection = project.descendants(rips.StimPlanModelTemplateCollection)[0]
stim_plan_model_template = fmt_collection.append_stim_plan_model_template(
    eclipse_case=case,
    time_step=time_step,
    elastic_properties_file_path=elastic_properties_file_path,
    facies_properties_file_path=facies_properties_file_path,
)
stim_plan_model_template.overburden_formation = "Garn"
stim_plan_model_template.overburden_facies = "Shale"
stim_plan_model_template.underburden_formation = "Garn"
stim_plan_model_template.underburden_facies = "Shale"
stim_plan_model_template.overburden_height = 68
stim_plan_model_template.update()
print("Overburden: ", stim_plan_model_template.overburden_formation)


# Set eclipse result for facies definition
eclipse_result = stim_plan_model_template.facies_properties().facies_definition()
eclipse_result.result_type = "INPUT_PROPERTY"
eclipse_result.result_variable = "OPERNUM_1"
eclipse_result.update()

# Set eclipse result for non-net layers
non_net_layers = stim_plan_model_template.non_net_layers()
non_net_layers_result = non_net_layers.facies_definition()
non_net_layers_result.result_type = "STATIC_NATIVE"
non_net_layers_result.result_variable = "NTG"
non_net_layers_result.update()
non_net_layers.formation = "Not"
non_net_layers.facies = "Shale"
non_net_layers.update()

# Add some pressure table items
pressure_table = stim_plan_model_template.pressure_table()
pressure_table.add_pressure(depth=2800.0, initial_pressure=260.0, pressure=261.0)
pressure_table.add_pressure(depth=3000.0, initial_pressure=270.0, pressure=273.0)
pressure_table.add_pressure(depth=3400.0, initial_pressure=274.0, pressure=276.0)
pressure_table.add_pressure(depth=3800.0, initial_pressure=276.0, pressure=280.0)

print("Pressure table ({} items)".format(len(pressure_table.items())))
for item in pressure_table.items():
    print(
        "TDVMSL [m]: {} Initial Pressure: {} Pressure: {}".format(
            item.depth, item.initial_pressure, item.pressure
        )
    )

# Add some scaling factors
elastic_properties = stim_plan_model_template.elastic_properties()
elastic_properties.add_property_scaling(
    formation="Garn", facies="Calcite", property="YOUNGS_MODULUS", scale=1.44
)


well_name = "B-2 H"

# Find a well
well_path = project.well_path_by_name(well_name)
print("well path:", well_path)
stim_plan_model_collection = project.descendants(rips.StimPlanModelCollection)[0]


export_folder = tempfile.gettempdir()

stim_plan_models = []

# Create and export a StimPlan model for each depth
measured_depths = [3200.0, 3400.0, 3600.0]
for measured_depth in measured_depths:
    # Create stim plan model at a give measured depth
    stim_plan_model = stim_plan_model_collection.append_stim_plan_model(
        well_path=well_path,
        measured_depth=measured_depth,
        stim_plan_model_template=stim_plan_model_template,
    )
    stim_plan_models.append(stim_plan_model)

    # Make the well name safer to use as a directory path
    well_name_part = well_name.replace(" ", "_")
    directory_path = Path(export_folder) / "{}_{}".format(
        well_name_part, int(measured_depth)
    )

    # Create the folder
    directory_path.mkdir(parents=True, exist_ok=True)

    print("Exporting fracture model to: ", directory_path)
    stim_plan_model.export_to_file(directory_path=directory_path.as_posix())

    # Create a fracture mode plot
    stim_plan_model_plot_collection = project.descendants(
        rips.StimPlanModelPlotCollection
    )[0]
    stim_plan_model_plot = stim_plan_model_plot_collection.append_stim_plan_model_plot(
        stim_plan_model=stim_plan_model
    )

    print("Exporting fracture model plot to: ", directory_path)
    stim_plan_model_plot.export_snapshot(export_folder=directory_path.as_posix())


print("Setting measured depth and perforation length.")
stim_plan_models[0].measured_depth = 3300.0
stim_plan_models[0].perforation_length = 123.445
stim_plan_models[0].update()

Create Intersection

# Load ResInsight Processing Server Client Library
import math, time
import rips

resinsight = rips.Instance.find()

# The coordinates in this example is based on the Drogon test case from Equinor
file_path = "e:/models/from_equinor_sftp/drogon-real0-iter3/DROGON-0.EGRID"

case = resinsight.project.load_case(file_path)

view = case.create_view()
view.set_time_step(2)

intersection_coll = resinsight.project.descendants(rips.IntersectionCollection)[0]

# Add a CurveIntersection and set coordinates for the polyline
intersection = intersection_coll.add_new_object(rips.CurveIntersection)
intersection.points = [
    [45854, 595757, 1500],
    [46493, 534259.1, 1500],
    [46598, 590044.1, 1500],
]
intersection.update()

# Add a new modeled well path
well_path_coll = resinsight.project.descendants(rips.WellPathCollection)[0]
well_path = well_path_coll.add_new_object(rips.ModeledWellPath)
well_path.name = "Test Well-1"
well_path.update()

# Set reference coordinate
geometry = well_path.well_path_geometry()
reference_point = geometry.reference_point
reference_point[0] = 458580
reference_point[1] = 5935514
reference_point[2] = 1742
geometry.update()  # Commit updates back to ResInsight

# Create the first well target at the reference point
coord = [0, 0, 0]
geometry.append_well_target(coord)

# Append well target with fixed azimuth
coord = [2229.10, -833.74, -74.70]
target = geometry.append_well_target(
    coord, use_fixed_azimuth=True, fixed_azimuth_value=45.1
)

# Append well target with fixed inclination
coord = [3403.15, -1938.61, -80.93]
target = geometry.append_well_target(
    coord, use_fixed_inclination=True, fixed_inclination_value=115.2
)

coord = [4577.21, -3043.47, -87.15]
target = geometry.append_well_target(coord)
geometry.update()

# Read out estimated dogleg and azimuth/inclination for well targets
for w in geometry.well_path_targets():
    print(
        "DL1:{}   DL2:{}   Azi: {}   Incl: {}".format(
            w.estimated_dogleg1,
            w.estimated_dogleg2,
            w.estimated_azimuth,
            w.estimated_inclination,
        )
    )

# Add a curve intersection based on the modeled well path
well_path_intersection = intersection_coll.add_new_object(rips.CurveIntersection)
well_path_intersection.type = "CS_WELL_PATH"
well_path_intersection.well_path = well_path
well_path_intersection.update()

Create Surface From Thermal Fracture

#!/usr/bin/env python
# coding: utf-8

import rips
import tempfile
from os.path import expanduser
from pathlib import Path
import numpy as np
import pyvista as pv


def generate_surface_from_file(path):
    point_cloud_data = np.loadtxt(path, delimiter=" ", skiprows=1)

    # Get [x, y, z] components in separate matrix
    num_rows = point_cloud_data.shape[0]
    xyz = point_cloud_data[0:num_rows, 0:3]

    # Generate surface
    cloud = pv.PolyData(xyz)
    surf = cloud.delaunay_2d()

    # Read properties names from header data
    f = open(path)
    header = f.readline()
    properties = header.strip().split(" ")

    return (surf, point_cloud_data, properties)


def export_surface_as_ts_file(surf, point_cloud, properties, path):
    # open text file
    text_file = open(path, "w")

    # write GOCAD header
    top_header = """GOCAD TSurf 1
HEADER {
name:MF_027_SU
}
"""

    properties_str = "PROPERTIES " + " ".join(properties)

    bottom_header = """
GOCAD_ORIGINAL_COORDINATE_SYSTEM
NAME Default
AXIS_NAME "X" "Y" "Z"
AXIS_UNIT "m" "m" "m"
ZPOSITIVE Depth
END_ORIGINAL_COORDINATE_SYSTEM
TFACE
"""

    text_file.write(top_header)
    text_file.write(properties_str)
    text_file.write(bottom_header)

    i = 1
    (num_rows, num_props) = point_cloud.shape
    for row in range(0, num_rows):
        x = point_cloud[row, 0]
        y = point_cloud[row, 1]
        z = point_cloud[row, 2]
        txt = "PVRTX {} {:.3f} {:.3f} {:.3f} ".format(i, x, y, z)
        for property_index in range(0, num_props):
            txt += "{:.3f} ".format(point_cloud[row, property_index])
        txt += "\n"
        text_file.write(txt)
        i += 1

    mysurface = surf.faces.reshape(-1, 4)
    for p in mysurface:
        txt = "TRGL {} {} {}\n".format(p[1] + 1, p[2] + 1, p[3] + 1)
        text_file.write(txt)

    text_file.write("END")
    text_file.close()


# Connect to ResInsight instance
resinsight = rips.Instance.find()
project = resinsight.project


fractures = project.descendants(rips.ThermalFractureTemplate)
print("Number of thermal fractures: ", len(fractures))


temp_folder = tempfile.gettempdir()

# Write results to a suitable directory
home_dir = expanduser("~")

for fracture in fractures:
    fracture_name = fracture.user_description

    # Create the ouput directory
    output_directory = (
        Path(home_dir) / "thermal_fracture_surfaces" / "{}".format(fracture_name)
    )

    output_directory.mkdir(parents=True, exist_ok=True)
    print("Creating result directory: ", output_directory.as_posix())

    time_steps = fracture.time_steps().values
    for time_step_index, time_step in enumerate(time_steps):
        print(
            "Generating surface for time step #{}: {}".format(
                time_step_index, time_step
            )
        )
        temp_file_path = Path(temp_folder) / "output.xyz"
        fracture.export_to_file(
            file_path=temp_file_path.as_posix(), time_step=time_step_index
        )

        # Reconstruct a surface from the exported values file
        (surface, point_cloud, properties) = generate_surface_from_file(
            temp_file_path.as_posix()
        )

        # Export surface ts file from the surface data
        output_file_path = output_directory / "time_step_{:03d}.ts".format(
            time_step_index
        )
        export_surface_as_ts_file(
            surface, point_cloud, properties, output_file_path.as_posix()
        )
        print(
            "Wrote surface for time step #{} to {}".format(
                time_step, output_file_path.as_posix()
            )
        )

Create Wbs Plot

import os
import grpc

# Load ResInsight Processing Server Client Library
import rips

# Connect to ResInsight instance
resInsight = rips.Instance.find()

# Get all GeoMech cases
cases = resInsight.project.descendants(rips.GeoMechCase)

# Get all well paths
well_paths = resInsight.project.well_paths()

# Ensure there's at least one well path
if len(well_paths) < 1:
    print("No well paths in project")
    exit(1)

# Create a set of WbsParameters
params = rips.WbsParameters()
params.user_poisson_ratio = 0.23456
params.user_ucs = 123

# Loop through all cases
for case in cases:
    assert isinstance(case, rips.GeoMechCase)
    min_res_depth, max_res_depth = case.reservoir_depth_range()

    # Find a good output path
    case_path = case.file_path
    folder_name = os.path.dirname(case_path)

    # Import formation names
    case.import_formation_names(
        formation_files=[
            "D:/Projects/ResInsight-regression-test/ModelData/norne/Norne_ATW2013.lyr"
        ]
    )

    # create a folder to hold the snapshots
    dirname = os.path.join(folder_name, "snapshots")
    print("Exporting to: " + dirname)

    for well_path in well_paths[0:4]:  # Loop through the first five well paths
        # Create plot with parameters
        wbsplot = case.create_well_bore_stability_plot(
            well_path=well_path.name, time_step=0, parameters=params
        )

Error Handling

###################################################################
# This example demonstrates the use of ResInsight exceptions
# for proper error handling
###################################################################

import rips
import grpc
import tempfile

resinsight = rips.Instance.find()

case = None

# Try loading a non-existing case. We should get a grpc.RpcError exception from the server
try:
    case = resinsight.project.load_case("Nonsense")
except grpc.RpcError as e:
    print(
        "Expected Server Exception Received while loading case: ", e.code(), e.details()
    )

# Try loading well paths from a non-existing folder.  We should get a grpc.RpcError exception from the server
try:
    well_path_files = resinsight.project.import_well_paths(
        well_path_folder="NONSENSE/NONSENSE"
    )
except grpc.RpcError as e:
    print(
        "Expected Server Exception Received while loading wellpaths: ",
        e.code(),
        e.details(),
    )

# Try loading well paths from an existing but empty folder. We should get a warning.
try:
    with tempfile.TemporaryDirectory() as tmpdirname:
        well_path_files = resinsight.project.import_well_paths(
            well_path_folder=tmpdirname
        )
        assert len(well_path_files) == 0
        assert resinsight.project.has_warnings()
        print("Should get warnings below")
        for warning in resinsight.project.warnings():
            print(warning)
except grpc.RpcError as e:
    print("Unexpected Server Exception caught!!!", e)

case = resinsight.project.case(case_id=0)
if case is not None:
    results = case.active_cell_property("STATIC_NATIVE", "PORO", 0)
    active_cell_count = len(results)

    # Send the results back to ResInsight inside try / except construct
    try:
        case.set_active_cell_property(results, "GENERATED", "POROAPPENDED", 0)
        print("Everything went well as expected")
    except:  # Match any exception, but it should not happen
        print("Ooops!")

    # Add another value, so this is outside the bounds of the active cell result storage
    results.append(1.0)

    # This time we should get a grpc.RpcError exception, which is a server side error.
    try:
        case.set_active_cell_property(results, "GENERATED", "POROAPPENDED", 0)
        print("Everything went well??")
    except grpc.RpcError as e:
        print("Expected Server Exception Received: ", e)
    except IndexError:
        print("Got index out of bounds error. This shouldn't happen here")

    # With a chunk size exactly matching the active cell count the server will not
    # be able to see any error as it will successfully close the stream after receiving
    # the correct number of values, even if the python client has more chunks to send
    case.chunk_size = active_cell_count

    try:
        case.set_active_cell_property(results, "GENERATED", "POROAPPENDED", 0)
        print("Everything went well??")
    except grpc.RpcError as e:
        print("Got unexpected server exception", e, "This should not happen now")
    except IndexError:
        print("Got expected index out of bounds error on client side")

Export Contour Maps

# Load ResInsight Processing Server Client Library
import rips
import tempfile
import pathlib

# Connect to ResInsight instance
resInsight = rips.Instance.find()

# Data will be written to temp
tmpdir = pathlib.Path(tempfile.gettempdir())

# Find all eclipse contour maps of the project
contour_maps = resInsight.project.descendants(rips.EclipseContourMap)
print("Number of eclipse contour maps:", len(contour_maps))

# Export the contour maps to a text file
for index, contour_map in enumerate(contour_maps):
    filename = "eclipse_contour_map" + str(index) + ".txt"
    filepath = tmpdir / filename
    print("Exporting to:", filepath)
    contour_map.export_to_text(str(filepath))

# The contour maps is also available for a Case
cases = resInsight.project.cases()
for case in cases:
    contour_maps = case.descendants(rips.GeoMechContourMap)
    # Export the contour maps to a text file
    for index, contour_map in enumerate(contour_maps):
        filename = "geomech_contour_map" + str(index) + ".txt"
        filepath = tmpdir / filename
        print("Exporting to:", filepath)
        contour_map.export_to_text(str(filepath))

Export Plots

# Import the tempfile module
import tempfile

# Load ResInsight Processing Server Client Library
import rips

# Connect to ResInsight instance
resInsight = rips.Instance.find()

# Get a list of all plots
plots = resInsight.project.plots()

export_folder = tempfile.mkdtemp()

print("Exporting to: " + export_folder)

for plot in plots:
    plot.export_snapshot(export_folder=export_folder)
    plot.export_snapshot(export_folder=export_folder, output_format="PDF")
    if isinstance(plot, rips.WellLogPlot):
        plot.export_data_as_las(export_folder=export_folder)
        plot.export_data_as_ascii(export_folder=export_folder)

Export Snapshots

############################################################################
# This script will export snapshots for two properties in every loaded case
# And put them in a snapshots folder in the same folder as the case grid
############################################################################
import os
import rips

# Load instance
resinsight = rips.Instance.find()
cases = resinsight.project.cases()

# Set main window size
resinsight.set_main_window_size(width=800, height=500)

n = 5  # every n-th time_step for snapshot
property_list = ["SOIL", "PRESSURE"]  # list of parameter for snapshot

print("Looping through cases")
for case in cases:
    print("Case name: ", case.name)
    print("Case id: ", case.id)
    # Get grid path and its folder name
    case_path = case.file_path
    folder_name = os.path.dirname(case_path)

    # create a folder to hold the snapshots
    dirname = os.path.join(folder_name, "snapshots")

    if os.path.exists(dirname) is False:
        os.mkdir(dirname)

    print("Exporting to folder: " + dirname)
    resinsight.set_export_folder(export_type="SNAPSHOTS", path=dirname)

    time_steps = case.time_steps()
    print("Number of time_steps: " + str(len(time_steps)))

    for view in case.views():
        for property in property_list:
            view.apply_cell_result(
                result_type="DYNAMIC_NATIVE", result_variable=property
            )
        for time_step in range(0, len(time_steps), 10):
            view.set_time_step(time_step=time_step)
            view.export_snapshot()

Export Well Path Completions

############################################################################
# This script will export completions for a well path for all cases in the project
#
############################################################################

import os
import rips

# Load instance
resinsight = rips.Instance.find()
cases = resinsight.project.cases()

for case in cases:
    print("Case name: ", case.name)
    print("Case id: ", case.id)

    case.export_well_path_completions(
        time_step=0,
        well_path_names=["Well-1"],
        file_split="UNIFIED_FILE",
        include_perforations=True,
        custom_file_name="d:/scratch/well_path_export/myfile.myext",
    )

Generate Ensemble Of Well Logs

# Load ResInsight Processing Server Client Library
import rips
import tempfile
from os.path import expanduser
from pathlib import Path

# Connect to ResInsight instance
resinsight = rips.Instance.find()


home_dir = expanduser("~")


properties = [
    ("STATIC_NATIVE", "INDEX_K", 0),
    ("STATIC_NATIVE", "PORO", 0),
    ("STATIC_NATIVE", "PERMX", 0),
    ("DYNAMIC_NATIVE", "PRESSURE", 0),
]

export_folder = tempfile.mkdtemp()

directory_path = "resprojects/webviz-subsurface-testdata/reek_history_match/"


case_file_paths = []
num_realizations = 9
num_iterations = 4


for realization in range(0, num_realizations):
    for iteration in range(0, num_iterations):
        realization_dir = "realization-" + str(realization)
        iteration_dir = "iter-" + str(iteration)
        egrid_name = "eclipse/model/5_R001_REEK-" + str(realization) + ".EGRID"
        path = Path(
            home_dir, directory_path, realization_dir, iteration_dir, egrid_name
        )
        case_file_paths.append(path)

for path in case_file_paths:
    # Load a case
    path_name = path.as_posix()
    grid_only = True
    case = resinsight.project.load_case(path_name, grid_only)

    # Load some wells
    well_paths = resinsight.project.import_well_paths(
        well_path_files=[
            Path(home_dir, directory_path, "wellpaths", "Well-1.dev").as_posix(),
            Path(home_dir, directory_path, "wellpaths", "Well-2.dev").as_posix(),
        ]
    )

    if resinsight.project.has_warnings():
        for warning in resinsight.project.warnings():
            print(warning)

    well_log_plot_collection = resinsight.project.descendants(
        rips.WellLogPlotCollection
    )[0]

    for well_path in well_paths:
        print(
            "Generating las file for well: " + well_path.name + " in case: " + path_name
        )

        well_log_plot = well_log_plot_collection.new_well_log_plot(case, well_path)

        # Create a track for each property
        for prop_type, prop_name, time_step in properties:
            track = well_log_plot.new_well_log_track(
                "Track: " + prop_name, case, well_path
            )

            c = track.add_extraction_curve(
                case, well_path, prop_type, prop_name, time_step
            )

        parent_path = path.parent
        export_folder_path = Path(parent_path, "lasexport")
        export_folder_path.mkdir(parents=True, exist_ok=True)

        export_folder = export_folder_path.as_posix()
        well_log_plot.export_data_as_las(export_folder=export_folder)

    resinsight.project.close()

Generate Ensemble Surface

# Load ResInsight Processing Server Client Library
import rips
import tempfile
from os.path import expanduser
from pathlib import Path

# Connect to ResInsight instance
resinsight = rips.Instance.find()


home_dir = expanduser("~")

export_folder = tempfile.mkdtemp()

directory_path = "resprojects/webviz-subsurface-testdata/reek_history_match/"
# directory_path = "e:/gitroot/webviz-subsurface-testdata/reek_history_match"


case_file_paths = []
num_realizations = 9
num_iterations = 4


for realization in range(0, num_realizations):
    for iteration in range(0, num_iterations):
        realization_dir = "realization-" + str(realization)
        iteration_dir = "iter-" + str(iteration)
        egrid_name = "eclipse/model/5_R001_REEK-" + str(realization) + ".EGRID"
        path = Path(
            home_dir, directory_path, realization_dir, iteration_dir, egrid_name
        )
        case_file_paths.append(path)

k_indexes = [4, 10]

for path in case_file_paths:
    # Load a case
    path_name = path.as_posix()
    case = resinsight.project.load_case(path_name)

    if resinsight.project.has_warnings():
        for warning in resinsight.project.warnings():
            print(warning)

    surface_collection = resinsight.project.descendants(rips.SurfaceCollection)[0]

    for k_index in k_indexes:
        print("Generating surface K layer " + str(k_index) + " for case " + path_name)

        surface = surface_collection.new_surface(case, k_index)
        print("Surface: ", surface)

        parent_path = path.parent
        export_folder_path = Path(parent_path, "surfaceexport")
        export_folder_path.mkdir(parents=True, exist_ok=True)

        export_file = Path(export_folder_path, "surf_" + str(k_index) + ".ts")
        print("Exporting to " + export_file.as_posix())
        surface.export_to_file(export_file.as_posix())

    # Close project to avoid aggregated memory usage
    # Can be replaced when case.close() is implemented
    resinsight.project.close()

Generate Ensemble Surface Optimized

# Load ResInsight Processing Server Client Library
import rips
import tempfile
from os.path import expanduser
from pathlib import Path

# Connect to ResInsight instance
resinsight = rips.Instance.find()


home_dir = expanduser("~")

export_folder = tempfile.mkdtemp()

directory_path = "resprojects/webviz-subsurface-testdata/reek_history_match/"
# directory_path = "e:/gitroot/webviz-subsurface-testdata/reek_history_match"


case_file_paths = []
num_realizations = 9
num_iterations = 4


for realization in range(0, num_realizations):
    for iteration in range(0, num_iterations):
        realization_dir = "realization-" + str(realization)
        iteration_dir = "iter-" + str(iteration)
        egrid_name = "eclipse/model/5_R001_REEK-" + str(realization) + ".EGRID"
        path = Path(
            home_dir, directory_path, realization_dir, iteration_dir, egrid_name
        )
        case_file_paths.append(path)

k_indexes = [4, 10]

command_router = resinsight.command_router

for path in case_file_paths:
    path_name = path.as_posix()

    command_router.extract_surfaces(path_name, k_indexes)

Grid Information

######################################################################################
# This example prints information about the grids of all cases in the current project
######################################################################################

import rips

resinsight = rips.Instance.find()

cases = resinsight.project.cases()
print("Number of cases found: ", len(cases))
for case in cases:
    print(case.name)
    grids = case.grids()
    print("Number of grids: ", len(grids))
    for grid in grids:
        print("Grid dimensions: ", grid.dimensions())

Headless Plot Export

import sys
import os

import rips

use_platform_offscreen = True
if use_platform_offscreen:
    # To use offscreen, the path to fonts must be specified in the environment variable QT_QPA_FONTDIR="C:/windows/fonts"
    resinsight = rips.Instance.launch(
        command_line_parameters=["-platform", "offscreen", "--size", 1200, 1000]
    )

    qpa_fontdir = os.environ["QT_QPA_FONTDIR"]
    print("Environment var QT_QPA_FONTDIR : " + qpa_fontdir)
else:
    resinsight = rips.Instance.find()

summary_filename = "NORNE.SMSPEC"

project = resinsight.project
summary_case = project.import_summary_case(summary_filename)

summary_plot_collection = project.descendants(rips.SummaryPlotCollection)[0]

summary_plot_collection.new_summary_plot(summary_cases=[summary_case], address="FOPR")
summary_plot_collection.new_summary_plot(
    summary_cases=[summary_case], address="WOPR:A*;WOPR:B*"
)

plots = resinsight.project.plots()
for plot in plots:
    plot.export_snapshot()
    # plot.export_snapshot(output_format="PDF")

resinsight.exit()

Import Case Properties

#######################################################
#
# This file shows how to import properties for a
# grid case created with .ROFFASC files
#
# Same procedure can also be used for .GRDECL files
#
#######################################################


# Access to environment variables and path tools
import os

# Load ResInsight Processing Server Client Library
import rips

# Connect to ResInsight instance
resinsight = rips.Instance.find()

# This requires the TestModels to be installed with ResInsight (RESINSIGHT_BUNDLE_TESTMODELS):
resinsight_exe_path = os.environ.get("RESINSIGHT_EXECUTABLE")

# Get the TestModels path from the executable path
resinsight_install_path = os.path.dirname(resinsight_exe_path)
test_models_path = os.path.join(resinsight_install_path, "TestModels")

# Get the .roff case
roff_case_path = os.path.join(
    test_models_path, "reek/reek_box_grid_w_out_props.roffasc"
)
roff_case = resinsight.project.load_case(roff_case_path)

# PORO and EQLNUM should not be among available properties yet
for prop in roff_case.available_properties("INPUT_PROPERTY"):
    print(prop)

# Import properties with file paths
poro_property_path = os.path.join(
    test_models_path, "reek/reek_box_PORO_property.roffasc"
)
eqlnum_property_path = os.path.join(
    test_models_path, "reek/reek_box_EQLNUM_property.roffasc"
)
roff_case.import_properties(file_names=[poro_property_path, eqlnum_property_path])

# PORO and EQLNUM should now be among available properties
for prop in roff_case.available_properties("INPUT_PROPERTY"):
    print(prop)

Import Fractures On Well

# Load ResInsight Processing Server Client Library
import rips
import tempfile
from os.path import expanduser
from pathlib import Path

# Connect to ResInsight instance
resinsight = rips.Instance.find()
project = resinsight.project

# Look for input files in the home directory of the user
home_dir = expanduser("~")
stim_plan_file_path = (Path(home_dir) / "contour.xml").as_posix()
print("StimPlan contour file path:", stim_plan_file_path)

# Find a case
cases = resinsight.project.cases()
case = cases[0]

# Create stim plan template
fmt_collection = project.descendants(rips.FractureTemplateCollection)[0]
fracture_template = fmt_collection.append_fracture_template(
    file_path=stim_plan_file_path
)

well_name = "B-2 H"

# Find a well
well_path = project.well_path_by_name(well_name)
print("well path:", well_path.name)

# Place fracture at given depths
measured_depths = [3200.0, 3400.0, 3600.0]
for measured_depth in measured_depths:
    print("Placing fracture at {} depth (MD)".format(measured_depth))
    # Create stim plan  at a give measured depth
    fracture = well_path.add_fracture(
        measured_depth=measured_depth,
        stim_plan_fracture_template=fracture_template,
        align_dip=True,
        eclipse_case=case,
    )

# Update the orientation of the fracture
# Call update() to propagate changes from the Python object back to ResInsight
fracture_template.orientation = "Azimuth"
fracture_template.azimuth_angle = 60.0
fracture_template.user_defined_perforation_length = True
fracture_template.conductivity_type = "InfiniteConductivity"
fracture_template.perforation_length = 12.3
fracture_template.update()

# Scale the template
fracture_template.set_scale_factors(
    half_length=2.0, height=2.0, d_factor=1.1, conductivity=1.2
)

# Output scale factors for all fracture templates
fmt_collection = project.descendants(rips.FractureTemplate)
for fracture_template in fmt_collection:
    print(
        "Fracture: '{}' Scale factors: Height={} Half Length={} D Factor={} Conductivity={}".format(
            fracture_template.user_description,
            fracture_template.height_scale_factor,
            fracture_template.width_scale_factor,
            fracture_template.d_factor_scale_factor,
            fracture_template.conductivity_factor,
        )
    )

Import Thermal Fracture On Well

# Load ResInsight Processing Server Client Library
import rips
import tempfile
from os.path import expanduser
from pathlib import Path

# Connect to ResInsight instance
resinsight = rips.Instance.find()
project = resinsight.project

# Look for input files in the home directory of the user
home_dir = expanduser("~")
fracture_file_path = (Path(home_dir) / "fracture.csv").as_posix()
print("Thermal fracture file path:", fracture_file_path)

# Find a case
cases = resinsight.project.cases()
case = cases[0]

# Create thermal template
fmt_collection = project.descendants(rips.FractureTemplateCollection)[0]
fracture_template = fmt_collection.append_thermal_fracture_template(
    file_path=fracture_file_path
)

well_name = "F-1 H"

# Find a well
well_path = project.well_path_by_name(well_name)
print("Well path:", well_path.name)

# Create fracture and place it using data from the fracture template
fracture = well_path.add_thermal_fracture(
    fracture_template=fracture_template,
    place_using_template_data=True,
)


time_steps = fracture_template.time_steps().values
for time_step_index, time_stamp in enumerate(time_steps):
    print("Time step #{}: {}".format(time_step_index, time_stamp))
    fracture_template.active_time_step_index = time_step_index
    fracture_template.conductivity_result_name = "Conductivity"
    fracture_template.update()

Import Well Paths And Logs

# Load ResInsight Processing Server Client Library
import rips

# Connect to ResInsight instance
resInsight = rips.Instance.find()

well_paths = resInsight.project.import_well_paths(
    well_path_folder="D:/Projects/ResInsight-regression-test/ModelData/norne/wellpaths"
)
if resInsight.project.has_warnings():
    for warning in resInsight.project.warnings():
        print(warning)


for well_path in well_paths:
    print("Imported from folder: " + well_path.name)

well_paths = resInsight.project.import_well_paths(
    well_path_files=[
        "D:/Projects/ResInsight-regression-test/ModelData/Norne_WellPaths/E-3H.json",
        "D:/Projects/ResInsight-regression-test/ModelData/Norne_WellPaths/C-1H.json",
    ]
)
if resInsight.project.has_warnings():
    for warning in resInsight.project.warnings():
        print(warning)


for well_path in well_paths:
    print("Imported from individual files: " + well_path.name)


well_path_names = resInsight.project.import_well_log_files(
    well_log_folder="D:/Projects/ResInsight-regression-test/ModelData/Norne_PLT_LAS"
)
if resInsight.project.has_warnings():
    for warning in resInsight.project.warnings():
        print(warning)

for well_path_name in well_path_names:
    print("Imported well log file for: " + well_path_name)

Input Prop Test Async

########################################################################################
# This example generates a derived property in an asynchronous manner
# Meaning it does not wait for all the data for each stage to be read before proceeding
########################################################################################
import rips
import time


# Internal function for creating a result from a small chunk of poro and permx results
# The return value of the function is a generator for the results rather than the result itself.
def create_result(poro_chunks, permx_chunks):
    # Loop through all the chunks of poro and permx in order
    for poroChunk, permxChunk in zip(poro_chunks, permx_chunks):
        resultChunk = []
        # Loop through all the values inside the chunks, in order
        for poro, permx in zip(poroChunk.values, permxChunk.values):
            resultChunk.append(poro * permx)
        # Return a generator object that behaves like a Python iterator
        yield resultChunk


resinsight = rips.Instance.find()
start = time.time()
case = resinsight.project.cases()[0]

# Get a generator for the poro results. The generator will provide a chunk each time it is iterated
poro_chunks = case.active_cell_property_async("STATIC_NATIVE", "PORO", 0)
# Get a generator for the permx results. The generator will provide a chunk each time it is iterated
permx_chunks = case.active_cell_property_async("STATIC_NATIVE", "PERMX", 0)

# Send back the result with the result provided by a generator object.
# Iterating the result generator will cause the script to read from the poro and permx generators
# And return the result of each iteration
case.set_active_cell_property_async(
    create_result(poro_chunks, permx_chunks), "GENERATED", "POROPERMXAS", 0
)

end = time.time()
print("Time elapsed: ", end - start)
print("Transferred all results back")
view = case.views()[0].apply_cell_result("GENERATED", "POROPERMXAS")

Input Prop Test Sync

########################################################################################
# This example generates a derived property in an synchronous manner
# Meaning it completes reading each result before calculating the derived result
# See InputPropTestAsync for how to do this asynchronously instead.
########################################################################################
import rips
import time
import grpc

resinsight = rips.Instance.find()
start = time.time()
case = resinsight.project.cases()[0]

# Read poro result into list
poro_results = case.active_cell_property("STATIC_NATIVE", "PORO", 0)
# Read permx result into list
permx_results = case.active_cell_property("STATIC_NATIVE", "PERMX", 0)

# Generate output result
results = []
for poro, permx in zip(poro_results, permx_results):
    results.append(poro * permx)

try:
    # Send back output result
    case.set_active_cell_property(results, "GENERATED", "POROPERMXSY", 0)
except grpc.RpcError as e:
    print("Exception Received: ", e)


end = time.time()
print("Time elapsed: ", end - start)
print("Transferred all results back")

view = case.views()[0].apply_cell_result("GENERATED", "POROPERMXSY")

Instance Example

#######################################
# This example connects to ResInsight
#######################################
import rips

resinsight = rips.Instance.find()

if resinsight is None:
    print("ERROR: could not find ResInsight")
else:
    print("Successfully connected to ResInsight")

Launch Load Case Snapshot Exit

# Access to environment variables
import os

# Load ResInsight Processing Server Client Library
import rips

# Connect to ResInsight instance
resinsight = rips.Instance.launch()

# This requires the TestModels to be installed with ResInsight (RESINSIGHT_BUNDLE_TESTMODELS):
resinsight_exe_path = os.environ.get("RESINSIGHT_EXECUTABLE")

# Get the TestModels path from the executable path
resinsight_install_path = os.path.dirname(resinsight_exe_path)
test_models_path = os.path.join(resinsight_install_path, "TestModels")
path_name = os.path.join(
    test_models_path, "TEST10K_FLT_LGR_NNC/TEST10K_FLT_LGR_NNC.EGRID"
)

# Load an example case. Needs to be replaced with a valid path!
case = resinsight.project.load_case(path_name)

# Get a view
view1 = case.views()[0]

# Set the time step for view1 only
view1.set_time_step(time_step=2)

# Set cell result to SOIL
view1.apply_cell_result(result_type="DYNAMIC_NATIVE", result_variable="SOIL")

# Set export folder for snapshots and properties
resinsight.set_export_folder(export_type="SNAPSHOTS", path="e:/temp")
resinsight.set_export_folder(export_type="PROPERTIES", path="e:/temp")

# Export all snapshots
resinsight.project.export_snapshots()

# Export properties in the view
view1.export_property()

resinsight.exit()

Launch With Commandline Options

# Load ResInsight Processing Server Client Library
import rips

# Launch ResInsight with last project file and a Window size of 600x1000 pixels
resinsight = rips.Instance.launch(
    command_line_parameters=["--last", "--size", 600, 1000]
)
# Get a list of all cases
cases = resinsight.project.cases()

print("Got " + str(len(cases)) + " cases: ")
for case in cases:
    print("Case name: " + case.name)
    print("Case grid path: " + case.file_path)

Load Case

# Access to environment variables and path tools
import os

# Load ResInsight Processing Server Client Library
import rips

# Connect to ResInsight instance
resinsight = rips.Instance.find()

# This requires the TestModels to be installed with ResInsight (RESINSIGHT_BUNDLE_TESTMODELS):
resinsight_exe_path = os.environ.get("RESINSIGHT_EXECUTABLE")

# Get the TestModels path from the executable path
resinsight_install_path = os.path.dirname(resinsight_exe_path)
test_models_path = os.path.join(resinsight_install_path, "TestModels")
path_name = os.path.join(
    test_models_path, "TEST10K_FLT_LGR_NNC/TEST10K_FLT_LGR_NNC.EGRID"
)
case = resinsight.project.load_case(path_name)
case.create_view()

# Print out lots of information from the case object
print("Case id: " + str(case.id))
print("Case name: " + case.name)
print("Case type: " + case.__class__.__name__)
print("Case file name: " + case.file_path)
print("Case reservoir bounding box:", case.reservoir_boundingbox())

timesteps = case.time_steps()
for t in timesteps:
    print("Year: " + str(t.year))
    print("Month: " + str(t.month))

Modeled Well Path

# Load ResInsight Processing Server Client Library
import rips

# Connect to ResInsight instance
resinsight = rips.Instance.find()

# Create a modeled well path and add well path targets
# The coordinates are based on the Norne case

well_path_coll = resinsight.project.descendants(rips.WellPathCollection)[0]
well_path = well_path_coll.add_new_object(rips.ModeledWellPath)
well_path.name = "Test Well-1"
well_path.update()

geometry = well_path.well_path_geometry()

reference_point = geometry.reference_point
reference_point[0] = 457196
reference_point[1] = 7322270
reference_point[2] = 2742
geometry.update()  # Commit updates back to ResInsight

# Create the first well target at the reference point
coord = [0, 0, 0]
geometry.append_well_target(coord)

# Append new well targets relative the the reference point
coord = [454.28, 250, -10]
target = geometry.append_well_target(coord)

coord = [1054.28, 250, -50]
target = geometry.append_well_target(coord)

well_path.append_perforation_interval(3300, 3350, 0.2, 0.76)


# Update skin factor of the perforation
perforation_coll = well_path.completions().perforations()
perforation = perforation_coll.perforations()[0]
new_skin_factor = 0.9
print(
    "Changing perforation skin factor from {} to {}.".format(
        perforation.skin_factor, new_skin_factor
    )
)
perforation.skin_factor = new_skin_factor
perforation.update()

# Optionally update the completion settings
completions_settings = well_path.completion_settings()
completions_settings.msw_roughness = 12.34
completions_settings.msw_liner_diameter = 0.2222
completions_settings.well_name_for_export = "file name"
completions_settings.group_name_for_export = "msj"
completions_settings.well_type_for_export = "GAS"
completions_settings.update()  # Commit updates back to ResInsight

# export completions
cases = resinsight.project.cases()

for case in cases:
    print("Case name: ", case.name)
    print("Case id: ", case.id)

    case.export_well_path_completions(
        time_step=0,
        well_path_names=["Test Well-1 Y1"],
        file_split="UNIFIED_FILE",
        include_perforations=True,
        # Replace the following with a valid path
        custom_file_name="f:/scratch/2023-11-02/myfile.myext",
    )

Modeled Well Path Lateral

# Load ResInsight Processing Server Client Library
import rips
import time

# Connect to ResInsight instance
resinsight = rips.Instance.find()

# Create a modeled well path and add well path targets
# The coordinates are based on the Norne case
# Add a lateral to the main well path

well_path_coll = resinsight.project.descendants(rips.WellPathCollection)[0]
well_path = well_path_coll.add_new_object(rips.ModeledWellPath)
well_path.name = "Test Well-1"
well_path.update()

geometry = well_path.well_path_geometry()

reference_point = geometry.reference_point
reference_point[0] = 457196
reference_point[1] = 7322270
reference_point[2] = 2742
geometry.update()  # Commit updates back to ResInsight

# Create the first well target at the reference point
coord = [0, 0, 0]
geometry.append_well_target(coord)

# Append new well targets relative the the reference point
coord = [454.28, 250, -10]
target = geometry.append_well_target(coord)

coord = [1054.28, 250, -50]
target = geometry.append_well_target(coord)

# Create a lateral at specified location on parent well
measured_depth = 3600
lateral = well_path.append_lateral(measured_depth)
geometry = lateral.well_path_geometry()

coord = [770, 280, 50]
target = geometry.append_well_target(coord)

coord = [1054.28, -100, 50]
target = geometry.append_well_target(coord)

coord = [2054.28, -100, 45]
target = geometry.append_well_target(coord)


# Wait 2 second
print("Wait 2 seconds ...")
time.sleep(2)
print("Move reference point of parent well")

geometry = well_path.well_path_geometry()
reference_point = geometry.reference_point
reference_point[2] += 50
geometry.update()  # Commit updates back to ResInsight

New Summary Plot

# Load ResInsight Processing Server Client Library
import rips

# Connect to ResInsight instance
resinsight = rips.Instance.find()
# Example code
project = resinsight.project

summary_cases = project.descendants(rips.SummaryCase)
summary_plot_collection = project.descendants(rips.SummaryPlotCollection)[0]
if len(summary_cases) > 0:
    summary_plot = summary_plot_collection.new_summary_plot(
        summary_cases=summary_cases, address="FOP*"
    )

Open Project

# Access to environment variables and path tools
import os

# Load ResInsight Processing Server Client Library
import rips

# Connect to ResInsight instance
resinsight = rips.Instance.find()

# This requires the TestModels to be installed with ResInsight (RESINSIGHT_BUNDLE_TESTMODELS):
resinsight_exe_path = os.environ.get("RESINSIGHT_EXECUTABLE")

# Get the TestModels path from the executable path
resinsight_install_path = os.path.dirname(resinsight_exe_path)
test_models_path = os.path.join(resinsight_install_path, "TestModels")
path_name = os.path.join(test_models_path, "TEST10K_FLT_LGR_NNC/10KWithWellLog.rsp")

# Open a project
resinsight.project.open(path_name)

Replace Case

# Load ResInsight Processing Server Client Library
import rips

# Connect to ResInsight instance
resinsight = rips.Instance.find()
# Example code
print("ResInsight version: " + resinsight.version_string())

case = resinsight.project.case(case_id=0)
case.replace(
    new_grid_file="C:/Users/lindkvis/Projects/ResInsight/TestModels/Case_with_10_timesteps/Real0/BRUGGE_0000.EGRID"
)

Save Project

# Access to environment variables and path tools
import os

# Load ResInsight Processing Server Client Library
import rips

# Connect to ResInsight instance
resinsight = rips.Instance.find()

# This requires the TestModels to be installed with ResInsight (RESINSIGHT_BUNDLE_TESTMODELS):
resinsight_exe_path = os.environ.get("RESINSIGHT_EXECUTABLE")

# Get the TestModels path from the executable path
resinsight_install_path = os.path.dirname(resinsight_exe_path)
test_models_path = os.path.join(resinsight_install_path, "TestModels")
path_name = os.path.join(
    test_models_path, "TEST10K_FLT_LGR_NNC/TEST10K_FLT_LGR_NNC.EGRID"
)
case = resinsight.project.load_case(path_name)

# Save the project to file
home_dir = os.path.expanduser("~")
project_path = home_dir + "/new-project.rsp"
print("Saving project to: ", project_path)
resinsight.project.save(project_path)

Selected Cases

############################################################################
# This example returns the currently selected cases in ResInsight
# Because running this script in the GUI takes away the selection
# This script does not run successfully from within the ResInsight GUI
# And will need to be run from the command line separately from ResInsight
############################################################################

import rips

resinsight = rips.Instance.find()
if resinsight is not None:
    cases = resinsight.project.selected_cases()

    print("Got " + str(len(cases)) + " cases: ")
    for case in cases:
        print(case.name)
        for property in case.available_properties("DYNAMIC_NATIVE"):
            print(property)

Selected Cells

############################################################################
# This example prints center and corners for the currently selected cells
# in ResInsight
############################################################################

import rips

resinsight = rips.Instance.find()
if resinsight is not None:
    cases = resinsight.project.cases()

    print("Got " + str(len(cases)) + " cases: ")
    for case in cases:
        print(case.name)
        cells = case.selected_cells()
        print("Found " + str(len(cells)) + " selected cells")

        time_step_info = case.time_steps()

        for idx, cell in enumerate(cells):
            print(
                "Selected cell: [{}, {}, {}] grid: {}".format(
                    cell.ijk.i + 1, cell.ijk.j + 1, cell.ijk.k + 1, cell.grid_index
                )
            )

            # Get the grid and dimensions
            grid = case.grids()[cell.grid_index]
            dimensions = grid.dimensions()

            # Map ijk to cell index
            cell_index = (
                dimensions.i * dimensions.j * cell.ijk.k
                + dimensions.i * cell.ijk.j
                + cell.ijk.i
            )

            # Print the cell center
            cell_centers = grid.cell_centers()
            cell_center = cell_centers[cell_index]
            print(
                "Cell center: [{}, {}, {}]".format(
                    cell_center.x, cell_center.y, cell_center.z
                )
            )

            # Print the cell corners
            cell_corners = grid.cell_corners()[cell_index]
            print("Cell corners:")
            print("c0:\n" + str(cell_corners.c0))
            print("c1:\n" + str(cell_corners.c1))
            print("c2:\n" + str(cell_corners.c2))
            print("c3:\n" + str(cell_corners.c3))
            print("c4:\n" + str(cell_corners.c4))
            print("c5:\n" + str(cell_corners.c5))
            print("c6:\n" + str(cell_corners.c6))
            print("c7:\n" + str(cell_corners.c7))

            for tidx, timestep in enumerate(time_step_info):
                # Read the full SOIL result for time step
                soil_results = case.selected_cell_property(
                    "DYNAMIC_NATIVE", "SOIL", tidx
                )
                print(
                    "SOIL: {} ({}.{}.{})".format(
                        soil_results[idx], timestep.year, timestep.month, timestep.day
                    )
                )

Set Cell Result

######################################################################
# This script applies a cell result to the first view in the project
######################################################################
import rips

resinsight = rips.Instance.find()

view = resinsight.project.views()[0]
view.apply_cell_result(result_type="STATIC_NATIVE", result_variable="DX")

Set Flow Diagnostics Result

######################################################################
# This script applies a flow diagnostics cell result to the first view in the project
######################################################################

# Load ResInsight Processing Server Client Library
import rips

# Connect to ResInsight instance
resinsight = rips.Instance.find()

view = resinsight.project.view(view_id=1)
# view.apply_flow_diagnostics_cell_result(result_variable='Fraction',
#                                    selection_mode='FLOW_TR_INJ_AND_PROD')

# Example of setting individual wells. Commented out because well names are case specific.
view.apply_flow_diagnostics_cell_result(
    result_variable="Fraction",
    selection_mode="FLOW_TR_BY_SELECTION",
    injectors=["C-1H", "C-2H", "F-2H"],
    producers=["B-1AH", "B-3H", "D-1H"],
)

Set Grid Properties

######################################################################
# This script sets values for all grid cells in the first case in the project
# The script is intended to be used for TEST10K_FLT_LGR_NNC.EGRID
# This grid case contains one LGR
######################################################################
import rips

resinsight = rips.Instance.find()

case = resinsight.project.case(case_id=0)
grid = case.grid()
grid_cell_count = grid.cell_count()
print("total cell count : " + str(grid_cell_count))

values = []
for i in range(0, grid_cell_count):
    values.append(i % 2 * 0.75)

# Assign value to IJK grid cell at (31, 53, 21)
grid = case.grid()
property_data_index = grid.property_data_index_from_ijk(31, 53, 21)
values[property_data_index] = 1.5

print("Applying values to main grid")
case.set_grid_property(values, "STATIC_NATIVE", "MY_DATA", 0)

values_from_ri = case.grid_property("STATIC_NATIVE", "MY_DATA", 0)
assert values[property_data_index] == values_from_ri[property_data_index]

# Get LGR grid as grid index 1
grid = case.grid(1)
grid_cell_count = grid.cell_count()
print("lgr cell count : " + str(grid_cell_count))

values = []
for i in range(0, grid_cell_count):
    values.append(i % 3 * 0.75)

print("Applying values to LGR grid")
case.set_grid_property(values, "STATIC_NATIVE", "MY_DATA", 0, 1)
values_from_ri = case.grid_property("STATIC_NATIVE", "MY_DATA", 0, 1)

Soil Average Async

###########################################################################################
# This example will asynchronously calculate the average value for SOIL for all time steps
###########################################################################################

import rips
import itertools
import time

resinsight = rips.Instance.find()

start = time.time()

# Get the case with case id 0
case = resinsight.project.case(case_id=0)

# Get a list of all time steps
timeSteps = case.time_steps()

averages = []
for i in range(0, len(timeSteps)):
    # Get the results from time step i asynchronously
    # It actually returns a generator object almost immediately
    result_chunks = case.active_cell_property_async("DYNAMIC_NATIVE", "SOIL", i)
    mysum = 0.0
    count = 0
    # Loop through and append the average. each time we loop resultChunks
    # We will trigger a read of the input data, meaning the script will start
    # Calculating averages before the whole resultValue for this time step has been received
    for chunk in result_chunks:
        mysum += sum(chunk.values)
        count += len(chunk.values)

    averages.append(mysum / count)

end = time.time()
print("Time elapsed: ", end - start)
print(averages)

Soil Average Sync

###########################################################################################
# This example will synchronously calculate the average value for SOIL for all time steps
###########################################################################################
import rips
import itertools
import time

resinsight = rips.Instance.find()

start = time.time()

# Get the case with case id 0
case = resinsight.project.case(case_id=0)

# Get a list of all time steps
time_steps = case.time_steps()

averages = []
for i in range(0, len(time_steps)):
    # Get a list of all the results for time step i
    results = case.active_cell_property("DYNAMIC_NATIVE", "SOIL", i)
    mysum = sum(results)
    averages.append(mysum / len(results))

end = time.time()
print("Time elapsed: ", end - start)
print(averages)

Soil Porv Async

##############################################################################
# This example will create a derived result for each time step asynchronously
##############################################################################

import rips
import time


# Internal function for creating a result from a small chunk of soil and porv results
# The return value of the function is a generator for the results rather than the result itself.
def create_result(soil_chunks, porv_chunks):
    for soil_chunk, porv_chunk in zip(soil_chunks, porv_chunks):
        resultChunk = []
        number = 0
        for soil_value, porv_value in zip(soil_chunk.values, porv_chunk.values):
            resultChunk.append(soil_value * porv_value)
        # Return a Python generator
        yield resultChunk


resinsight = rips.Instance.find()
start = time.time()
case = resinsight.project.cases()[0]
timeStepInfo = case.time_steps()

# Get a generator for the porv results. The generator will provide a chunk each time it is iterated
porv_chunks = case.active_cell_property_async("STATIC_NATIVE", "PORV", 0)

# Read the static result into an array, so we don't have to transfer it for each iteration
# Note we use the async method even if we synchronise here, because we need the values chunked
# ... to match the soil chunks
porv_array = []
for porv_chunk in porv_chunks:
    porv_array.append(porv_chunk)

for i in range(0, len(timeStepInfo)):
    # Get a generator object for the SOIL property for time step i
    soil_chunks = case.active_cell_property_async("DYNAMIC_NATIVE", "SOIL", i)
    # Create the generator object for the SOIL * PORV derived result
    result_generator = create_result(soil_chunks, iter(porv_array))
    # Send back the result asynchronously with a generator object
    case.set_active_cell_property_async(
        result_generator, "GENERATED", "SOILPORVAsync", i
    )

end = time.time()
print("Time elapsed: ", end - start)

print("Transferred all results back")

view = case.views()[0].apply_cell_result("GENERATED", "SOILPORVAsync")

Soil Porv Sync

##############################################################################
# This example will create a derived result for each time step synchronously
##############################################################################

import rips
import time

resinsight = rips.Instance.find()
start = time.time()
case = resinsight.project.cases()[0]

# Read the full porv result
porv_results = case.active_cell_property("STATIC_NATIVE", "PORV", 0)
time_step_info = case.time_steps()

for i in range(0, len(time_step_info)):
    # Read the full SOIl result for time step i
    soil_results = case.active_cell_property("DYNAMIC_NATIVE", "SOIL", i)

    # Generate the result by looping through both lists in order
    results = []
    for soil, porv in zip(soil_results, porv_results):
        results.append(soil * porv)

    # Send back result
    case.set_active_cell_property(results, "GENERATED", "SOILPORVSync", i)

end = time.time()
print("Time elapsed: ", end - start)

print("Transferred all results back")

view = case.views()[0].apply_cell_result("GENERATED", "SOILPORVSync")

Summary Cases

# Load ResInsight Processing Server Client Library
import rips

# Connect to ResInsight instance
resinsight = rips.Instance.find()
# Example code

# Specific summary case with case_id = 1
summary_case = resinsight.project.summary_case(case_id=1)
summary_case.print_object_info()

# All summary cases
summary_cases = resinsight.project.summary_cases()
for summary_case in summary_cases:
    print("Summary case found: ", summary_case.short_name)

Summary Vectors

import rips
import time

resinsight = rips.Instance.find()

project = resinsight.project

# Use the following commented lines to import a file from disk
# filename = "path/to/file/1_R001_REEK-0.SMSPEC"
# summary_case = project.import_summary_case(filename)

# Assumes at least one summery case loaded with case_id 1
summary_case = project.summary_case(1)
if summary_case is None:
    print("No summary case found")
    exit()

vector_name = "FOPT"
summary_data = summary_case.summary_vector_values(vector_name)

print("Data for summary vector " + vector_name)
print(summary_data.values)

time_steps = summary_case.available_time_steps()
print(time_steps.values)

summary_data_sampled = summary_case.resample_values("FOPT", "QUARTER")
print("\nResampled data")

for t, value in zip(summary_data_sampled.time_steps, summary_data_sampled.values):
    print(time.strftime("%a, %d %b %Y ", time.gmtime(t)) + " | " + str(value))

test_values = summary_data.values
offset = test_values[len(test_values) - 1] / 10

for index, item in enumerate(test_values):
    test_values[index] = test_values[index] + offset

summary_case.set_summary_values("FOPT_M1", "myUnit", test_values)

for index, item in enumerate(test_values):
    test_values[index] = test_values[index] + offset
summary_case.set_summary_values("FOPT_M2", "myUnit", test_values)

for index, item in enumerate(test_values):
    test_values[index] = test_values[index] + offset
summary_case.set_summary_values("FOPT_M3", "myUnit", test_values)

for index, item in enumerate(test_values):
    test_values[index] = test_values[index] + offset
summary_case.set_summary_values("FOPT_M4", "myUnit", test_values)

Surface Import

# Load ResInsight Processing Server Client Library
import rips

# Connect to ResInsight instance
resinsight = rips.Instance.find()
print("ResInsight version: " + resinsight.version_string())

# Example code

# get the project
project = resinsight.project

# get the topmost surface folder from the project
surfacefolder = project.surface_folder()

# list of surface files to load
filenames = ["surface1.ts", "surface2.ts", "surface3.ts"]

# Load the files into the top level
for surffile in filenames:
    surface = surfacefolder.import_surface(surffile)
    if surface is None:
        print("Could not import the surface " + surffile)

# add a subfolder
subfolder = surfacefolder.add_folder("ExampleFolder")

# load the same surface multiple times using increasing depth offsets
# store them in the new subfolder we just created
for offset in range(0, 200, 20):
    surface = subfolder.import_surface("mysurface.ts")
    if surface:
        surface.depth_offset = offset
        surface.update()
    else:
        print("Could not import surface.")

# get an existing subfolder
existingfolder = project.surface_folder("ExistingFolder")
if existingfolder is None:
    print("Could not find the specified folder.")

View Example

#############################################################
# This example will alter the views of all cases
# By setting the background color and toggle the grid box
# Also clones the first view
#############################################################
import rips

# Connect to ResInsight instance
resinsight = rips.Instance.find()

# Check if connection worked
if resinsight is not None:
    # Get a list of all cases
    cases = resinsight.project.cases()
    for case in cases:
        # Get a list of all views
        views = case.views()
        for view in views:
            # Set some parameters for the view
            view.show_grid_box = not view.show_grid_box
            view.background_color = "#3388AA"
            # Update the view in ResInsight
            view.update()
        # Clone the first view
        new_view = views[0].clone()
        new_view.background_color = "#FFAA33"
        new_view.update()
        view.show_grid_box = False
        view.set_visible(False)
        view.update()