Files
ResInsight/scripting/pythonexamples/index.html
Magne Sjaastad 34f799d9cd Add redirect from /docs/home to /getting-started
When using ResInsight and trying to open User documentation from Help menu does not work. Add redirect to getting-started
2019-09-13 11:23:37 +02:00

3626 lines
71 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!DOCTYPE html>
<html lang="en" class="js csstransforms3d">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="Hugo 0.56.3" />
<meta name="description" content="">
<link rel="icon" href="/images/favicon.png" type="image/png">
<title>Python Examples :: ResInsight</title>
<link href="/css/nucleus.css?1568366249" rel="stylesheet">
<link href="/css/fontawesome-all.min.css?1568366249" rel="stylesheet">
<link href="/css/hybrid.css?1568366249" rel="stylesheet">
<link href="/css/featherlight.min.css?1568366249" rel="stylesheet">
<link href="/css/perfect-scrollbar.min.css?1568366249" rel="stylesheet">
<link href="/css/auto-complete.css?1568366249" rel="stylesheet">
<link href="/css/atom-one-dark-reasonable.css?1568366249" rel="stylesheet">
<link href="/css/theme.css?1568366249" rel="stylesheet">
<link href="/css/hugo-theme.css?1568366249" rel="stylesheet">
<script src="/js/jquery-3.3.1.min.js?1568366249"></script>
<style>
:root #header + #content > #left > #rlblock_left{
display:none !important;
}
</style>
</head>
<body class="" data-url="/scripting/pythonexamples/">
<nav id="sidebar" class="">
<div id="header-wrapper">
<div id="header">
<a id="logo" href="https://resinsight.org/">
<img src="https://resinsight.org//images/ResInsightCroppedIconPicture.png">
</a>
</div>
<div class="searchbox">
<label for="searchbox"><i class="fas fa-search"></i></label>
<form action="/search/" method="GET" id="search-form">
<input type="search" name="q" id="searchbox" placeholder="Search">
</form>
<span data-search-clear=""><i class="fas fa-times"></i></span>
</div>
</div>
<div class="highlightable">
<ul class="topics">
<li data-nav-id="/getting-started/" title="Getting Started" class="dd-item
">
<a href="/getting-started/">
Getting Started
</a>
<ul>
<li data-nav-id="/getting-started/overview/" title="Overview" class="dd-item ">
<a href="/getting-started/overview/">
Overview
</a>
</li>
<li data-nav-id="/getting-started/download-and-install/" title="Download and Install" class="dd-item
">
<a href="/getting-started/download-and-install/">
Download and Install
</a>
<ul>
<li data-nav-id="/getting-started/download-and-install/linux-installation/" title="Linux Installation" class="dd-item ">
<a href="/getting-started/download-and-install/linux-installation/">
Linux Installation
</a>
</li>
<li data-nav-id="/getting-started/download-and-install/windows-installation/" title="Windows Installation" class="dd-item ">
<a href="/getting-started/download-and-install/windows-installation/">
Windows Installation
</a>
</li>
<li data-nav-id="/getting-started/download-and-install/buildinstructions/" title="Build Instructions" class="dd-item ">
<a href="/getting-started/download-and-install/buildinstructions/">
Build Instructions
</a>
</li>
</ul>
</li>
<li data-nav-id="/getting-started/modelnavigation/" title="Model Navigation" class="dd-item ">
<a href="/getting-started/modelnavigation/">
Model Navigation
</a>
</li>
</ul>
</li>
<li data-nav-id="/3d-main-window/" title="3D Main Window" class="dd-item
">
<a href="/3d-main-window/">
3D Main Window
</a>
<ul>
<li data-nav-id="/3d-main-window/3dviews/" title="3D Views" class="dd-item ">
<a href="/3d-main-window/3dviews/">
3D Views
</a>
</li>
<li data-nav-id="/3d-main-window/cellresults/" title="Cell Results" class="dd-item ">
<a href="/3d-main-window/cellresults/">
Cell Results
</a>
</li>
<li data-nav-id="/3d-main-window/resultcolorlegend/" title="Result Color Legend" class="dd-item ">
<a href="/3d-main-window/resultcolorlegend/">
Result Color Legend
</a>
</li>
<li data-nav-id="/3d-main-window/contourmaps/" title="Contour Maps" class="dd-item ">
<a href="/3d-main-window/contourmaps/">
Contour Maps
</a>
</li>
<li data-nav-id="/3d-main-window/tensors/" title="Tensor Results" class="dd-item ">
<a href="/3d-main-window/tensors/">
Tensor Results
</a>
</li>
<li data-nav-id="/3d-main-window/resultinspection/" title="Result Inspection" class="dd-item ">
<a href="/3d-main-window/resultinspection/">
Result Inspection
</a>
</li>
<li data-nav-id="/3d-main-window/filters/" title="Cell Filters" class="dd-item ">
<a href="/3d-main-window/filters/">
Cell Filters
</a>
</li>
<li data-nav-id="/3d-main-window/intersections/" title="Intersections" class="dd-item ">
<a href="/3d-main-window/intersections/">
Intersections
</a>
</li>
<li data-nav-id="/3d-main-window/faults/" title="Faults" class="dd-item ">
<a href="/3d-main-window/faults/">
Faults
</a>
</li>
<li data-nav-id="/3d-main-window/formations/" title=" Zonations/Formations" class="dd-item ">
<a href="/3d-main-window/formations/">
Zonations/Formations
</a>
</li>
<li data-nav-id="/3d-main-window/gridstatisticsdialog/" title="Grid Statistics Dialog" class="dd-item ">
<a href="/3d-main-window/gridstatisticsdialog/">
Grid Statistics Dialog
</a>
</li>
<li data-nav-id="/3d-main-window/casegroupsandstatistics/" title="Grid Case Groups and Statistics" class="dd-item ">
<a href="/3d-main-window/casegroupsandstatistics/">
Grid Case Groups and Statistics
</a>
</li>
<li data-nav-id="/3d-main-window/linkedviews/" title="Linked Views" class="dd-item ">
<a href="/3d-main-window/linkedviews/">
Linked Views
</a>
</li>
<li data-nav-id="/3d-main-window/measurement/" title="Measurement" class="dd-item ">
<a href="/3d-main-window/measurement/">
Measurement
</a>
</li>
<li data-nav-id="/3d-main-window/annotations/" title="Annotations" class="dd-item ">
<a href="/3d-main-window/annotations/">
Annotations
</a>
</li>
</ul>
</li>
<li data-nav-id="/plot-window/" title="Plot Main Window" class="dd-item
">
<a href="/plot-window/">
Plot Main Window
</a>
<ul>
<li data-nav-id="/plot-window/summaryplots/" title="Summary Plots" class="dd-item ">
<a href="/plot-window/summaryplots/">
Summary Plots
</a>
</li>
<li data-nav-id="/plot-window/summarysourcestepping/" title="Summary Plot Source Stepping" class="dd-item ">
<a href="/plot-window/summarysourcestepping/">
Summary Plot Source Stepping
</a>
</li>
<li data-nav-id="/plot-window/summaryploteditor/" title="Summary Plot Editor" class="dd-item ">
<a href="/plot-window/summaryploteditor/">
Summary Plot Editor
</a>
</li>
<li data-nav-id="/plot-window/summarycrossplots/" title="Summary Cross Plot" class="dd-item ">
<a href="/plot-window/summarycrossplots/">
Summary Cross Plot
</a>
</li>
<li data-nav-id="/plot-window/ensembleplotting/" title="Ensemble Plotting" class="dd-item ">
<a href="/plot-window/ensembleplotting/">
Ensemble Plotting
</a>
</li>
<li data-nav-id="/plot-window/curvecalculator/" title="Curve Calculator" class="dd-item ">
<a href="/plot-window/curvecalculator/">
Curve Calculator
</a>
</li>
<li data-nav-id="/plot-window/welllogsandplots/" title="Well Log Plots" class="dd-item ">
<a href="/plot-window/welllogsandplots/">
Well Log Plots
</a>
</li>
<li data-nav-id="/plot-window/wellborestabilityplots/" title="Well Bore Stability Plots" class="dd-item ">
<a href="/plot-window/wellborestabilityplots/">
Well Bore Stability Plots
</a>
</li>
<li data-nav-id="/plot-window/rftplot/" title="RFT Plot" class="dd-item ">
<a href="/plot-window/rftplot/">
RFT Plot
</a>
</li>
<li data-nav-id="/plot-window/pltplot/" title="PLT Plot" class="dd-item ">
<a href="/plot-window/pltplot/">
PLT Plot
</a>
</li>
<li data-nav-id="/plot-window/flowdiagnosticsplots/" title="Flow Diagnostics Plots" class="dd-item ">
<a href="/plot-window/flowdiagnosticsplots/">
Flow Diagnostics Plots
</a>
</li>
<li data-nav-id="/plot-window/gridcrossplots/" title="Grid Cross Plots" class="dd-item ">
<a href="/plot-window/gridcrossplots/">
Grid Cross Plots
</a>
</li>
<li data-nav-id="/plot-window/saturationpressureplots/" title="Saturation Pressure Plots" class="dd-item ">
<a href="/plot-window/saturationpressureplots/">
Saturation Pressure Plots
</a>
</li>
</ul>
</li>
<li data-nav-id="/wells-and-completions/" title="Wells and Completions" class="dd-item
">
<a href="/wells-and-completions/">
Wells and Completions
</a>
<ul>
<li data-nav-id="/wells-and-completions/simulationwells/" title="Simulation Wells" class="dd-item ">
<a href="/wells-and-completions/simulationwells/">
Simulation Wells
</a>
</li>
<li data-nav-id="/wells-and-completions/wellpaths/" title="Well Paths" class="dd-item ">
<a href="/wells-and-completions/wellpaths/">
Well Paths
</a>
</li>
<li data-nav-id="/wells-and-completions/createnewwellpaths/" title="Create Well Paths" class="dd-item ">
<a href="/wells-and-completions/createnewwellpaths/">
Create Well Paths
</a>
</li>
<li data-nav-id="/wells-and-completions/3dwelllogcurves/" title="3D Well Log Plots" class="dd-item ">
<a href="/wells-and-completions/3dwelllogcurves/">
3D Well Log Plots
</a>
</li>
<li data-nav-id="/wells-and-completions/completions/" title="Completions" class="dd-item ">
<a href="/wells-and-completions/completions/">
Completions
</a>
</li>
<li data-nav-id="/wells-and-completions/completionslgr/" title="Completions LGR" class="dd-item ">
<a href="/wells-and-completions/completionslgr/">
Completions LGR
</a>
</li>
</ul>
</li>
<li data-nav-id="/import/" title="Import" class="dd-item
">
<a href="/import/">
Import
</a>
<ul>
<li data-nav-id="/import/eclipsecases/" title="Eclipse Cases" class="dd-item ">
<a href="/import/eclipsecases/">
Eclipse Cases
</a>
</li>
<li data-nav-id="/import/geomechanicaldata/" title="Geomechanical Data" class="dd-item ">
<a href="/import/geomechanicaldata/">
Geomechanical Data
</a>
</li>
<li data-nav-id="/import/soursimrlresults/" title="SourSimRL Results" class="dd-item ">
<a href="/import/soursimrlresults/">
SourSimRL Results
</a>
</li>
<li data-nav-id="/import/elementpropertytable/" title="Element Property Table" class="dd-item ">
<a href="/import/elementpropertytable/">
Element Property Table
</a>
</li>
<li data-nav-id="/import/observeddata/" title="Observed Time History Data" class="dd-item ">
<a href="/import/observeddata/">
Observed Time History Data
</a>
</li>
<li data-nav-id="/import/pasteexceltimedata/" title="Paste Excel Time History Data" class="dd-item ">
<a href="/import/pasteexceltimedata/">
Paste Excel Time History Data
</a>
</li>
</ul>
</li>
<li data-nav-id="/export/" title="Export" class="dd-item
">
<a href="/export/">
Export
</a>
<ul>
<li data-nav-id="/export/snapshots/" title="Snapshots" class="dd-item ">
<a href="/export/snapshots/">
Snapshots
</a>
</li>
<li data-nav-id="/export/eclipseproperties/" title="Eclipse Properties" class="dd-item ">
<a href="/export/eclipseproperties/">
Eclipse Properties
</a>
</li>
<li data-nav-id="/export/fluxnummultnum/" title="FLUXNUM/MULTNUM" class="dd-item ">
<a href="/export/fluxnummultnum/">
FLUXNUM/MULTNUM
</a>
</li>
<li data-nav-id="/export/completionexport/" title="Completions" class="dd-item ">
<a href="/export/completionexport/">
Completions
</a>
</li>
<li data-nav-id="/export/exportwellpaths/" title="Well Paths" class="dd-item ">
<a href="/export/exportwellpaths/">
Well Paths
</a>
</li>
<li data-nav-id="/export/sectormodel/" title="Sector Model" class="dd-item ">
<a href="/export/sectormodel/">
Sector Model
</a>
</li>
</ul>
</li>
<li data-nav-id="/scripting/" title="Scripting" class="dd-item
parent
">
<a href="/scripting/">
Scripting
</a>
<ul>
<li data-nav-id="/scripting/commandlineinterface/" title="Command Line Interface" class="dd-item ">
<a href="/scripting/commandlineinterface/">
Command Line Interface
</a>
</li>
<li data-nav-id="/scripting/commandfile/" title="Command File" class="dd-item ">
<a href="/scripting/commandfile/">
Command File
</a>
</li>
<li data-nav-id="/scripting/pythonexamples/" title="Python Examples" class="dd-item active">
<a href="/scripting/pythonexamples/">
Python Examples
</a>
</li>
<li data-nav-id="/scripting/pythonrips/" title="Python API - rips" class="dd-item ">
<a href="/scripting/pythonrips/">
Python API - rips
</a>
</li>
<li data-nav-id="/scripting/pythonconfiguration/" title="Python Configuration" class="dd-item ">
<a href="/scripting/pythonconfiguration/">
Python Configuration
</a>
</li>
<li data-nav-id="/scripting/octaveinterface/" title="Octave Interface" class="dd-item ">
<a href="/scripting/octaveinterface/">
Octave Interface
</a>
</li>
<li data-nav-id="/scripting/octaveinterfacereference/" title="Octave Interface Reference" class="dd-item ">
<a href="/scripting/octaveinterfacereference/">
Octave Interface Reference
</a>
</li>
</ul>
</li>
<li data-nav-id="/misc/" title="Miscellaneous" class="dd-item
">
<a href="/misc/">
Miscellaneous
</a>
<ul>
<li data-nav-id="/misc/preferences/" title="Preferences" class="dd-item ">
<a href="/misc/preferences/">
Preferences
</a>
</li>
<li data-nav-id="/misc/memorymanagement/" title="Memory Management" class="dd-item ">
<a href="/misc/memorymanagement/">
Memory Management
</a>
</li>
<li data-nav-id="/misc/keyboardshortcuts/" title="Keyboard Shortcuts" class="dd-item ">
<a href="/misc/keyboardshortcuts/">
Keyboard Shortcuts
</a>
</li>
<li data-nav-id="/misc/regressiontestsystem/" title="Regression Test System" class="dd-item ">
<a href="/misc/regressiontestsystem/">
Regression Test System
</a>
</li>
</ul>
</li>
</ul>
<section id="shortcuts">
<h3></h3>
<ul>
<li>
<a class="padding" href="https://resinsight.org/about"><i class='fas fa-info-circle'></i> About</a>
</li>
<li>
<a class="padding" href="https://resinsight.org/support"><i class='far fa-question-circle'></i> Support</a>
</li>
<li>
<a class="padding" href="https://resinsight.org/getting-started/download-and-install"><i class='fas fa-download'></i> Download and Install</a>
</li>
</ul>
</section>
<section id="footer">
<a href="https://www.ceetronsolutions.com"><img src='https://resinsight.org//images/CeeSolLogoSmallForDarkBackground.png' style='width: 140px; '></a><br>
ResInsight is developed by <br> <a href="https://www.ceetronsolutions.com">Ceetron Solutions</a>
<p>in collaboration with</p>
<a href="https://www.equinor.com">Equinor ASA</a>
<script type="application/javascript">
var doNotTrack = false;
if (!doNotTrack) {
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-79509181-1', 'auto');
ga('send', 'pageview');
}
</script>
</section>
</div>
</nav>
<section id="body">
<div id="overlay"></div>
<div class="padding highlightable">
<div>
<div id="top-bar">
<div id="breadcrumbs" itemscope="" itemtype="http://data-vocabulary.org/Breadcrumb">
<span id="sidebar-toggle-span">
<a href="#" id="sidebar-toggle" data-sidebar-toggle="">
<i class="fas fa-bars"></i>
</a>
</span>
<span id="toc-menu"><i class="fas fa-list-alt"></i></span>
<span class="links">
<a href='/'>ResInsight</a> > <a href='/scripting/'>Scripting</a> > Python Examples
</span>
</div>
<div class="progress">
<div class="wrapper">
<nav id="TableOfContents">
<ul>
<li><a href="#allcases">AllCases</a></li>
<li><a href="#appinfo">AppInfo</a></li>
<li><a href="#casegridgroup">CaseGridGroup</a></li>
<li><a href="#caseinfostreamingexample">CaseInfoStreamingExample</a></li>
<li><a href="#commandexample">CommandExample</a></li>
<li><a href="#errorhandling">ErrorHandling</a></li>
<li><a href="#exportsnapshots">ExportSnapshots</a></li>
<li><a href="#gridinformation">GridInformation</a></li>
<li><a href="#inputproptestasync">InputPropTestAsync</a></li>
<li><a href="#inputproptestsync">InputPropTestSync</a></li>
<li><a href="#instanceexample">InstanceExample</a></li>
<li><a href="#launchwithcommandlineoptions">LaunchWithCommandLineOptions</a></li>
<li><a href="#selectedcases">SelectedCases</a></li>
<li><a href="#setcellresult">SetCellResult</a></li>
<li><a href="#setflowdiagnosticsresult">SetFlowDiagnosticsResult</a></li>
<li><a href="#setgridproperties">SetGridProperties</a></li>
<li><a href="#soilaverageasync">SoilAverageAsync</a></li>
<li><a href="#soilaveragesync">SoilAverageSync</a></li>
<li><a href="#soilporvasync">SoilPorvAsync</a></li>
<li><a href="#soilporvsync">SoilPorvSync</a></li>
<li><a href="#viewexample">ViewExample</a></li>
</ul>
</nav>
</div>
</div>
</div>
</div>
<div id="head-tags">
</div>
<div id="body-inner">
<h1>
Python Examples
</h1>
<p><img src="/images/scripting/python-logo-master-v3-TM.png" alt="" /></p>
<p>This pages is created based on the content in the <strong>PythonExamples</strong> folder located inside the <strong>rips</strong> module, made available online for convenience.</p>
<h1 id="allcases">AllCases</h1>
<pre><code>###################################################################################
# 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 (&quot;Got &quot; + str(len(cases)) + &quot; cases: &quot;)
for case in cases:
print(&quot;Case name: &quot; + case.name)
print(&quot;Case grid path: &quot; + case.gridPath())
timesteps = case.timeSteps()
for t in timesteps:
print(&quot;Year: &quot; + str(t.year))
print(&quot;Month: &quot; + str(t.month))
</code></pre>
<h1 id="appinfo">AppInfo</h1>
<pre><code>import rips
resInsight = rips.Instance.find()
if resInsight is not None:
print(resInsight.versionString())
print(&quot;Is this a console run?&quot;, resInsight.isConsole())
</code></pre>
<h1 id="casegridgroup">CaseGridGroup</h1>
<pre><code>import os
import rips
resInsight = rips.Instance.find()
casePaths = []
casePaths.append(&quot;C:/Users/lindk/source/repos/ResInsight/TestModels/Case_with_10_timesteps/Real0/BRUGGE_0000.EGRID&quot;)
casePaths.append(&quot;C:/Users/lindk/source/repos/ResInsight/TestModels/Case_with_10_timesteps/Real10/BRUGGE_0010.EGRID&quot;)
for casePath in casePaths:
assert os.path.exists(casePath), &quot;You need to set valid case paths for this script to work&quot;
caseGroup = resInsight.project.createGridCaseGroup(casePaths=casePaths)
caseGroup.printObjectInfo()
#statCases = caseGroup.statisticsCases()
#caseIds = []
#for statCase in statCases:
# statCase.setValue(&quot;DynamicPropertiesToCalculate&quot;, [&quot;SWAT&quot;])
# statCase.update()
# caseIds.append(statCase.getValue(&quot;CaseId&quot;))
resInsight.commands.computeCaseGroupStatistics(caseGroupId=caseGroup.groupId)
view = caseGroup.views()[0]
cellResult = view.cellResult()
cellResult.setValue(&quot;ResultVariable&quot;, &quot;PRESSURE_DEV&quot;)
cellResult.update()
</code></pre>
<h1 id="caseinfostreamingexample">CaseInfoStreamingExample</h1>
<pre><code>###############################################################################
# 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 case with id == 0. This will fail if your project doesn't have a case with id == 0
case = resInsight.project.case(id = 0)
# Get the cell count object
cellCounts = case.cellCount()
print(&quot;Number of active cells: &quot; + str(cellCounts.active_cell_count))
print(&quot;Total number of reservoir cells: &quot; + str(cellCounts.reservoir_cell_count))
# Get information for all active cells
activeCellInfos = case.cellInfoForActiveCells()
# A simple check on the size of the cell info
assert(cellCounts.active_cell_count == len(activeCellInfos))
# Print information for the first active cell
print(&quot;First active cell: &quot;)
print(activeCellInfos[0])
</code></pre>
<h1 id="commandexample">CommandExample</h1>
<pre><code>###############################################################################
# This example will run a few ResInsight command file commands
# .. which are exposed in the Python interface.
# Including setting time step, window size and export snapshots and properties
###############################################################################
import os
import tempfile
import rips
# Load instance
resInsight = rips.Instance.find()
# Run a couple of commands
resInsight.commands.setTimeStep(caseId=0, timeStep=3)
resInsight.commands.setMainWindowSize(width=800, height=500)
# 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=&quot;rips&quot;) as tmpdirname:
print(&quot;Temporary folder: &quot;, tmpdirname)
# Set export folder for snapshots and properties
resInsight.commands.setExportFolder(type='SNAPSHOTS', path=tmpdirname)
resInsight.commands.setExportFolder(type='PROPERTIES', path=tmpdirname)
# Export snapshots
resInsight.commands.exportSnapshots()
# Print contents of temporary folder
print(os.listdir(tmpdirname))
assert(len(os.listdir(tmpdirname)) &gt; 0)
case = resInsight.project.case(id=0)
# Export properties in the view
resInsight.commands.exportPropertyInViews(0, &quot;3D View&quot;, 0)
# Check that the exported file exists
expectedFileName = case.name + &quot;-&quot; + str(&quot;3D_View&quot;) + &quot;-&quot; + &quot;T3&quot; + &quot;-SOIL&quot;
fullPath = tmpdirname + &quot;/&quot; + expectedFileName
assert(os.path.exists(fullPath))
</code></pre>
<h1 id="errorhandling">ErrorHandling</h1>
<pre><code>###################################################################
# This example demonstrates the use of ResInsight exceptions
# for proper error handling
###################################################################
import rips
import grpc
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.loadCase(&quot;Nonsense&quot;)
except grpc.RpcError as e:
print(&quot;Expected Server Exception Received: &quot;, e)
case = resInsight.project.case(id=0)
if case is not None:
results = case.properties.activeCellProperty('STATIC_NATIVE', 'PORO', 0)
activeCellCount = len(results)
# Send the results back to ResInsight inside try / except construct
try:
case.properties.setActiveCellProperty(results, 'GENERATED', 'POROAPPENDED', 0)
print(&quot;Everything went well as expected&quot;)
except: # Match any exception, but it should not happen
print(&quot;Ooops!&quot;)
# 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.properties.setActiveCellProperty(results, 'GENERATED', 'POROAPPENDED', 0)
print(&quot;Everything went well??&quot;)
except grpc.RpcError as e:
print(&quot;Expected Server Exception Received: &quot;, e)
except IndexError:
print (&quot;Got index out of bounds error. This shouldn't happen here&quot;)
# 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.properties.chunkSize = activeCellCount
try:
case.properties.setActiveCellProperty(results, 'GENERATED', 'POROAPPENDED', 0)
print(&quot;Everything went well??&quot;)
except grpc.RpcError as e:
print(&quot;Got unexpected server exception&quot;, e, &quot;This should not happen now&quot;)
except IndexError:
print (&quot;Got expected index out of bounds error on client side&quot;)
</code></pre>
<h1 id="exportsnapshots">ExportSnapshots</h1>
<pre><code>############################################################################
# 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.commands.setMainWindowSize(width=800, height=500)
n = 5 # every n-th timestep for snapshot
property_list = ['SOIL', 'PRESSURE'] # list of parameter for snapshot
print (&quot;Looping through cases&quot;)
for case in cases:
# Get grid path and its folder name
casepath = case.gridPath()
foldername = os.path.dirname(casepath)
# create a folder to hold the snapshots
dirname = os.path.join(foldername, 'snapshots')
if os.path.exists(dirname) is False:
os.mkdir(dirname)
print (&quot;Exporting to folder: &quot; + dirname)
resInsight.commands.setExportFolder(type='SNAPSHOTS', path=dirname)
timeSteps = case.timeSteps()
tss_snapshot = range(0, len(timeSteps), n)
print(case.name, case.id, 'Number of timesteps: ' + str(len(timeSteps)))
print('Number of timesteps for snapshoting: ' + str(len(tss_snapshot)))
view = case.views()[0]
for property in property_list:
view.applyCellResult(resultType='DYNAMIC_NATIVE', resultVariable=property)
for ts_snapshot in tss_snapshot:
resInsight.commands.setTimeStep(caseId = case.id, timeStep = ts_snapshot)
resInsight.commands.exportSnapshots(type='VIEWS', caseId=case.id) # ALL, VIEWS or PLOTS default is 'ALL'
</code></pre>
<h1 id="gridinformation">GridInformation</h1>
<pre><code>######################################################################################
# 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(&quot;Number of cases found: &quot;, len(cases))
for case in cases:
print(case.name)
grids = case.grids()
print(&quot;Number of grids: &quot;, len(grids))
for grid in grids:
print(&quot;Grid dimensions: &quot;, grid.dimensions())
</code></pre>
<h1 id="inputproptestasync">InputPropTestAsync</h1>
<pre><code>########################################################################################
# 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 createResult(poroChunks, permxChunks):
# Loop through all the chunks of poro and permx in order
for (poroChunk, permxChunk) in zip(poroChunks, permxChunks):
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.case(id=0)
# Get a generator for the poro results. The generator will provide a chunk each time it is iterated
poroChunks = case.properties.activeCellPropertyAsync('STATIC_NATIVE', 'PORO', 0)
# Get a generator for the permx results. The generator will provide a chunk each time it is iterated
permxChunks = case.properties.activeCellPropertyAsync('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.properties.setActiveCellPropertyAsync(createResult(poroChunks, permxChunks),
'GENERATED', 'POROPERMXAS', 0)
end = time.time()
print(&quot;Time elapsed: &quot;, end - start)
print(&quot;Transferred all results back&quot;)
view = case.views()[0].applyCellResult('GENERATED', 'POROPERMXAS')
</code></pre>
<h1 id="inputproptestsync">InputPropTestSync</h1>
<pre><code>########################################################################################
# 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.case(id=0)
# Read poro result into list
poroResults = case.properties.activeCellProperty('STATIC_NATIVE', 'PORO', 0)
# Read permx result into list
permxResults = case.properties.activeCellProperty('STATIC_NATIVE', 'PERMX', 0)
# Generate output result
results = []
for (poro, permx) in zip(poroResults, permxResults):
results.append(poro * permx)
try:
# Send back output result
case.properties.setActiveCellProperty(results, 'GENERATED', 'POROPERMXSY', 0)
except grpc.RpcError as e:
print(&quot;Exception Received: &quot;, e)
end = time.time()
print(&quot;Time elapsed: &quot;, end - start)
print(&quot;Transferred all results back&quot;)
view = case.views()[0].applyCellResult('GENERATED', 'POROPERMXSY')
</code></pre>
<h1 id="instanceexample">InstanceExample</h1>
<pre><code>#######################################
# 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')
</code></pre>
<h1 id="launchwithcommandlineoptions">LaunchWithCommandLineOptions</h1>
<pre><code># 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(commandLineParameters=['--last', '--size', 600, 1000])
# Get a list of all cases
cases = resInsight.project.cases()
print (&quot;Got &quot; + str(len(cases)) + &quot; cases: &quot;)
for case in cases:
print(&quot;Case name: &quot; + case.name)
print(&quot;Case grid path: &quot; + case.gridPath())
</code></pre>
<h1 id="selectedcases">SelectedCases</h1>
<pre><code>############################################################################
# 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.selectedCases()
print (&quot;Got &quot; + str(len(cases)) + &quot; cases: &quot;)
for case in cases:
print(case.name)
for property in case.properties.available('DYNAMIC_NATIVE'):
print(property)
</code></pre>
<h1 id="setcellresult">SetCellResult</h1>
<pre><code>######################################################################
# This script applies a cell result to the first view in the project
######################################################################
import rips
resInsight = rips.Instance.find()
view = resInsight.project.view(0)
view.applyCellResult(resultType='STATIC_NATIVE', resultVariable='DX')
</code></pre>
<h1 id="setflowdiagnosticsresult">SetFlowDiagnosticsResult</h1>
<pre><code>######################################################################
# 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(0)
#view.applyFlowDiagnosticsCellResult(resultVariable='Fraction',
# selectionMode='FLOW_TR_INJ_AND_PROD')
# Example of setting individual wells. Commented out because well names are case specific.
view.applyFlowDiagnosticsCellResult(resultVariable='Fraction',
selectionMode='FLOW_TR_BY_SELECTION',
injectors = ['C-1H', 'C-2H', 'F-2H'],
producers = ['B-1AH', 'B-3H', 'D-1H'])
</code></pre>
<h1 id="setgridproperties">SetGridProperties</h1>
<pre><code>######################################################################
# This script sets values for SOIL for all grid cells in the first case in the project
######################################################################
import rips
resInsight = rips.Instance.find()
case = resInsight.project.case(id=0)
totalCellCount = case.cellCount().reservoir_cell_count
values = []
for i in range(0, totalCellCount):
values.append(i % 2 * 0.75);
print(&quot;Applying values to full grid&quot;)
case.properties.setGridProperty(values, 'DYNAMIC_NATIVE', 'SOIL', 0)
</code></pre>
<h1 id="soilaverageasync">SoilAverageAsync</h1>
<pre><code>###########################################################################################
# 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(id=0)
# Get a list of all time steps
timeSteps = case.timeSteps()
averages = []
for i in range(0, len(timeSteps)):
# Get the results from time step i asynchronously
# It actually returns a generator object almost immediately
resultChunks = case.properties.activeCellPropertyAsync('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 resultChunks:
mysum += sum(chunk.values)
count += len(chunk.values)
averages.append(mysum/count)
end = time.time()
print(&quot;Time elapsed: &quot;, end - start)
print(averages)
</code></pre>
<h1 id="soilaveragesync">SoilAverageSync</h1>
<pre><code>###########################################################################################
# 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()
case = resInsight.project.case(id=0)
# Get the case with case id 0
case = resInsight.project.case(id=0)
# Get a list of all time steps
timeSteps = case.timeSteps()
averages = []
for i in range(0, len(timeSteps)):
# Get a list of all the results for time step i
results = case.properties.activeCellProperty('DYNAMIC_NATIVE', 'SOIL', i)
mysum = sum(results)
averages.append(mysum/len(results))
end = time.time()
print(&quot;Time elapsed: &quot;, end - start)
print(averages)
</code></pre>
<h1 id="soilporvasync">SoilPorvAsync</h1>
<pre><code>##############################################################################
# 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 createResult(soilChunks, porvChunks):
for (soilChunk, porvChunk) in zip(soilChunks, porvChunks):
resultChunk = []
number = 0
for (soilValue, porvValue) in zip(soilChunk.values, porvChunk.values):
resultChunk.append(soilValue * porvValue)
# Return a Python generator
yield resultChunk
resInsight = rips.Instance.find()
start = time.time()
case = resInsight.project.case(id=0)
timeStepInfo = case.timeSteps()
# Get a generator for the porv results. The generator will provide a chunk each time it is iterated
porvChunks = case.properties.activeCellPropertyAsync('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
porvArray = []
for porvChunk in porvChunks:
porvArray.append(porvChunk)
for i in range (0, len(timeStepInfo)):
# Get a generator object for the SOIL property for time step i
soilChunks = case.properties.activeCellPropertyAsync('DYNAMIC_NATIVE', 'SOIL', i)
# Create the generator object for the SOIL * PORV derived result
result_generator = createResult(soilChunks, iter(porvArray))
# Send back the result asynchronously with a generator object
case.properties.setActiveCellPropertyAsync(result_generator, 'GENERATED', 'SOILPORVAsync', i)
end = time.time()
print(&quot;Time elapsed: &quot;, end - start)
print(&quot;Transferred all results back&quot;)
view = case.views()[0].applyCellResult('GENERATED', 'SOILPORVAsync')
</code></pre>
<h1 id="soilporvsync">SoilPorvSync</h1>
<pre><code>##############################################################################
# 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.case(id=0)
# Read the full porv result
porvResults = case.properties.activeCellProperty('STATIC_NATIVE', 'PORV', 0)
timeStepInfo = case.timeSteps()
for i in range (0, len(timeStepInfo)):
# Read the full SOIl result for time step i
soilResults = case.properties.activeCellProperty('DYNAMIC_NATIVE', 'SOIL', i)
# Generate the result by looping through both lists in order
results = []
for (soil, porv) in zip(soilResults, porvResults):
results.append(soil * porv)
# Send back result
case.properties.setActiveCellProperty(results, 'GENERATED', 'SOILPORVSync', i)
end = time.time()
print(&quot;Time elapsed: &quot;, end - start)
print(&quot;Transferred all results back&quot;)
view = case.views()[0].applyCellResult('GENERATED', 'SOILPORVSync')
</code></pre>
<h1 id="viewexample">ViewExample</h1>
<pre><code>#############################################################
# 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.setShowGridBox(not view.showGridBox())
view.setBackgroundColor(&quot;#3388AA&quot;)
# Update the view in ResInsight
view.update()
# Clone the first view
newView = views[0].clone()
view.setShowGridBox(False)
newView.setBackgroundColor(&quot;#FFAA33&quot;)
newView.update()
</code></pre>
<footer class=" footline" >
</footer>
</div>
</div>
<div id="navigation">
<a class="nav nav-prev" href="/scripting/commandfile/" title="Command File"> <i class="fa fa-chevron-left"></i></a>
<a class="nav nav-next" href="/scripting/pythonrips/" title="Python API - rips" style="margin-right: 0px;"><i class="fa fa-chevron-right"></i></a>
</div>
</section>
<div style="left: -1000px; overflow: scroll; position: absolute; top: -1000px; border: none; box-sizing: content-box; height: 200px; margin: 0px; padding: 0px; width: 200px;">
<div style="border: none; box-sizing: content-box; height: 200px; margin: 0px; padding: 0px; width: 200px;"></div>
</div>
<script src="/js/clipboard.min.js?1568366249"></script>
<script src="/js/perfect-scrollbar.min.js?1568366249"></script>
<script src="/js/perfect-scrollbar.jquery.min.js?1568366249"></script>
<script src="/js/jquery.sticky.js?1568366249"></script>
<script src="/js/featherlight.min.js?1568366249"></script>
<script src="/js/html5shiv-printshiv.min.js?1568366249"></script>
<script src="/js/highlight.pack.js?1568366249"></script>
<script>hljs.initHighlightingOnLoad();</script>
<script src="/js/modernizr.custom-3.6.0.js?1568366249"></script>
<script src="/js/learn.js?1568366249"></script>
<script src="/js/hugo-learn.js?1568366249"></script>
<link href="/mermaid/mermaid.css?1568366249" rel="stylesheet" />
<script src="/mermaid/mermaid.js?1568366249"></script>
<script>
mermaid.initialize({ startOnLoad: true });
</script>
</body>
</html>