Merge pull request #4738 from OPM/system-python-renames-pep8

#4736 Renames of python methods and variables to match PEP8
This commit is contained in:
Gaute Lindkvist 2019-09-20 12:23:34 +02:00 committed by GitHub
commit 374a4e396b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
35 changed files with 757 additions and 743 deletions

View File

@ -31,13 +31,13 @@ class Case (PdmObject):
self.id = id
info = self.stub.GetCaseInfo(Case_pb2.CaseRequest(id=self.id))
self.name = info.name
self.groupId = info.group_id
self.group_id = info.group_id
self.type = info.type
self.properties = Properties(self)
self.request = Case_pb2.CaseRequest(id=self.id)
PdmObject.__init__(self, self.stub.GetPdmObject(self.request), self.channel)
def gridCount(self):
def grid_count(self):
"""Get number of grids in the case"""
try:
return self.stub.GetGridCount(self.request).count
@ -47,8 +47,8 @@ class Case (PdmObject):
print("ERROR: ", e)
return 0
def gridPath(self):
return self.getValue("CaseFileName")
def grid_path(self):
return self.get_value("CaseFileName")
def grid(self, index):
"""Get Grid of a given index. Returns a rips Grid object
@ -62,50 +62,50 @@ class Case (PdmObject):
def grids(self):
"""Get a list of all rips Grid objects in the case"""
gridList = []
for i in range(0, self.gridCount()):
gridList.append(Grid(i, self))
return gridList
grid_list = []
for i in range(0, self.grid_count()):
grid_list.append(Grid(i, self))
return grid_list
def cellCount(self, porosityModel='MATRIX_MODEL'):
def cell_count(self, porosity_model='MATRIX_MODEL'):
"""Get a cell count object containing number of active cells and
total number of cells
Arguments:
porosityModel (str): String representing an enum.
porosity_model (str): String representing an enum.
must be 'MATRIX_MODEL' or 'FRACTURE_MODEL'.
Returns:
Cell Count object with the following integer attributes:
active_cell_count: number of active cells
reservoir_cell_count: total number of reservoir cells
"""
porosityModelEnum = Case_pb2.PorosityModelType.Value(porosityModel)
porosity_model_enum = Case_pb2.PorosityModelType.Value(porosity_model)
request = Case_pb2.CellInfoRequest(case_request=self.request,
porosity_model=porosityModel)
porosity_model=porosity_model_enum)
return self.stub.GetCellCount(request)
def cellInfoForActiveCellsAsync(self, porosityModel='MATRIX_MODEL'):
def cell_info_for_active_cells_async(self, porosity_model='MATRIX_MODEL'):
"""Get Stream of cell info objects for current case
Arguments:
porosityModel(str): String representing an enum.
porosity_model(str): String representing an enum.
must be 'MATRIX_MODEL' or 'FRACTURE_MODEL'.
Returns:
Stream of **CellInfo** objects
See cellInfoForActiveCells() for detalis on the **CellInfo** class.
See cell_info_for_active_cells() for detalis on the **CellInfo** class.
"""
porosityModelEnum = Case_pb2.PorosityModelType.Value(porosityModel)
porosity_model_enum = Case_pb2.PorosityModelType.Value(porosity_model)
request = Case_pb2.CellInfoRequest(case_request=self.request,
porosity_model=porosityModel)
porosity_model=porosity_model_enum)
return self.stub.GetCellInfoForActiveCells(request)
def cellInfoForActiveCells(self, porosityModel='MATRIX_MODEL'):
def cell_info_for_active_cells(self, porosity_model='MATRIX_MODEL'):
"""Get list of cell info objects for current case
Arguments:
porosityModel(str): String representing an enum.
porosity_model(str): String representing an enum.
must be 'MATRIX_MODEL' or 'FRACTURE_MODEL'.
Returns:
@ -130,14 +130,14 @@ class Case (PdmObject):
k | K grid index | Integer
"""
activeCellInfoChunks = self.cellInfoForActiveCellsAsync()
receivedActiveCells = []
for activeCellChunk in activeCellInfoChunks:
for activeCell in activeCellChunk.data:
receivedActiveCells.append(activeCell)
return receivedActiveCells
active_cell_info_chunks = self.cell_info_for_active_cells_async()
received_active_cells = []
for active_cell_chunk in active_cell_info_chunks:
for active_cell in active_cell_chunk.data:
received_active_cells.append(active_cell)
return received_active_cells
def timeSteps(self):
def time_steps(self):
"""Get a list containing all time steps
The time steps are defined by the class **TimeStepDate** :
@ -155,17 +155,17 @@ class Case (PdmObject):
"""
return self.stub.GetTimeSteps(self.request).dates
def daysSinceStart(self):
def days_since_start(self):
"""Get a list of decimal values representing days since the start of the simulation"""
return self.stub.GetDaysSinceStart(self.request).day_decimals
def views(self):
"""Get a list of views belonging to a case"""
pbmObjects = self.children("ReservoirViews")
viewList = []
for pbmObject in pbmObjects:
viewList.append(View(pbmObject))
return viewList
pdm_objects = self.children("ReservoirViews")
view_list = []
for pdm_object in pdm_objects:
view_list.append(View(pdm_object))
return view_list
def view(self, id):
"""Get a particular view belonging to a case by providing view id
@ -176,13 +176,13 @@ class Case (PdmObject):
"""
views = self.views()
for viewObject in views:
if viewObject.id == id:
return viewObject
for view_object in views:
if view_object.id == id:
return view_object
return None
def createView(self):
def create_view(self):
"""Create a new view in the current case"""
viewId = Commands(self.channel).createView(self.id)
return self.view(viewId)
view_id = Commands(self.channel).create_view(self.id)
return self.view(view_id)

View File

@ -23,14 +23,14 @@ class Commands:
self.channel = channel
self.commands = CmdRpc.CommandsStub(channel)
def __execute(self, **commandParams):
return self.commands.Execute(Cmd.CommandParams(**commandParams))
def __execute(self, **command_params):
return self.commands.Execute(Cmd.CommandParams(**command_params))
########################
# Case Control Commands
########################
def openProject(self, path):
def open_project(self, path):
"""Open a project
Arguments:
@ -40,11 +40,11 @@ class Commands:
"""
return self.__execute(openProject=Cmd.FilePathRequest(path=path))
def closeProject(self):
def close_project(self):
"""Close the current project (and reopen empty one)"""
return self.__execute(closeProject=Empty())
def setStartDir(self, path):
def set_start_dir(self, path):
"""Set current start directory
Arguments:
@ -53,7 +53,7 @@ class Commands:
"""
return self.__execute(setStartDir=Cmd.FilePathRequest(path=path))
def loadCase(self, path):
def load_case(self, path):
"""Load a case
Arguments:
@ -63,234 +63,249 @@ class Commands:
A Case object
"""
commandReply = self.__execute(loadCase=Cmd.FilePathRequest(path=path))
return rips.Case(self.channel, commandReply.loadCaseResult.id)
command_reply = self.__execute(loadCase=Cmd.FilePathRequest(path=path))
return rips.Case(self.channel, command_reply.loadCaseResult.id)
def replaceCase(self, newGridFile, caseId=0):
def replace_case(self, new_grid_file, case_id=0):
"""Replace the given case with a new case loaded from file
Arguments:
newGridFile (str): path to EGRID file
caseId (int): case Id to replace
new_grid_file (str): path to EGRID file
case_id (int): case Id to replace
"""
return self.__execute(replaceCase=Cmd.ReplaceCaseRequest(newGridFile=newGridFile,
caseId=caseId))
return self.__execute(replaceCase=Cmd.ReplaceCaseRequest(newGridFile=new_grid_file,
caseId=case_id))
def replaceSourceCases(self, gridListFile, caseGroupId=0):
def replace_source_cases(self, grid_list_file, case_group_id=0):
"""Replace all source cases within a case group
Arguments:
gridListFile (str): path to file containing a list of cases
caseGroupId (int): id of the case group to replace
grid_list_file (str): path to file containing a list of cases
case_group_id (int): id of the case group to replace
"""
return self.__execute(replaceSourceCases=Cmd.ReplaceSourceCasesRequest(gridListFile=gridListFile,
caseGroupId=caseGroupId))
return self.__execute(replaceSourceCases=Cmd.ReplaceSourceCasesRequest(gridListFile=grid_list_file,
caseGroupId=case_group_id))
def createGridCaseGroup(self, casePaths):
def create_grid_case_group(self, case_paths):
"""Create a Grid Case Group from a list of cases
Arguments:
casePaths (list): list of file path strings
case_paths (list): list of file path strings
Returns:
A case group id and name
"""
commandReply = self.__execute(createGridCaseGroup=Cmd.CreateGridCaseGroupRequest(casePaths=casePaths))
commandReply = self.__execute(createGridCaseGroup=Cmd.CreateGridCaseGroupRequest(casePaths=case_paths))
return (commandReply.createGridCaseGroupResult.groupId, commandReply.createGridCaseGroupResult.groupName)
def createStatisticsCase(self, caseGroupId):
commandReply = self.__execute(createStatisticsCase=Cmd.CreateStatisticsCaseRequest(caseGroupId=caseGroupId))
return commandReply.createStatisticsCaseResult.caseId;
def create_statistics_case(self, case_group_id):
"""Create a Statistics case in a Grid Case Group
Arguments:
case_group_id (int): id of the case group
Returns:
A case id for the new case
"""
commandReply = self.__execute(createStatisticsCase=Cmd.CreateStatisticsCaseRequest(caseGroupId=case_group_id))
return commandReply.createStatisticsCaseResult.caseId
##################
# Export Commands
##################
def exportMultiCaseSnapshots(self, gridListFile):
def export_multi_case_snapshots(self, grid_list_file):
"""Export snapshots for a set of cases
Arguments:
gridListFile (str): Path to a file containing a list of grids to export snapshot for
grid_list_file (str): Path to a file containing a list of grids to export snapshot for
"""
return self.__execute(exportMultiCaseSnapshot=Cmd.ExportMultiCaseRequest(gridListFile=gridListFile))
return self.__execute(exportMultiCaseSnapshot=Cmd.ExportMultiCaseRequest(gridListFile=grid_list_file))
def exportSnapshots(self, type = 'ALL', prefix='', caseId = -1):
def export_snapshots(self, type = 'ALL', prefix='', case_id = -1):
""" Export snapshots of a given type
Arguments:
type (str): Enum string ('ALL', 'VIEWS' or 'PLOTS')
prefix (str): Exported file name prefix
caseId (int): the case Id to export for. The default of -1 will export all cases
case_id (int): the case Id to export for. The default of -1 will export all cases
"""
return self.__execute(exportSnapshots=Cmd.ExportSnapshotsRequest(type=type,
prefix=prefix,
caseId=caseId))
caseId=case_id))
def exportProperty(self, caseId, timeStep, property, eclipseKeyword=property, undefinedValue=0.0, exportFile=property):
def export_property(self, case_id, time_step, property, eclipse_keyword=property, undefined_value=0.0, export_file=property):
""" Export an Eclipse property
Arguments:
caseId (int): case id
timeStep (int): time step index
case_id (int): case id
time_step (int): time step index
property (str): property to export
eclipseKeyword (str): Eclipse keyword used as text in export header. Defaults to the value of property parameter.
undefinedValue (double): Value to use for undefined values. Defaults to 0.0
exportFile (str): Filename for export. Defaults to the value of property parameter
eclipse_keyword (str): Eclipse keyword used as text in export header. Defaults to the value of property parameter.
undefined_value (double): Value to use for undefined values. Defaults to 0.0
export_file (str): File name for export. Defaults to the value of property parameter
"""
return self.__execute(exportProperty=Cmd.ExportPropertyRequest(caseId=caseId,
timeStep=timeStep,
return self.__execute(exportProperty=Cmd.ExportPropertyRequest(caseId=case_id,
timeStep=time_step,
property=property,
eclipseKeyword=eclipseKeyword,
undefinedValue=undefinedValue,
exportFile=exportFile))
eclipseKeyword=eclipse_keyword,
undefinedValue=undefined_value,
exportFile=export_file))
def exportPropertyInViews(self, caseId, viewNames, undefinedValue):
if isinstance(viewNames, str):
viewNames = [viewNames]
def export_property_in_views(self, case_id, view_names, undefined_value):
""" Export the current Eclipse property from the given views
return self.__execute(exportPropertyInViews=Cmd.ExportPropertyInViewsRequest(caseId=caseId,
viewNames=viewNames,
undefinedValue=undefinedValue))
Arguments:
case_id (int): case id
view_names (list): list of views
undefined_value (double): Value to use for undefined values. Defaults to 0.0
"""
if isinstance(view_names, str):
view_names = [view_names]
def exportWellPathCompletions(self, caseId, timeStep, wellPathNames, fileSplit,
compdatExport, includePerforations, includeFishbones,
excludeMainBoreForFishbones, combinationMode):
if (isinstance(wellPathNames, str)):
wellPathNames = [wellPathNames]
return self.__execute(exportWellPathCompletions=Cmd.ExportWellPathCompRequest(caseId=caseId,
timeStep=timeStep,
wellPathNames=wellPathNames,
fileSplit=fileSplit,
compdatExport=compdatExport,
includePerforations=includePerforations,
includeFishbones=includeFishbones,
excludeMainBoreForFishbones=excludeMainBoreForFishbones,
combinationMode=combinationMode))
return self.__execute(exportPropertyInViews=Cmd.ExportPropertyInViewsRequest(caseId=case_id,
viewNames=view_names,
undefinedValue=undefined_value))
def exportSimWellFractureCompletions(self, caseId, viewName, timeStep, simulationWellNames, fileSplit, compdatExport):
if(isinstance(simulationWellNames, str)):
simulationWellNames = [simulationWellNames]
return self.__execute(exportSimWellFractureCompletions=Cmd.ExportSimWellPathFraqRequest(caseId=caseId,
viewName=viewName,
timeStep=timeStep,
simulationWellNames=simulationWellNames,
fileSplit=fileSplit,
compdatExport=compdatExport))
def export_well_path_completions(self, case_id, time_step, well_path_names, file_split,
compdat_export, include_perforations, include_fishbones,
exclude_main_bore_for_fishbones, combination_mode):
if (isinstance(well_path_names, str)):
well_path_names = [well_path_names]
return self.__execute(exportWellPathCompletions=Cmd.ExportWellPathCompRequest(caseId=case_id,
timeStep=time_step,
wellPathNames=well_path_names,
fileSplit=file_split,
compdatExport=compdat_export,
includePerforations=include_perforations,
includeFishbones=include_fishbones,
excludeMainBoreForFishbones=exclude_main_bore_for_fishbones,
combinationMode=combination_mode))
def exportMsw(self, caseId, wellPath):
return self.__execute(exportMsw=Cmd.ExportMswRequest(caseId=caseId,
wellPath=wellPath))
def export_sim_well_fracture_completions(self, case_id, view_name, time_step, simulation_well_names, file_split, compdat_export):
if(isinstance(simulation_well_names, str)):
simulation_well_names = [simulation_well_names]
return self.__execute(exportSimWellFractureCompletions=Cmd.ExportSimWellPathFraqRequest(caseId=case_id,
viewName=view_name,
timeStep=time_step,
simulationWellNames=simulation_well_names,
fileSplit=file_split,
compdatExport=compdat_export))
def exportWellPaths(self, wellPaths=[], mdStepSize=5.0):
if isinstance(wellPaths, str):
wellPaths = [wellPaths]
return self.__execute(exportWellPaths=Cmd.ExportWellPathRequest(wellPathNames=wellPaths, mdStepSize=mdStepSize))
def export_msw(self, case_id, well_path):
return self.__execute(exportMsw=Cmd.ExportMswRequest(caseId=case_id,
wellPath=well_path))
def exportVisibleCells(self, caseId, viewName, exportKeyword='FLUXNUM', visibleActiveCellsValue=1, hiddenActiveCellsValue=0, inactiveCellsValue=0):
return self.__execute(exportVisibleCells=Cmd.ExportVisibleCellsRequest(caseId=caseId,
viewName=viewName,
exportKeyword=exportKeyword,
visibleActiveCellsValue=visibleActiveCellsValue,
hiddenActiveCellsValue=hiddenActiveCellsValue,
inactiveCellsValue=inactiveCellsValue))
def setExportFolder(self, type, path, createFolder=False):
def export_well_paths(self, well_paths=[], md_step_size=5.0):
if isinstance(well_paths, str):
well_paths = [well_paths]
return self.__execute(exportWellPaths=Cmd.ExportWellPathRequest(wellPathNames=well_paths, mdStepSize=md_step_size))
def export_visible_cells(self, case_id, view_name, export_keyword='FLUXNUM', visible_active_cells_value=1, hidden_active_cells_value=0, inactive_cells_value=0):
return self.__execute(exportVisibleCells=Cmd.ExportVisibleCellsRequest(caseId=case_id,
viewName=view_name,
exportKeyword=export_keyword,
visibleActiveCellsValue=visible_active_cells_value,
hiddenActiveCellsValue=hidden_active_cells_value,
inactiveCellsValue=inactive_cells_value))
def set_export_folder(self, type, path, create_folder=False):
return self.__execute(setExportFolder=Cmd.SetExportFolderRequest(type=type,
path=path,
createFolder=createFolder))
createFolder=create_folder))
def runOctaveScript(self, path, cases):
def run_octave_script(self, path, cases):
caseIds = []
for case in cases:
caseIds.append(case.id)
return self.__execute(runOctaveScript=Cmd.RunOctaveScriptRequest(path=path,
caseIds=caseIds))
def setMainWindowSize(self, width, height):
def set_main_window_size(self, width, height):
return self.__execute(setMainWindowSize=Cmd.SetMainWindowSizeParams(width=width, height=height))
def computeCaseGroupStatistics(self, caseIds = [], caseGroupId = -1):
return self.__execute(computeCaseGroupStatistics=Cmd.ComputeCaseGroupStatRequest(caseIds=caseIds,
caseGroupId=caseGroupId))
def compute_case_group_statistics(self, case_ids = [], case_group_id = -1):
return self.__execute(computeCaseGroupStatistics=Cmd.ComputeCaseGroupStatRequest(caseIds=case_ids,
caseGroupId=case_group_id))
def setTimeStep(self, caseId, timeStep):
return self.__execute(setTimeStep=Cmd.SetTimeStepParams(caseId=caseId, timeStep=timeStep))
def set_time_step(self, case_id, time_step):
return self.__execute(setTimeStep=Cmd.SetTimeStepParams(caseId=case_id, timeStep=time_step))
def scaleFractureTemplate(self, id, halfLength, height, dFactor, conductivity):
def scale_fracture_template(self, id, half_length, height, dfactor, conductivity):
return self.__execute(scaleFractureTemplate=Cmd.ScaleFractureTemplateRequest(id=id,
halfLength=halfLength,
halfLength=half_length,
height=height,
dFactor=dFactor,
dFactor=dfactor,
conductivity=conductivity))
def setFractureContainment(self, id, topLayer, baseLayer):
def set_fracture_containment(self, id, top_layer, base_layer):
return self.__execute(setFractureContainment=Cmd.SetFracContainmentRequest(id=id,
topLayer=topLayer,
baseLayer=baseLayer))
topLayer=top_layer,
baseLayer=base_layer))
def createMultipleFractures(self, caseId, templateId, wellPathNames, minDistFromWellTd,
maxFracturesPerWell, topLayer, baseLayer, spacing, action):
if isinstance(wellPathNames, str):
wellPathNames = [wellPathNames]
return self.__execute(createMultipleFractures=Cmd.MultipleFracAction(caseId=caseId,
templateId=templateId,
wellPathNames=wellPathNames,
minDistFromWellTd=minDistFromWellTd,
maxFracturesPerWell=maxFracturesPerWell,
topLayer=topLayer,
baseLayer=baseLayer,
def create_multiple_fractures(self, case_id, template_id, well_path_names, min_dist_from_well_td,
max_fractures_per_well, top_layer, base_layer, spacing, action):
if isinstance(well_path_names, str):
well_path_names = [well_path_names]
return self.__execute(createMultipleFractures=Cmd.MultipleFracAction(caseId=case_id,
templateId=template_id,
wellPathNames=well_path_names,
minDistFromWellTd=min_dist_from_well_td,
maxFracturesPerWell=max_fractures_per_well,
topLayer=top_layer,
baseLayer=base_layer,
spacing=spacing,
action=action))
def createLgrForCompletions(self, caseId, timeStep, wellPathNames, refinementI, refinementJ, refinementK, splitType):
if isinstance(wellPathNames, str):
wellPathNames = [wellPathNames]
return self.__execute(createLgrForCompletions=Cmd.CreateLgrForCompRequest(caseId=caseId,
timeStep=timeStep,
wellPathNames=wellPathNames,
refinementI=refinementI,
refinementJ=refinementJ,
refinementK=refinementK,
splitType=splitType))
def create_lgr_for_completion(self, case_id, time_step, well_path_names, refinement_i, refinement_j, refinement_k, split_type):
if isinstance(well_path_names, str):
well_path_names = [well_path_names]
return self.__execute(createLgrForCompletions=Cmd.CreateLgrForCompRequest(caseId=case_id,
timeStep=time_step,
wellPathNames=well_path_names,
refinementI=refinement_i,
refinementJ=refinement_j,
refinementK=refinement_k,
splitType=split_type))
def createSaturationPressurePlots(self, caseIds):
if isinstance(caseIds, int):
caseIds = [caseIds]
return self.__execute(createSaturationPressurePlots=Cmd.CreateSatPressPlotRequest(caseIds=caseIds))
def create_saturation_pressure_plots(self, case_ids):
if isinstance(case_ids, int):
case_ids = [case_ids]
return self.__execute(createSaturationPressurePlots=Cmd.CreateSatPressPlotRequest(caseIds=case_ids))
def exportFlowCharacteristics(self, caseId, timeSteps, injectors, producers, fileName, minimumCommunication=0.0, aquiferCellThreshold=0.1):
def export_flow_characteristics(self, case_id, time_steps, injectors, producers, file_name, minimum_communication=0.0, aquifer_cell_threshold=0.1):
""" Export Flow Characteristics data to text file in CSV format
Parameter | Description | Type
------------------------- | --------------------------------------------- | -----
caseId | ID of case | Integer
timeSteps | Time step indices | List of Integer
case_id | ID of case | Integer
time_steps | Time step indices | List of Integer
injectors | Injector names | List of Strings
producers | Producer names | List of Strings
fileName | Export file name | Integer
minimumCommunication | Minimum Communication, defaults to 0.0 | Integer
aquiferCellThreshold | Aquifer Cell Threshold, defaults to 0.1 | Integer
file_name | Export file name | Integer
minimum_communication | Minimum Communication, defaults to 0.0 | Integer
aquifer_cell_threshold | Aquifer Cell Threshold, defaults to 0.1 | Integer
"""
if isinstance(timeSteps, int):
timeSteps = [timeSteps]
if isinstance(time_steps, int):
time_steps = [time_steps]
if isinstance(injectors, str):
injectors = [injectors]
if isinstance(producers, str):
producers = [producers]
return self.__execute(exportFlowCharacteristics=Cmd.ExportFlowInfoRequest(caseId=caseId,
timeSteps=timeSteps,
return self.__execute(exportFlowCharacteristics=Cmd.ExportFlowInfoRequest(caseId=case_id,
timeSteps=time_steps,
injectors=injectors,
producers=producers,
fileName=fileName,
minimumCommunication = minimumCommunication,
aquiferCellThreshold = aquiferCellThreshold))
fileName=file_name,
minimumCommunication = minimum_communication,
aquiferCellThreshold = aquifer_cell_threshold))
def createView(self, caseId):
return self.__execute(createView=Cmd.CreateViewRequest(caseId=caseId)).createViewResult.viewId
def create_view(self, case_id):
return self.__execute(createView=Cmd.CreateViewRequest(caseId=case_id)).createViewResult.viewId
def cloneView(self, viewId):
return self.__execute(cloneView=Cmd.CloneViewRequest(viewId=viewId)).createViewResult.viewId
def clone_view(self, view_id):
return self.__execute(cloneView=Cmd.CloneViewRequest(viewId=view_id)).createViewResult.viewId

View File

@ -14,25 +14,24 @@ class GridCaseGroup (PdmObject):
Operate on a ResInsight case group specified by a Case Group Id integer.
Attributes:
id (int): Grid Case Group Id corresponding to case group Id in ResInsight project.
name (str): Case name
group_id (int): Grid Case Group Id corresponding to case group Id in ResInsight project.
"""
def __init__(self, pdmObject):
self.groupId = pdmObject.getValue("GroupId")
PdmObject.__init__(self, pdmObject.pb2Object, pdmObject.channel)
def __init__(self, pdm_object):
self.group_id = pdm_object.get_value("GroupId")
PdmObject.__init__(self, pdm_object.pb2Object, pdm_object.channel)
def statisticsCases(self):
def statistics_cases(self):
"""Get a list of all statistics cases in the Grid Case Group"""
statCaseCollection = self.children("StatisticsCaseCollection")[0]
return statCaseCollection.children("Reservoirs")
stat_case_collection = self.children("StatisticsCaseCollection")[0]
return stat_case_collection.children("Reservoirs")
def views(self):
"""Get a list of views belonging to a grid case group"""
pbmObjects = self.descendants("ReservoirView")
viewList = []
for pbmObject in pbmObjects:
viewList.append(View(pbmObject))
return viewList
pdm_objects = self.descendants("ReservoirView")
view_list = []
for pdm_object in pdm_objects:
view_list.append(View(pdm_object))
return view_list
def view(self, id):
"""Get a particular view belonging to a case group by providing view id
@ -43,7 +42,7 @@ class GridCaseGroup (PdmObject):
"""
views = self.views()
for viewObject in views:
if viewObject.id == id:
return viewObject
for view_object in views:
if view_object.id == id:
return view_object
return None

View File

@ -33,33 +33,33 @@ class Instance:
return s.connect_ex(('localhost', port)) == 0
@staticmethod
def launch(resInsightExecutable = '', console = False, launchPort = -1, commandLineParameters=[]):
def launch(resinsight_executable = '', console = False, launch_port = -1, command_line_parameters=[]):
""" Launch a new Instance of ResInsight. This requires the environment variable
RESINSIGHT_EXECUTABLE to be set or the parameter resInsightExecutable to be provided.
RESINSIGHT_EXECUTABLE to be set or the parameter resinsight_executable to be provided.
The RESINSIGHT_GRPC_PORT environment variable can be set to an alternative port number.
Args:
resInsightExecutable (str): Path to a valid ResInsight executable. If set
resinsight_executable (str): Path to a valid ResInsight executable. If set
will take precedence over what is provided in the RESINSIGHT_EXECUTABLE
environment variable.
console (bool): If True, launch as console application, without GUI.
launchPort(int): If -1 will use the default port of 50051 or look for RESINSIGHT_GRPC_PORT
launch_port(int): If -1 will use the default port of 50051 or look for RESINSIGHT_GRPC_PORT
if anything else, ResInsight will try to launch with this port
commandLineParameters(list): Additional command line parameters as string entries in the list.
command_line_parameters(list): Additional command line parameters as string entries in the list.
Returns:
Instance: an instance object if it worked. None if not.
"""
port = 50051
portEnv = os.environ.get('RESINSIGHT_GRPC_PORT')
if portEnv:
port = int(portEnv)
if launchPort is not -1:
port = launchPort
port_env = os.environ.get('RESINSIGHT_GRPC_PORT')
if port_env:
port = int(port_env)
if launch_port is not -1:
port = launch_port
if not resInsightExecutable:
resInsightExecutable = os.environ.get('RESINSIGHT_EXECUTABLE')
if not resInsightExecutable:
if not resinsight_executable:
resinsight_executable = os.environ.get('RESINSIGHT_EXECUTABLE')
if not resinsight_executable:
print('ERROR: Could not launch ResInsight because the environment variable'
' RESINSIGHT_EXECUTABLE is not set')
return None
@ -68,12 +68,12 @@ class Instance:
port += 1
print('Port ' + str(port))
print('Trying to launch', resInsightExecutable)
print('Trying to launch', resinsight_executable)
if isinstance(commandLineParameters, str):
commandLineParameters = [str]
if isinstance(command_line_parameters, str):
command_line_parameters = [str]
parameters = ["ResInsight", "--server", str(port)] + commandLineParameters
parameters = ["ResInsight", "--server", str(port)] + command_line_parameters
if console:
print("Launching as console app")
parameters.append("--console")
@ -82,14 +82,14 @@ class Instance:
for i in range(0, len(parameters)):
parameters[i] = str(parameters[i])
pid = os.spawnv(os.P_NOWAIT, resInsightExecutable, parameters)
pid = os.spawnv(os.P_NOWAIT, resinsight_executable, parameters)
if pid:
instance = Instance(port=port, launched=True)
return instance
return None
@staticmethod
def find(startPort = 50051, endPort = 50071):
def find(start_port = 50051, end_port = 50071):
""" Search for an existing Instance of ResInsight by testing ports.
By default we search from port 50051 to 50071 or if the environment
@ -97,27 +97,27 @@ class Instance:
RESINSIGHT_GRPC_PORT to RESINSIGHT_GRPC_PORT+20
Args:
startPort (int): start searching from this port
endPort (int): search up to but not including this port
start_port (int): start searching from this port
end_port (int): search up to but not including this port
"""
portEnv = os.environ.get('RESINSIGHT_GRPC_PORT')
if portEnv:
startPort = int(portEnv)
endPort = startPort + 20
port_env = os.environ.get('RESINSIGHT_GRPC_PORT')
if port_env:
start_port = int(port_env)
end_port = start_port + 20
for tryPort in range(startPort, endPort):
if Instance.__is_port_in_use(tryPort):
return Instance(port=tryPort)
for try_port in range(start_port, end_port):
if Instance.__is_port_in_use(try_port):
return Instance(port=try_port)
print('Error: Could not find any ResInsight instances responding between ports ' + str(startPort) + ' and ' + str(endPort))
print('Error: Could not find any ResInsight instances responding between ports ' + str(start_port) + ' and ' + str(end_port))
return None
def __checkVersion(self):
def __check_version(self):
try:
majorVersionOk = self.majorVersion() == int(RiaVersionInfo.RESINSIGHT_MAJOR_VERSION)
minorVersionOk = self.minorVersion() == int(RiaVersionInfo.RESINSIGHT_MINOR_VERSION)
return True, majorVersionOk and minorVersionOk
except grpc.RpcError as e:
major_version_ok = self.major_version() == int(RiaVersionInfo.RESINSIGHT_MAJOR_VERSION)
minor_version_ok = self.minor_version() == int(RiaVersionInfo.RESINSIGHT_MINOR_VERSION)
return True, major_version_ok and minor_version_ok
except:
return False, False
def __init__(self, port = 50051, launched = False):
@ -135,25 +135,25 @@ class Instance:
# Main version check package
self.app = self.app = App_pb2_grpc.AppStub(self.channel)
connectionOk = False
versionOk = False
connection_ok = False
version_ok = False
if self.launched:
for i in range(0, 10):
connectionOk, versionOk = self.__checkVersion()
if connectionOk:
connection_ok, version_ok = self.__check_version()
if connection_ok:
break
time.sleep(1.0)
else:
connectionOk, versionOk = self.__checkVersion()
connection_ok, version_ok = self.__check_version()
if not connectionOk:
if not connection_ok:
if self.launched:
raise Exception('Error: Could not connect to resinsight at ', location, ' after trying 10 times with 1 second apart')
else:
raise Exception('Error: Could not connect to resinsight at ', location)
exit(1)
if not versionOk:
if not version_ok:
raise Exception('Error: Wrong Version of ResInsight at ', location)
# Service packages
@ -161,36 +161,36 @@ class Instance:
self.project = Project(self.channel)
path = os.getcwd()
self.commands.setStartDir(path=path)
self.commands.set_start_dir(path=path)
def __versionMessage(self):
def __version_message(self):
return self.app.GetVersion(Empty())
def majorVersion(self):
def major_version(self):
"""Get an integer with the major version number"""
return self.__versionMessage().major_version
return self.__version_message().major_version
def minorVersion(self):
def minor_version(self):
"""Get an integer with the minor version number"""
return self.__versionMessage().minor_version
return self.__version_message().minor_version
def patchVersion(self):
def patch_version(self):
"""Get an integer with the patch version number"""
return self.__versionMessage().patch_version
return self.__version_message().patch_version
def versionString(self):
def version_string(self):
"""Get a full version string, i.e. 2019.04.01"""
return str(self.majorVersion()) + "." + str(self.minorVersion()) + "." + str(self.patchVersion())
return str(self.major_version()) + "." + str(self.minor_version()) + "." + str(self.patch_version())
def exit(self):
"""Tell ResInsight instance to quit"""
print("Telling ResInsight to Exit")
return self.app.Exit(Empty())
def isConsole(self):
def is_console(self):
"""Returns true if the connected ResInsight instance is a console app"""
return self.app.GetRuntimeInfo(Empty()).app_type == App_pb2.ApplicationTypeEnum.Value('CONSOLE_APPLICATION')
def isGui(self):
def is_gui(self):
"""Returns true if the connected ResInsight instance is a GUI app"""
return self.app.GetRuntimeInfo(Empty()).app_type == App_pb2.ApplicationTypeEnum.Value('GUI_APPLICATION')

View File

@ -9,10 +9,10 @@ import PdmObject_pb2
import PdmObject_pb2_grpc
class PdmObject:
def __init__(self, pb2Object, channel):
self.pb2Object = pb2Object
def __init__(self, pb2_object, channel):
self.pb2_object = pb2_object
self.channel = channel
self.pdmObjectStub = PdmObject_pb2_grpc.PdmObjectServiceStub(self.channel)
self.pdm_object_stub = PdmObject_pb2_grpc.PdmObjectServiceStub(self.channel)
def address(self):
"""Get the unique address of the PdmObject
@ -21,59 +21,59 @@ class PdmObject:
A 64-bit unsigned integer address
"""
return self.pb2Object.address
return self.pb2_object.address
def classKeyword(self):
def class_keyword(self):
"""Get the class keyword in the ResInsight Data Model for the given PdmObject"""
return self.pb2Object.class_keyword
return self.pb2_object.class_keyword
def keywords(self):
"""Get a list of all parameter keywords available in the object"""
listOfKeywords = []
for keyword in self.pb2Object.parameters:
listOfKeywords.append(keyword)
return listOfKeywords
list_of_keywords = []
for keyword in self.pb2_object.parameters:
list_of_keywords.append(keyword)
return list_of_keywords
def printObjectInfo(self):
def print_object_info(self):
"""Print the structure and data content of the PdmObject"""
print ("Class Keyword: " + self.classKeyword())
print ("Class Keyword: " + self.class_keyword())
for keyword in self.keywords():
print(keyword + " [" + type(self.getValue(keyword)).__name__ + "]: " + str(self.getValue(keyword)))
print(keyword + " [" + type(self.get_value(keyword)).__name__ + "]: " + str(self.get_value(keyword)))
def __toValue(self, value):
def __to_value(self, value):
if value.lower() == 'false':
return False
elif value.lower() == 'true':
return True
else:
try:
intVal = int(value)
return intVal
int_val = int(value)
return int_val
except ValueError:
try:
floatVal = float(value)
return floatVal
float_val = float(value)
return float_val
except ValueError:
# We may have a string. Strip internal start and end quotes
value = value.strip('\"')
if self.__islist(value):
return self.__makelist(value)
return value
def __fromValue(self, value):
def __from_value(self, value):
if isinstance(value, bool):
if value:
return "true"
else:
return "false"
elif isinstance(value, list):
listofstrings = []
list_of_strings = []
for val in value:
listofstrings.append(self.__fromValue('\"' + val + '\"'))
return "[" + ", ".join(listofstrings) + "]"
list_of_strings.append(self.__from_value('\"' + val + '\"'))
return "[" + ", ".join(list_of_strings) + "]"
else:
return str(value)
def getValue(self, keyword):
def get_value(self, keyword):
"""Get the value associated with the provided keyword
Arguments:
keyword(str): A string containing the parameter keyword
@ -81,72 +81,72 @@ class PdmObject:
Returns:
The value of the parameter. Can be int, str or list.
"""
value = self.pb2Object.parameters[keyword]
return self.__toValue(value)
value = self.pb2_object.parameters[keyword]
return self.__to_value(value)
def __islist(self, value):
return value.startswith("[") and value.endswith("]")
def __makelist(self, liststring):
liststring = liststring.lstrip("[")
liststring = liststring.rstrip("]")
strings = liststring.split(", ")
def __makelist(self, list_string):
list_string = list_string.lstrip("[")
list_string = list_string.rstrip("]")
strings = list_string.split(", ")
values = []
for string in strings:
values.append(self.__toValue(string))
values.append(self.__to_value(string))
return values
def setValue(self, keyword, value):
def set_value(self, keyword, value):
"""Set the value associated with the provided keyword
Arguments:
keyword(str): A string containing the parameter keyword
value(varying): A value matching the type of the parameter.
See keyword documentation and/or printObjectInfo() to find
See keyword documentation and/or print_object_info() to find
the correct data type.
"""
self.pb2Object.parameters[keyword] = self.__fromValue(value)
self.pb2_object.parameters[keyword] = self.__from_value(value)
def descendants(self, classKeyword):
def descendants(self, class_keyword):
"""Get a list of all project tree descendants matching the class keyword
Arguments:
classKeyword[str]: A class keyword matching the type of class wanted
class_keyword[str]: A class keyword matching the type of class wanted
Returns:
A list of PdmObjects matching the keyword provided
"""
request = PdmObject_pb2.PdmDescendantObjectRequest(object=self.pb2Object, child_keyword=classKeyword)
objectList = self.pdmObjectStub.GetDescendantPdmObjects(request).objects
childList = []
for object in objectList:
childList.append(PdmObject(object, self.channel))
return childList
request = PdmObject_pb2.PdmDescendantObjectRequest(object=self.pb2_object, child_keyword=class_keyword)
object_list = self.pdm_object_stub.GetDescendantPdmObjects(request).objects
child_list = []
for object in object_list:
child_list.append(PdmObject(object, self.channel))
return child_list
def children(self, childField):
"""Get a list of all direct project tree children inside the provided childField
def children(self, child_field):
"""Get a list of all direct project tree children inside the provided child_field
Arguments:
childField[str]: A field name
child_field[str]: A field name
Returns:
A list of PdmObjects inside the childField
A list of PdmObjects inside the child_field
"""
request = PdmObject_pb2.PdmChildObjectRequest(object=self.pb2Object, child_field=childField)
objectList = self.pdmObjectStub.GetChildPdmObjects(request).objects
childList = []
for object in objectList:
childList.append(PdmObject(object, self.channel))
return childList
request = PdmObject_pb2.PdmChildObjectRequest(object=self.pb2_object, child_field=child_field)
object_list = self.pdm_object_stub.GetChildPdmObjects(request).objects
child_list = []
for object in object_list:
child_list.append(PdmObject(object, self.channel))
return child_list
def ancestor(self, classKeyword):
"""Find the first ancestor that matches the provided classKeyword
def ancestor(self, class_keyword):
"""Find the first ancestor that matches the provided class_keyword
Arguments:
classKeyword[str]: A class keyword matching the type of class wanted
class_keyword[str]: A class keyword matching the type of class wanted
"""
request = PdmObject_pb2.PdmParentObjectRequest(object=self.pb2Object, parent_keyword=classKeyword)
return PdmObject(self.pdmObjectStub.GetAncestorPdmObject(request), self.channel)
request = PdmObject_pb2.PdmParentObjectRequest(object=self.pb2_object, parent_keyword=class_keyword)
return PdmObject(self.pdm_object_stub.GetAncestorPdmObject(request), self.channel)
def update(self):
"""Sync all fields from the Python Object to ResInsight"""
self.pdmObjectStub.UpdateExistingPdmObject(self.pb2Object)
self.pdm_object_stub.UpdateExistingPdmObject(self.pb2_object)
# def createChild(self, childField, childClassKeyword):
# childRequest = PdmObject_pb2.CreatePdmChildObjectRequest(object=self.pb2Object, child_field=childField, child_class=childClassKeyword)
# def createChild(self, child_field, childClassKeyword):
# childRequest = PdmObject_pb2.CreatePdmChildObjectRequest(object=self.pb2Object, child_field=child_field, child_class=childClassKeyword)
# return PdmObject(self.pdmObjectStub.CreateChildPdmObject(childRequest), self.channel)

View File

@ -31,23 +31,23 @@ class Project (PdmObject):
path(str): path to project file
"""
Commands(self.channel).openProject(path)
Commands(self.channel).open_project(path)
return self
def close(self):
"""Close the current project (and open new blank project)"""
Commands(self.channel).closeProject()
Commands(self.channel).close_project()
def selectedCases(self):
def selected_cases(self):
"""Get a list of all cases selected in the project tree
Returns:
A list of rips Case objects
"""
caseInfos = self.project.GetSelectedCases(Empty())
case_infos = self.project.GetSelectedCases(Empty())
cases = []
for caseInfo in caseInfos.data:
cases.append(Case(self.channel, caseInfo.id))
for case_info in case_infos.data:
cases.append(Case(self.channel, case_info.id))
return cases
def cases(self):
@ -57,11 +57,11 @@ class Project (PdmObject):
A list of rips Case objects
"""
try:
caseInfos = self.project.GetAllCases(Empty())
case_infos = self.project.GetAllCases(Empty())
cases = []
for caseInfo in caseInfos.data:
cases.append(Case(self.channel, caseInfo.id))
for case_info in case_infos.data:
cases.append(Case(self.channel, case_info.id))
return cases
except grpc.RpcError as e:
if e.code() == grpc.StatusCode.NOT_FOUND:
@ -84,7 +84,7 @@ class Project (PdmObject):
except grpc.RpcError as e:
return None
def loadCase(self, path):
def load_case(self, path):
"""Load a new case from the given file path
Arguments:
@ -92,15 +92,15 @@ class Project (PdmObject):
Returns:
A rips Case object
"""
return Commands(self.channel).loadCase(path)
return Commands(self.channel).load_case(path)
def views(self):
"""Get a list of views belonging to a project"""
pdmObjects = self.descendants("ReservoirView")
viewList = []
for pdmObject in pdmObjects:
viewList.append(View(pdmObject))
return viewList
pdm_objects = self.descendants("ReservoirView")
view_list = []
for pdm_object in pdm_objects:
view_list.append(View(pdm_object))
return view_list
def view(self, id):
"""Get a particular view belonging to a case by providing view id
@ -111,39 +111,39 @@ class Project (PdmObject):
"""
views = self.views()
for viewObject in views:
if viewObject.id == id:
return viewObject
for view_object in views:
if view_object.id == id:
return view_object
return None
def gridCaseGroups(self):
def grid_case_groups(self):
"""Get a list of all grid case groups in the project"""
caseGroups = self.descendants("RimIdenticalGridCaseGroup");
case_groups = self.descendants("RimIdenticalGridCaseGroup")
caseGroupList = []
for pb2Group in caseGroups:
caseGroupList.append(GridCaseGroup(pb2Group))
return caseGroupList
case_group_list = []
for pdm_group in case_groups:
case_group_list.append(GridCaseGroup(pdm_group))
return case_group_list
def gridCaseGroup(self, groupId):
def grid_case_group(self, group_id):
"""Get a particular grid case group belonging to a project
Arguments:
groupId(int): group id
Returns: a grid case group object
"""
caseGroups = self.gridCaseGroups()
for caseGroup in caseGroups:
if caseGroup.groupId == groupId:
return caseGroup
case_groups = self.grid_case_groups()
for case_group in case_groups:
if case_group.groupId == group_id:
return case_group
return None
def createGridCaseGroup(self, casePaths):
def create_grid_case_group(self, case_paths):
"""Create a new grid case group from the provided case paths
Arguments:
casePaths(list): a list of paths to the cases to be loaded and included in the group
Returns:
A new grid case group object
"""
groupId, groupName = Commands(self.channel).createGridCaseGroup(casePaths)
return self.gridCaseGroup(groupId)
group_id, group_name = Commands(self.channel).create_grid_case_group(case_paths)
return self.grid_case_group(group_id)

View File

@ -26,11 +26,11 @@ class Properties:
case(Case): A rips case to handle properties for
"""
self.case = case
self.propertiesStub = Properties_pb2_grpc.PropertiesStub(self.case.channel)
self.chunkSize = 8160
self._properties_stub = Properties_pb2_grpc.PropertiesStub(self.case.channel)
self.chunk_size = 8160
def __generatePropertyInputIterator(self, values_iterator, parameters):
def __generate_property_input_iterator(self, values_iterator, parameters):
chunk = Properties_pb2.PropertyInputChunk()
chunk.params.CopyFrom(parameters)
yield chunk
@ -40,7 +40,7 @@ class Properties:
chunk.values.CopyFrom(valmsg)
yield chunk
def __generatePropertyInputChunks(self, array, parameters):
def __generate_property_input_chunks(self, array, parameters):
index = -1
while index < len(array):
@ -49,20 +49,20 @@ class Properties:
chunk.params.CopyFrom(parameters)
index += 1
else:
actualChunkSize = min(len(array) - index + 1, self.chunkSize)
chunk.values.CopyFrom(Properties_pb2.PropertyChunk(values = array[index:index+actualChunkSize]))
index += actualChunkSize
actual_chunk_size = min(len(array) - index + 1, self.chunk_size)
chunk.values.CopyFrom(Properties_pb2.PropertyChunk(values = array[index:index+actual_chunk_size]))
index += actual_chunk_size
yield chunk
# Final empty message to signal completion
chunk = Properties_pb2.PropertyInputChunk()
yield chunk
def available(self, propertyType, porosityModel = 'MATRIX_MODEL'):
def available(self, property_type, porosity_model = 'MATRIX_MODEL'):
"""Get a list of available properties
Arguments:
propertyType (str): string corresponding to propertyType enum. Can be one of the following:
property_type (str): string corresponding to property_type enum. Can be one of the following:
- DYNAMIC_NATIVE
- STATIC_NATIVE
- SOURSIMRL
@ -72,168 +72,168 @@ class Properties:
- FLOW_DIAGNOSTICS
- INJECTION_FLOODING
porosityModel(str): 'MATRIX_MODEL' or 'FRACTURE_MODEL'.
porosity_model(str): 'MATRIX_MODEL' or 'FRACTURE_MODEL'.
"""
propertyTypeEnum = Properties_pb2.PropertyType.Value(propertyType)
porosityModelEnum = Case_pb2.PorosityModelType.Value(porosityModel)
property_type_enum = Properties_pb2.PropertyType.Value(property_type)
porosity_model_enum = Case_pb2.PorosityModelType.Value(porosity_model)
request = Properties_pb2.AvailablePropertiesRequest (case_request = Case_pb2.CaseRequest(id=self.case.id),
property_type = propertyTypeEnum,
porosity_model = porosityModelEnum)
return self.propertiesStub.GetAvailableProperties(request).property_names
property_type = property_type_enum,
porosity_model = porosity_model_enum)
return self._properties_stub.GetAvailableProperties(request).property_names
def activeCellPropertyAsync(self, propertyType, propertyName, timeStep, porosityModel = 'MATRIX_MODEL'):
def active_cell_property_async(self, property_type, property_name, time_step, porosity_model = 'MATRIX_MODEL'):
"""Get a cell property for all active cells. Async, so returns an iterator
Arguments:
propertyType(str): string enum. See available()
propertyName(str): name of an Eclipse property
timeStep(int): the time step for which to get the property for
porosityModel(str): string enum. See available()
property_type(str): string enum. See available()
property_name(str): name of an Eclipse property
time_step(int): the time step for which to get the property for
porosity_model(str): string enum. See available()
Returns:
An iterator to a chunk object containing an array of double values
You first loop through the chunks and then the values within the chunk to get all values.
"""
propertyTypeEnum = Properties_pb2.PropertyType.Value(propertyType)
porosityModelEnum = Case_pb2.PorosityModelType.Value(porosityModel)
property_type_enum = Properties_pb2.PropertyType.Value(property_type)
porosity_model_enum = Case_pb2.PorosityModelType.Value(porosity_model)
request = Properties_pb2.PropertyRequest(case_request = Case_pb2.CaseRequest(id=self.case.id),
property_type = propertyTypeEnum,
property_name = propertyName,
time_step = timeStep,
porosity_model = porosityModelEnum)
for chunk in self.propertiesStub.GetActiveCellProperty(request):
property_type = property_type_enum,
property_name = property_name,
time_step = time_step,
porosity_model = porosity_model_enum)
for chunk in self._properties_stub.GetActiveCellProperty(request):
yield chunk
def activeCellProperty(self, propertyType, propertyName, timeStep, porosityModel = 'MATRIX_MODEL'):
def active_cell_property(self, property_type, property_name, time_step, porosity_model = 'MATRIX_MODEL'):
"""Get a cell property for all active cells. Sync, so returns a list
Arguments:
propertyType(str): string enum. See available()
propertyName(str): name of an Eclipse property
timeStep(int): the time step for which to get the property for
porosityModel(str): string enum. See available()
property_type(str): string enum. See available()
property_name(str): name of an Eclipse property
time_step(int): the time step for which to get the property for
porosity_model(str): string enum. See available()
Returns:
A list containing double values
You first loop through the chunks and then the values within the chunk to get all values.
"""
allValues = []
generator = self.activeCellPropertyAsync(propertyType, propertyName, timeStep, porosityModel)
all_values = []
generator = self.active_cell_property_async(property_type, property_name, time_step, porosity_model)
for chunk in generator:
for value in chunk.values:
allValues.append(value)
return allValues
all_values.append(value)
return all_values
def gridPropertyAsync(self, propertyType, propertyName, timeStep, gridIndex = 0, porosityModel = 'MATRIX_MODEL'):
def grid_property_async(self, property_type, property_name, time_step, gridIndex = 0, porosity_model = 'MATRIX_MODEL'):
"""Get a cell property for all grid cells. Async, so returns an iterator
Arguments:
propertyType(str): string enum. See available()
propertyName(str): name of an Eclipse property
timeStep(int): the time step for which to get the property for
property_type(str): string enum. See available()
property_name(str): name of an Eclipse property
time_step(int): the time step for which to get the property for
gridIndex(int): index to the grid we're getting values for
porosityModel(str): string enum. See available()
porosity_model(str): string enum. See available()
Returns:
An iterator to a chunk object containing an array of double values
You first loop through the chunks and then the values within the chunk to get all values.
"""
propertyTypeEnum = Properties_pb2.PropertyType.Value(propertyType)
porosityModelEnum = Case_pb2.PorosityModelType.Value(porosityModel)
property_type_enum = Properties_pb2.PropertyType.Value(property_type)
porosity_model_enum = Case_pb2.PorosityModelType.Value(porosity_model)
request = Properties_pb2.PropertyRequest(case_request = self.case.request,
property_type = propertyTypeEnum,
property_name = propertyName,
time_step = timeStep,
property_type = property_type_enum,
property_name = property_name,
time_step = time_step,
grid_index = gridIndex,
porosity_model = porosityModelEnum)
for chunk in self.propertiesStub.GetGridProperty(request):
porosity_model = porosity_model_enum)
for chunk in self._properties_stub.GetGridProperty(request):
yield chunk
def gridProperty(self, propertyType, propertyName, timeStep, gridIndex = 0, porosityModel = 'MATRIX_MODEL'):
def grid_property(self, property_type, property_name, time_step, grid_index = 0, porosity_model = 'MATRIX_MODEL'):
"""Get a cell property for all grid cells. Synchronous, so returns a list
Arguments:
propertyType(str): string enum. See available()
propertyName(str): name of an Eclipse property
timeStep(int): the time step for which to get the property for
gridIndex(int): index to the grid we're getting values for
porosityModel(str): string enum. See available()
property_type(str): string enum. See available()
property_name(str): name of an Eclipse property
time_step(int): the time step for which to get the property for
grid_index(int): index to the grid we're getting values for
porosity_model(str): string enum. See available()
Returns:
A list of double values
"""
allValues = []
generator = self.gridPropertyAsync(propertyType, propertyName, timeStep, gridIndex, porosityModel)
all_values = []
generator = self.grid_property_async(property_type, property_name, time_step, grid_index, porosity_model)
for chunk in generator:
for value in chunk.values:
allValues.append(value)
return allValues
all_values.append(value)
return all_values
def setActiveCellPropertyAsync(self, values_iterator, propertyType, propertyName, timeStep, porosityModel = 'MATRIX_MODEL'):
def set_active_cell_property_async(self, values_iterator, property_type, property_name, time_step, porosity_model = 'MATRIX_MODEL'):
"""Set a cell property for all active cells. Async, and so takes an iterator to the input values
Arguments:
values_iterator(iterator): an iterator to the properties to be set
propertyType(str): string enum. See available()
propertyName(str): name of an Eclipse property
timeStep(int): the time step for which to get the property for
porosityModel(str): string enum. See available()
property_type(str): string enum. See available()
property_name(str): name of an Eclipse property
time_step(int): the time step for which to get the property for
porosity_model(str): string enum. See available()
"""
propertyTypeEnum = Properties_pb2.PropertyType.Value(propertyType)
porosityModelEnum = Case_pb2.PorosityModelType.Value(porosityModel)
property_type_enum = Properties_pb2.PropertyType.Value(property_type)
porosity_model_enum = Case_pb2.PorosityModelType.Value(porosity_model)
request = Properties_pb2.PropertyRequest(case_request = self.case.request,
property_type = propertyTypeEnum,
property_name = propertyName,
time_step = timeStep,
porosity_model = porosityModelEnum)
property_type = property_type_enum,
property_name = property_name,
time_step = time_step,
porosity_model = porosity_model_enum)
request_iterator = self.__generatePropertyInputIterator(values_iterator, request)
self.propertiesStub.SetActiveCellProperty(request_iterator)
request_iterator = self.__generate_property_input_iterator(values_iterator, request)
self._properties_stub.SetActiveCellProperty(request_iterator)
def setActiveCellProperty(self, values, propertyType, propertyName, timeStep, porosityModel = 'MATRIX_MODEL'):
def set_active_cell_property(self, values, property_type, property_name, time_step, porosity_model = 'MATRIX_MODEL'):
"""Set a cell property for all active cells.
Arguments:
values(list): a list of double precision floating point numbers
propertyType(str): string enum. See available()
propertyName(str): name of an Eclipse property
timeStep(int): the time step for which to get the property for
porosityModel(str): string enum. See available()
property_type(str): string enum. See available()
property_name(str): name of an Eclipse property
time_step(int): the time step for which to get the property for
porosity_model(str): string enum. See available()
"""
propertyTypeEnum = Properties_pb2.PropertyType.Value(propertyType)
porosityModelEnum = Case_pb2.PorosityModelType.Value(porosityModel)
property_type_enum = Properties_pb2.PropertyType.Value(property_type)
porosity_model_enum = Case_pb2.PorosityModelType.Value(porosity_model)
request = Properties_pb2.PropertyRequest(case_request = self.case.request,
property_type = propertyTypeEnum,
property_name = propertyName,
time_step = timeStep,
porosity_model = porosityModelEnum)
request_iterator = self.__generatePropertyInputChunks(values, request)
reply = self.propertiesStub.SetActiveCellProperty(request_iterator)
property_type = property_type_enum,
property_name = property_name,
time_step = time_step,
porosity_model = porosity_model_enum)
request_iterator = self.__generate_property_input_chunks(values, request)
reply = self._properties_stub.SetActiveCellProperty(request_iterator)
if reply.accepted_value_count < len(values):
raise IndexError
def setGridProperty(self, values, propertyType, propertyName, timeStep, gridIndex = 0, porosityModel = 'MATRIX_MODEL'):
def set_grid_property(self, values, property_type, property_name, time_step, grid_index = 0, porosity_model = 'MATRIX_MODEL'):
"""Set a cell property for all grid cells.
Arguments:
values(list): a list of double precision floating point numbers
propertyType(str): string enum. See available()
propertyName(str): name of an Eclipse property
timeStep(int): the time step for which to get the property for
gridIndex(int): index to the grid we're setting values for
porosityModel(str): string enum. See available()
property_type(str): string enum. See available()
property_name(str): name of an Eclipse property
time_step(int): the time step for which to get the property for
grid_index(int): index to the grid we're setting values for
porosity_model(str): string enum. See available()
"""
propertyTypeEnum = Properties_pb2.PropertyType.Value(propertyType)
porosityModelEnum = Case_pb2.PorosityModelType.Value(porosityModel)
property_type_enum = Properties_pb2.PropertyType.Value(property_type)
porosity_model_enum = Case_pb2.PorosityModelType.Value(porosity_model)
request = Properties_pb2.PropertyRequest(case_request = self.case.request,
property_type = propertyTypeEnum,
property_name = propertyName,
time_step = timeStep,
grid_index = gridIndex,
porosity_model = porosityModelEnum)
request_iterator = self.__generatePropertyInputChunks(values, request)
reply = self.propertiesStub.SetGridProperty(request_iterator)
property_type = property_type_enum,
property_name = property_name,
time_step = time_step,
grid_index = grid_index,
porosity_model = porosity_model_enum)
request_iterator = self.__generate_property_input_chunks(values, request)
reply = self._properties_stub.SetGridProperty(request_iterator)
if reply.accepted_value_count < len(values):
raise IndexError

View File

@ -7,17 +7,17 @@
import rips
# Connect to ResInsight
resInsight = rips.Instance.find()
if resInsight is not None:
resinsight = rips.Instance.find()
if resinsight is not None:
# Get a list of all cases
cases = resInsight.project.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.gridPath())
print("Case grid path: " + case.grid_path())
timesteps = case.timeSteps()
timesteps = case.time_steps()
for t in timesteps:
print("Year: " + str(t.year))
print("Month: " + str(t.month))

View File

@ -1,6 +1,6 @@
import rips
resInsight = rips.Instance.find()
if resInsight is not None:
print(resInsight.versionString())
print("Is this a console run?", resInsight.isConsole())
resinsight = rips.Instance.find()
if resinsight is not None:
print(resinsight.version_string())
print("Is this a console run?", resinsight.is_console())

View File

@ -1,29 +1,29 @@
import os
import rips
resInsight = rips.Instance.find()
resinsight = rips.Instance.find()
casePaths = []
casePaths.append("C:/Users/lindk/source/repos/ResInsight/TestModels/Case_with_10_timesteps/Real0/BRUGGE_0000.EGRID")
casePaths.append("C:/Users/lindk/source/repos/ResInsight/TestModels/Case_with_10_timesteps/Real10/BRUGGE_0010.EGRID")
for casePath in casePaths:
case_paths = []
case_paths.append("C:/Users/lindk/source/repos/ResInsight/TestModels/Case_with_10_timesteps/Real0/BRUGGE_0000.EGRID")
case_paths.append("C:/Users/lindk/source/repos/ResInsight/TestModels/Case_with_10_timesteps/Real10/BRUGGE_0010.EGRID")
for casePath in case_paths:
assert os.path.exists(casePath), "You need to set valid case paths for this script to work"
caseGroup = resInsight.project.createGridCaseGroup(casePaths=casePaths)
case_group = resinsight.project.create_grid_case_group(case_paths=case_paths)
caseGroup.printObjectInfo()
case_group.print_object_info()
#statCases = caseGroup.statisticsCases()
#caseIds = []
#for statCase in statCases:
# statCase.setValue("DynamicPropertiesToCalculate", ["SWAT"])
# statCase.update()
# caseIds.append(statCase.getValue("CaseId"))
#stat_cases = caseGroup.statistics_cases()
#case_ids = []
#for stat_case in stat_cases:
# stat_case.set_value("DynamicPropertiesToCalculate", ["SWAT"])
# stat_case.update()
# case_ids.append(stat_case.get_value("CaseId"))
resInsight.commands.computeCaseGroupStatistics(caseGroupId=caseGroup.groupId)
resinsight.commands.compute_case_group_statistics(case_group_id=case_group.group_id)
view = caseGroup.views()[0]
cellResult = view.cellResult()
cellResult.setValue("ResultVariable", "PRESSURE_DEV")
cellResult.update()
view = case_group.views()[0]
cell_result = view.set_cell_result()
cell_result.set_value("ResultVariable", "PRESSURE_DEV")
cell_result.update()

View File

@ -6,22 +6,22 @@
import rips
# Connect to ResInsight
resInsight = rips.Instance.find()
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)
case = resinsight.project.case(id = 0)
# Get the cell count object
cellCounts = case.cellCount()
print("Number of active cells: " + str(cellCounts.active_cell_count))
print("Total number of reservoir cells: " + str(cellCounts.reservoir_cell_count))
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
activeCellInfos = case.cellInfoForActiveCells()
active_cell_infos = case.cell_info_for_active_cells()
# A simple check on the size of the cell info
assert(cellCounts.active_cell_count == len(activeCellInfos))
assert(cell_counts.active_cell_count == len(active_cell_infos))
# Print information for the first active cell
print("First active cell: ")
print(activeCellInfos[0])
print(active_cell_infos[0])

View File

@ -8,11 +8,11 @@ import tempfile
import rips
# Load instance
resInsight = rips.Instance.find()
resinsight = rips.Instance.find()
# Run a couple of commands
resInsight.commands.setTimeStep(caseId=0, timeStep=3)
resInsight.commands.setMainWindowSize(width=800, height=500)
resinsight.commands.set_time_step(case_id=0, time_step=3)
resinsight.commands.set_main_window_size(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
@ -20,23 +20,23 @@ with tempfile.TemporaryDirectory(prefix="rips") as tmpdirname:
print("Temporary folder: ", tmpdirname)
# Set export folder for snapshots and properties
resInsight.commands.setExportFolder(type='SNAPSHOTS', path=tmpdirname)
resInsight.commands.setExportFolder(type='PROPERTIES', path=tmpdirname)
resinsight.commands.set_export_folder(type='SNAPSHOTS', path=tmpdirname)
resinsight.commands.set_export_folder(type='PROPERTIES', path=tmpdirname)
# Export snapshots
resInsight.commands.exportSnapshots()
resinsight.commands.export_snapshots()
# Print contents of temporary folder
print(os.listdir(tmpdirname))
assert(len(os.listdir(tmpdirname)) > 0)
case = resInsight.project.case(id=0)
case = resinsight.project.case(id=0)
# Export properties in the view
resInsight.commands.exportPropertyInViews(0, "3D View", 0)
resinsight.commands.export_property_in_views(0, "3D View", 0)
# Check that the exported file exists
expectedFileName = case.name + "-" + str("3D_View") + "-" + "T3" + "-SOIL"
fullPath = tmpdirname + "/" + expectedFileName
assert(os.path.exists(fullPath))
expected_file_name = case.name + "-" + str("3D_View") + "-" + "T3" + "-SOIL"
full_path = tmpdirname + "/" + expected_file_name
assert(os.path.exists(full_path))

View File

@ -6,24 +6,24 @@
import rips
import grpc
resInsight = rips.Instance.find()
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("Nonsense")
case = resinsight.project.load_case("Nonsense")
except grpc.RpcError as e:
print("Expected Server Exception Received: ", e)
case = resInsight.project.case(id=0)
case = resinsight.project.case(id=0)
if case is not None:
results = case.properties.activeCellProperty('STATIC_NATIVE', 'PORO', 0)
activeCellCount = len(results)
results = case.properties.active_cell_property('STATIC_NATIVE', 'PORO', 0)
active_cell_count = len(results)
# Send the results back to ResInsight inside try / except construct
try:
case.properties.setActiveCellProperty(results, 'GENERATED', 'POROAPPENDED', 0)
case.properties.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!")
@ -33,7 +33,7 @@ if case is not None:
# This time we should get a grpc.RpcError exception, which is a server side error.
try:
case.properties.setActiveCellProperty(results, 'GENERATED', 'POROAPPENDED', 0)
case.properties.set_active_cell_property(results, 'GENERATED', 'POROAPPENDED', 0)
print("Everything went well??")
except grpc.RpcError as e:
print("Expected Server Exception Received: ", e)
@ -43,10 +43,10 @@ if case is not None:
# 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
case.properties.chunk_size = active_cell_count
try:
case.properties.setActiveCellProperty(results, 'GENERATED', 'POROAPPENDED', 0)
case.properties.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")

View File

@ -6,38 +6,38 @@ import os
import rips
# Load instance
resInsight = rips.Instance.find()
cases = resInsight.project.cases()
resinsight = rips.Instance.find()
cases = resinsight.project.cases()
# Set main window size
resInsight.commands.setMainWindowSize(width=800, height=500)
resinsight.commands.set_main_window_size(width=800, height=500)
n = 5 # every n-th timestep for snapshot
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:
# Get grid path and its folder name
casepath = case.gridPath()
foldername = os.path.dirname(casepath)
case_path = case.grid_path()
folder_name = os.path.dirname(case_path)
# create a folder to hold the snapshots
dirname = os.path.join(foldername, 'snapshots')
dirname = os.path.join(folder_name, 'snapshots')
if os.path.exists(dirname) is False:
os.mkdir(dirname)
print ("Exporting to folder: " + dirname)
resInsight.commands.setExportFolder(type='SNAPSHOTS', path=dirname)
resinsight.commands.set_export_folder(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)))
time_steps = case.time_steps()
tss_snapshot = range(0, len(time_steps), n)
print(case.name, case.id, 'Number of time_steps: ' + str(len(time_steps)))
print('Number of time_steps for snapshoting: ' + str(len(tss_snapshot)))
view = case.views()[0]
for property in property_list:
view.applyCellResult(resultType='DYNAMIC_NATIVE', resultVariable=property)
view.apply_cell_result(result_type='DYNAMIC_NATIVE', result_variable=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'
resinsight.commands.set_time_step(case_id = case.id, time_step = ts_snapshot)
resinsight.commands.export_snapshots(type='VIEWS', case_id=case.id) # ALL, VIEWS or PLOTS default is 'ALL'

View File

@ -4,9 +4,9 @@
import rips
resInsight = rips.Instance.find()
resinsight = rips.Instance.find()
cases = resInsight.project.cases()
cases = resinsight.project.cases()
print("Number of cases found: ", len(cases))
for case in cases:
print(case.name)

View File

@ -7,9 +7,9 @@ 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):
def create_result(poro_chunks, permx_chunks):
# Loop through all the chunks of poro and permx in order
for (poroChunk, permxChunk) in zip(poroChunks, permxChunks):
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):
@ -17,22 +17,22 @@ def createResult(poroChunks, permxChunks):
# Return a generator object that behaves like a Python iterator
yield resultChunk
resInsight = rips.Instance.find()
resinsight = rips.Instance.find()
start = time.time()
case = resInsight.project.case(id=0)
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)
poro_chunks = case.properties.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
permxChunks = case.properties.activeCellPropertyAsync('STATIC_NATIVE', 'PERMX', 0)
permx_chunks = case.properties.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.properties.setActiveCellPropertyAsync(createResult(poroChunks, permxChunks),
case.properties.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].applyCellResult('GENERATED', 'POROPERMXAS')
view = case.views()[0].apply_cell_result('GENERATED', 'POROPERMXAS')

View File

@ -7,23 +7,23 @@ import rips
import time
import grpc
resInsight = rips.Instance.find()
resinsight = rips.Instance.find()
start = time.time()
case = resInsight.project.case(id=0)
case = resinsight.project.case(id=0)
# Read poro result into list
poroResults = case.properties.activeCellProperty('STATIC_NATIVE', 'PORO', 0)
poro_results = case.properties.active_cell_property('STATIC_NATIVE', 'PORO', 0)
# Read permx result into list
permxResults = case.properties.activeCellProperty('STATIC_NATIVE', 'PERMX', 0)
permx_results = case.properties.active_cell_property('STATIC_NATIVE', 'PERMX', 0)
# Generate output result
results = []
for (poro, permx) in zip(poroResults, permxResults):
for (poro, permx) in zip(poro_results, permx_results):
results.append(poro * permx)
try:
# Send back output result
case.properties.setActiveCellProperty(results, 'GENERATED', 'POROPERMXSY', 0)
case.properties.set_active_cell_property(results, 'GENERATED', 'POROPERMXSY', 0)
except grpc.RpcError as e:
print("Exception Received: ", e)
@ -32,4 +32,4 @@ end = time.time()
print("Time elapsed: ", end - start)
print("Transferred all results back")
view = case.views()[0].applyCellResult('GENERATED', 'POROPERMXSY')
view = case.views()[0].apply_cell_result('GENERATED', 'POROPERMXSY')

View File

@ -3,9 +3,9 @@
#######################################
import rips
resInsight = rips.Instance.find()
resinsight = rips.Instance.find()
if resInsight is None:
if resinsight is None:
print('ERROR: could not find ResInsight')
else:
print('Successfully connected to ResInsight')

View File

@ -1,11 +1,11 @@
# 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])
resinsight = rips.Instance.launch(command_line_parameters=['--last', '--size', 600, 1000])
# Get a list of all cases
cases = resInsight.project.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.gridPath())
print("Case grid path: " + case.grid_path())

View File

@ -7,9 +7,9 @@
import rips
resInsight = rips.Instance.find()
if resInsight is not None:
cases = resInsight.project.selectedCases()
resinsight = rips.Instance.find()
if resinsight is not None:
cases = resinsight.project.selected_cases()
print ("Got " + str(len(cases)) + " cases: ")
for case in cases:

View File

@ -3,7 +3,7 @@
######################################################################
import rips
resInsight = rips.Instance.find()
resinsight = rips.Instance.find()
view = resInsight.project.view(0)
view.applyCellResult(resultType='STATIC_NATIVE', resultVariable='DX')
view = resinsight.project.view(0)
view.apply_cell_result(resultType='STATIC_NATIVE', resultVariable='DX')

View File

@ -5,14 +5,14 @@
# Load ResInsight Processing Server Client Library
import rips
# Connect to ResInsight instance
resInsight = rips.Instance.find()
resinsight = rips.Instance.find()
view = resInsight.project.view(0)
#view.applyFlowDiagnosticsCellResult(resultVariable='Fraction',
# selectionMode='FLOW_TR_INJ_AND_PROD')
view = resinsight.project.view(0)
#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.applyFlowDiagnosticsCellResult(resultVariable='Fraction',
selectionMode='FLOW_TR_BY_SELECTION',
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'])

View File

@ -3,15 +3,15 @@
######################################################################
import rips
resInsight = rips.Instance.find()
resinsight = rips.Instance.find()
case = resInsight.project.case(id=0)
totalCellCount = case.cellCount().reservoir_cell_count
case = resinsight.project.case(id=0)
total_cell_count = case.cell_count().reservoir_cell_count
values = []
for i in range(0, totalCellCount):
for i in range(0, total_cell_count):
values.append(i % 2 * 0.75);
print("Applying values to full grid")
case.properties.setGridProperty(values, 'DYNAMIC_NATIVE', 'SOIL', 0)
case.properties.set_grid_property(values, 'DYNAMIC_NATIVE', 'SOIL', 0)

View File

@ -6,27 +6,27 @@ import rips
import itertools
import time
resInsight = rips.Instance.find()
resinsight = rips.Instance.find()
start = time.time()
# Get the case with case id 0
case = resInsight.project.case(id=0)
case = resinsight.project.case(id=0)
# Get a list of all time steps
timeSteps = case.timeSteps()
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
resultChunks = case.properties.activeCellPropertyAsync('DYNAMIC_NATIVE', 'SOIL', i)
result_chunks = case.properties.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 resultChunks:
for chunk in result_chunks:
mysum += sum(chunk.values)
count += len(chunk.values)

View File

@ -5,21 +5,21 @@ import rips
import itertools
import time
resInsight = rips.Instance.find()
resinsight = rips.Instance.find()
start = time.time()
case = resInsight.project.case(id=0)
case = resinsight.project.case(id=0)
# Get the case with case id 0
case = resInsight.project.case(id=0)
case = resinsight.project.case(id=0)
# Get a list of all time steps
timeSteps = case.timeSteps()
time_steps = case.time_steps()
averages = []
for i in range(0, len(timeSteps)):
for i in range(0, len(time_steps)):
# Get a list of all the results for time step i
results = case.properties.activeCellProperty('DYNAMIC_NATIVE', 'SOIL', i)
results = case.properties.active_cell_property('DYNAMIC_NATIVE', 'SOIL', i)
mysum = sum(results)
averages.append(mysum/len(results))

View File

@ -7,41 +7,41 @@ 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):
def create_result(soil_chunks, porv_chunks):
for (soil_chunk, porv_chunk) in zip(soil_chunks, porv_chunks):
resultChunk = []
number = 0
for (soilValue, porvValue) in zip(soilChunk.values, porvChunk.values):
resultChunk.append(soilValue * porvValue)
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()
resinsight = rips.Instance.find()
start = time.time()
case = resInsight.project.case(id=0)
timeStepInfo = case.timeSteps()
case = resinsight.project.case(id=0)
timeStepInfo = case.time_steps()
# 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)
porv_chunks = case.properties.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
porvArray = []
for porvChunk in porvChunks:
porvArray.append(porvChunk)
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
soilChunks = case.properties.activeCellPropertyAsync('DYNAMIC_NATIVE', 'SOIL', i)
soil_chunks = case.properties.active_cell_property_async('DYNAMIC_NATIVE', 'SOIL', i)
# Create the generator object for the SOIL * PORV derived result
result_generator = createResult(soilChunks, iter(porvArray))
result_generator = create_result(soil_chunks, iter(porv_array))
# Send back the result asynchronously with a generator object
case.properties.setActiveCellPropertyAsync(result_generator, 'GENERATED', 'SOILPORVAsync', i)
case.properties.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].applyCellResult('GENERATED', 'SOILPORVAsync')
view = case.views()[0].apply_cell_result('GENERATED', 'SOILPORVAsync')

View File

@ -5,29 +5,29 @@
import rips
import time
resInsight = rips.Instance.find()
resinsight = rips.Instance.find()
start = time.time()
case = resInsight.project.case(id=0)
case = resinsight.project.case(id=0)
# Read the full porv result
porvResults = case.properties.activeCellProperty('STATIC_NATIVE', 'PORV', 0)
timeStepInfo = case.timeSteps()
porv_results = case.properties.active_cell_property('STATIC_NATIVE', 'PORV', 0)
time_step_info = case.time_steps()
for i in range (0, len(timeStepInfo)):
for i in range (0, len(time_step_info)):
# Read the full SOIl result for time step i
soilResults = case.properties.activeCellProperty('DYNAMIC_NATIVE', 'SOIL', i)
soil_results = case.properties.active_cell_property('DYNAMIC_NATIVE', 'SOIL', i)
# Generate the result by looping through both lists in order
results = []
for (soil, porv) in zip(soilResults, porvResults):
for (soil, porv) in zip(soil_results, porv_results):
results.append(soil * porv)
# Send back result
case.properties.setActiveCellProperty(results, 'GENERATED', 'SOILPORVSync', i)
case.properties.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].applyCellResult('GENERATED', 'SOILPORVSync')
view = case.views()[0].apply_cell_result('GENERATED', 'SOILPORVSync')

View File

@ -5,23 +5,23 @@
#############################################################
import rips
# Connect to ResInsight instance
resInsight = rips.Instance.find()
resinsight = rips.Instance.find()
# Check if connection worked
if resInsight is not None:
if resinsight is not None:
# Get a list of all cases
cases = resInsight.project.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("#3388AA")
view.set_show_grid_box(not view.show_grid_box())
view.set_background_color("#3388AA")
# Update the view in ResInsight
view.update()
# Clone the first view
newView = views[0].clone()
view.setShowGridBox(False)
newView.setBackgroundColor("#FFAA33")
newView.update()
new_view = views[0].clone()
view.set_show_grid_box(False)
new_view.set_background_color("#FFAA33")
new_view.update()

View File

@ -9,36 +9,36 @@ class View (PdmObject):
id(int): View Id corresponding to the View Id in ResInsight project.
"""
def __init__(self, pbmObject):
self.id = pbmObject.getValue("ViewId")
def __init__(self, pdm_object):
self.id = pdm_object.get_value("ViewId")
PdmObject.__init__(self, pbmObject.pb2Object, pbmObject.channel)
PdmObject.__init__(self, pdm_object.pb2_object, pdm_object.channel)
def showGridBox(self):
def show_grid_box(self):
"""Check if the grid box is meant to be shown in the view"""
return self.getValue("ShowGridBox")
return self.get_value("ShowGridBox")
def setShowGridBox(self, value):
def set_show_grid_box(self, value):
"""Set if the grid box is meant to be shown in the view"""
self.setValue("ShowGridBox", value)
self.set_value("ShowGridBox", value)
def backgroundColor(self):
def background_color(self):
"""Get the current background color in the view"""
return self.getValue("ViewBackgroundColor")
return self.get_value("ViewBackgroundColor")
def setBackgroundColor(self, bgColor):
def set_background_color(self, bgcolor):
"""Set the background color in the view"""
self.setValue("ViewBackgroundColor", bgColor)
self.set_value("ViewBackgroundColor", bgcolor)
def cellResult(self):
def set_cell_result(self):
"""Retrieve the current cell results"""
return self.children("GridCellResult")[0]
def applyCellResult(self, resultType, resultVariable):
def apply_cell_result(self, result_type, result_variable):
"""Apply a regular cell result
Arguments:
resultType (str): String representing the result category. The valid values are
result_type (str): String representing the result category. The valid values are
- DYNAMIC_NATIVE
- STATIC_NATIVE
- SOURSIMRL
@ -47,54 +47,54 @@ class View (PdmObject):
- FORMATION_NAMES
- FLOW_DIAGNOSTICS
- INJECTION_FLOODING
resultVariable (str): String representing the result variable.
result_variable (str): String representing the result variable.
"""
cellResult = self.cellResult()
cellResult.setValue("ResultType", resultType)
cellResult.setValue("ResultVariable", resultVariable)
cellResult.update()
cell_result = self.set_cell_result()
cell_result.set_value("ResultType", result_type)
cell_result.set_value("ResultVariable", result_variable)
cell_result.update()
def applyFlowDiagnosticsCellResult(self,
resultVariable = 'TOF',
selectionMode = 'FLOW_TR_BY_SELECTION',
def apply_flow_diagnostics_cell_result(self,
result_variable = 'TOF',
selection_mode = 'FLOW_TR_BY_SELECTION',
injectors = [],
producers = []):
"""Apply a flow diagnostics cell result
Arguments:
resultVariable (str): String representing the result value
result_variable (str): String representing the result value
The valid values are 'TOF', 'Fraction', 'MaxFractionTracer' and 'Communication'.
selectionMode (str): String specifying which tracers to select.
selection_mode (str): String specifying which tracers to select.
The valid values are
- FLOW_TR_INJ_AND_PROD (all injector and producer tracers),
- FLOW_TR_PRODUCERS (all producers)
- FLOW_TR_INJECTORS (all injectors),
- FLOW_TR_BY_SELECTION (specify individual tracers in the
injectorTracers and producerTracers variables)
injectorTracers (list): List of injector names (strings) to select.
Requires selectionMode to be 'FLOW_TR_BY_SELECTION'.
producerTracers (list): List of producer tracers (strings) to select.
Requires selectionMode to be 'FLOW_TR_BY_SELECTION'.
injectors and producers variables)
injectors (list): List of injector names (strings) to select.
Requires selection_mode to be 'FLOW_TR_BY_SELECTION'.
producers (list): List of producer tracers (strings) to select.
Requires selection_mode to be 'FLOW_TR_BY_SELECTION'.
"""
cellResult = self.cellResult()
cellResult.setValue("ResultType", "FLOW_DIAGNOSTICS")
cellResult.setValue("ResultVariable", resultVariable)
cellResult.setValue("FlowTracerSelectionMode", selectionMode)
if selectionMode == 'FLOW_TR_BY_SELECTION':
cellResult.setValue("SelectedInjectorTracers", injectors)
cellResult.setValue("SelectedProducerTracers", producers)
cellResult.update()
cell_result = self.set_cell_result()
cell_result.set_value("ResultType", "FLOW_DIAGNOSTICS")
cell_result.set_value("ResultVariable", result_variable)
cell_result.set_value("FlowTracerSelectionMode", selection_mode)
if selection_mode == 'FLOW_TR_BY_SELECTION':
cell_result.set_value("SelectedInjectorTracers", injectors)
cell_result.set_value("SelectedProducerTracers", producers)
cell_result.update()
def case(self):
"""Get the case the view belongs to"""
pdmCase = self.ancestor("EclipseCase")
if pdmCase is None:
pdmCase = self.ancestor("ResInsightGeoMechCase")
if pdmCase is None:
pdm_case = self.ancestor("EclipseCase")
if pdm_case is None:
pdm_case = self.ancestor("ResInsightGeoMechCase")
if pdm_case is None:
return None
return rips.Case(self.channel, pdmCase.getValue("CaseId"))
return rips.Case(self.channel, pdm_case.get_value("CaseId"))
def clone(self):
"""Clone the current view"""
viewId = Commands(self.channel).cloneView(self.id)
return self.case().view(viewId)
view_id = Commands(self.channel).clone_view(self.id)
return self.case().view(view_id)

View File

@ -13,9 +13,9 @@ def rips_instance():
return _rips_instance
@pytest.fixture
def initializeTest():
def initialize_test():
_rips_instance.project.close() # make sure ResInsight is clean before execution of test
yield initializeTest
yield initialize_test
_rips_instance.project.close() # make sure ResInsight is clean after test
def pytest_addoption(parser):

View File

@ -7,75 +7,75 @@ import rips
import dataroot
def test_Launch(rips_instance, initializeTest):
def test_Launch(rips_instance, initialize_test):
assert(rips_instance is not None)
def test_EmptyProject(rips_instance, initializeTest):
def test_EmptyProject(rips_instance, initialize_test):
cases = rips_instance.project.cases()
assert(len(cases) is 0)
def test_OneCase(rips_instance, initializeTest):
case = rips_instance.project.loadCase(dataroot.PATH + "/TEST10K_FLT_LGR_NNC/TEST10K_FLT_LGR_NNC.EGRID")
def test_OneCase(rips_instance, initialize_test):
case = rips_instance.project.load_case(dataroot.PATH + "/TEST10K_FLT_LGR_NNC/TEST10K_FLT_LGR_NNC.EGRID")
assert(case.name == "TEST10K_FLT_LGR_NNC")
assert(case.id == 0)
cases = rips_instance.project.cases()
assert(len(cases) is 1)
def test_MultipleCases(rips_instance, initializeTest):
casePaths = []
casePaths.append(dataroot.PATH + "/TEST10K_FLT_LGR_NNC/TEST10K_FLT_LGR_NNC.EGRID")
casePaths.append(dataroot.PATH + "/TEST10K_FLT_LGR_NNC/TEST10K_FLT_LGR_NNC.EGRID")
casePaths.append(dataroot.PATH + "/TEST10K_FLT_LGR_NNC/TEST10K_FLT_LGR_NNC.EGRID")
def test_MultipleCases(rips_instance, initialize_test):
case_paths = []
case_paths.append(dataroot.PATH + "/TEST10K_FLT_LGR_NNC/TEST10K_FLT_LGR_NNC.EGRID")
case_paths.append(dataroot.PATH + "/TEST10K_FLT_LGR_NNC/TEST10K_FLT_LGR_NNC.EGRID")
case_paths.append(dataroot.PATH + "/TEST10K_FLT_LGR_NNC/TEST10K_FLT_LGR_NNC.EGRID")
caseNames = []
for casePath in casePaths:
caseName = os.path.splitext(os.path.basename(casePath))[0]
caseNames.append(caseName)
rips_instance.project.loadCase(path=casePath)
case_names = []
for case_path in case_paths:
case_name = os.path.splitext(os.path.basename(case_path))[0]
case_names.append(case_name)
rips_instance.project.load_case(path=case_path)
cases = rips_instance.project.cases()
assert(len(cases) == len(caseNames))
for i, caseName in enumerate(caseNames):
assert(caseName == cases[i].name)
assert(len(cases) == len(case_names))
for i, case_name in enumerate(case_names):
assert(case_name == cases[i].name)
def test_10k(rips_instance, initializeTest):
casePath = dataroot.PATH + "/TEST10K_FLT_LGR_NNC/TEST10K_FLT_LGR_NNC.EGRID"
case = rips_instance.project.loadCase(path=casePath)
assert(case.gridCount() == 2)
cellCountInfo = case.cellCount()
assert(cellCountInfo.active_cell_count == 11125)
assert(cellCountInfo.reservoir_cell_count == 316224)
timeSteps = case.timeSteps()
assert(len(timeSteps) == 9)
daysSinceStart = case.daysSinceStart()
assert(len(daysSinceStart) == 9)
def test_10k(rips_instance, initialize_test):
case_path = dataroot.PATH + "/TEST10K_FLT_LGR_NNC/TEST10K_FLT_LGR_NNC.EGRID"
case = rips_instance.project.load_case(path=case_path)
assert(case.grid_count() == 2)
cell_count_info = case.cell_count()
assert(cell_count_info.active_cell_count == 11125)
assert(cell_count_info.reservoir_cell_count == 316224)
time_steps = case.time_steps()
assert(len(time_steps) == 9)
days_since_start = case.days_since_start()
assert(len(days_since_start) == 9)
def test_PdmObject(rips_instance, initializeTest):
casePath = dataroot.PATH + "/TEST10K_FLT_LGR_NNC/TEST10K_FLT_LGR_NNC.EGRID"
case = rips_instance.project.loadCase(path=casePath)
def test_PdmObject(rips_instance, initialize_test):
case_path = dataroot.PATH + "/TEST10K_FLT_LGR_NNC/TEST10K_FLT_LGR_NNC.EGRID"
case = rips_instance.project.load_case(path=case_path)
assert(case.id == 0)
assert(case.address() is not 0)
assert(case.classKeyword() == "EclipseCase")
caseId = case.getValue('CaseId')
assert(caseId == case.id)
assert(case.class_keyword() == "EclipseCase")
case_id = case.get_value('CaseId')
assert(case_id == case.id)
@pytest.mark.skipif(sys.platform.startswith('linux'), reason="Brugge is currently exceptionally slow on Linux")
def test_brugge_0010(rips_instance, initializeTest):
casePath = dataroot.PATH + "/Case_with_10_timesteps/Real10/BRUGGE_0010.EGRID"
case = rips_instance.project.loadCase(path=casePath)
assert(case.gridCount() == 1)
cellCountInfo = case.cellCount()
def test_brugge_0010(rips_instance, initialize_test):
case_path = dataroot.PATH + "/Case_with_10_timesteps/Real10/BRUGGE_0010.EGRID"
case = rips_instance.project.load_case(path=case_path)
assert(case.grid_count() == 1)
cellCountInfo = case.cell_count()
assert(cellCountInfo.active_cell_count == 43374)
assert(cellCountInfo.reservoir_cell_count == 60048)
timeSteps = case.timeSteps()
assert(len(timeSteps) == 11)
daysSinceStart = case.daysSinceStart()
assert(len(daysSinceStart) == 11)
time_steps = case.time_steps()
assert(len(time_steps) == 11)
days_since_start = case.days_since_start()
assert(len(days_since_start) == 11)
@pytest.mark.skipif(sys.platform.startswith('linux'), reason="Brugge is currently exceptionally slow on Linux")
def test_replaceCase(rips_instance, initializeTest):
def test_replaceCase(rips_instance, initialize_test):
project = rips_instance.project.open(dataroot.PATH + "/TEST10K_FLT_LGR_NNC/10KWithWellLog.rsp")
casePath = dataroot.PATH + "/Case_with_10_timesteps/Real0/BRUGGE_0000.EGRID"
case_path = dataroot.PATH + "/Case_with_10_timesteps/Real0/BRUGGE_0000.EGRID"
case = project.case(id=0)
assert(case is not None)
assert(case.name == "TEST10K_FLT_LGR_NNC")
@ -83,7 +83,7 @@ def test_replaceCase(rips_instance, initializeTest):
cases = rips_instance.project.cases()
assert(len(cases) is 1)
rips_instance.commands.replaceCase(newGridFile=casePath, caseId=case.id)
rips_instance.commands.replace_case(new_grid_file=case_path, case_id=case.id)
cases = rips_instance.project.cases()
assert(len(cases) is 1)
case = project.case(id=0)

View File

@ -9,50 +9,50 @@ import rips
import dataroot
def test_exportSnapshots(rips_instance, initializeTest):
if not rips_instance.isGui():
def test_exportSnapshots(rips_instance, initialize_test):
if not rips_instance.is_gui():
pytest.skip("Cannot run test without a GUI")
casePath = dataroot.PATH + "/TEST10K_FLT_LGR_NNC/TEST10K_FLT_LGR_NNC.EGRID"
rips_instance.project.loadCase(casePath)
case_path = dataroot.PATH + "/TEST10K_FLT_LGR_NNC/TEST10K_FLT_LGR_NNC.EGRID"
rips_instance.project.load_case(case_path)
with tempfile.TemporaryDirectory(prefix="rips") as tmpdirname:
print("Temporary folder: ", tmpdirname)
rips_instance.commands.setExportFolder(type='SNAPSHOTS', path=tmpdirname)
rips_instance.commands.exportSnapshots()
rips_instance.commands.set_export_folder(type='SNAPSHOTS', path=tmpdirname)
rips_instance.commands.export_snapshots()
print(os.listdir(tmpdirname))
assert(len(os.listdir(tmpdirname)) > 0)
for fileName in os.listdir(tmpdirname):
assert(os.path.splitext(fileName)[1] == '.png')
def test_exportPropertyInView(rips_instance, initializeTest):
casePath = dataroot.PATH + "/TEST10K_FLT_LGR_NNC/TEST10K_FLT_LGR_NNC.EGRID"
rips_instance.project.loadCase(casePath)
def test_exportPropertyInView(rips_instance, initialize_test):
case_path = dataroot.PATH + "/TEST10K_FLT_LGR_NNC/TEST10K_FLT_LGR_NNC.EGRID"
rips_instance.project.load_case(case_path)
with tempfile.TemporaryDirectory(prefix="rips") as tmpdirname:
print("Temporary folder: ", tmpdirname)
rips_instance.commands.setExportFolder(type='PROPERTIES', path=tmpdirname)
rips_instance.commands.set_export_folder(type='PROPERTIES', path=tmpdirname)
case = rips_instance.project.case(id=0)
rips_instance.commands.exportPropertyInViews(0, "3D View", 0)
expectedFileName = case.name + "-" + str("3D_View") + "-" + "T0" + "-SOIL"
fullPath = tmpdirname + "/" + expectedFileName
assert(os.path.exists(fullPath))
rips_instance.commands.export_property_in_views(0, "3D View", 0)
expected_file_name = case.name + "-" + str("3D_View") + "-" + "T0" + "-SOIL"
full_path = tmpdirname + "/" + expected_file_name
assert(os.path.exists(full_path))
@pytest.mark.skipif(sys.platform.startswith('linux'), reason="Brugge is currently exceptionally slow on Linux")
def test_loadGridCaseGroup(rips_instance, initializeTest):
casePaths = []
casePaths.append(dataroot.PATH + "/Case_with_10_timesteps/Real0/BRUGGE_0000.EGRID")
casePaths.append(dataroot.PATH + "/Case_with_10_timesteps/Real10/BRUGGE_0010.EGRID")
groupId, groupName = rips_instance.commands.createGridCaseGroup(casePaths=casePaths)
print(groupId, groupName)
def test_loadGridCaseGroup(rips_instance, initialize_test):
case_paths = []
case_paths.append(dataroot.PATH + "/Case_with_10_timesteps/Real0/BRUGGE_0000.EGRID")
case_paths.append(dataroot.PATH + "/Case_with_10_timesteps/Real10/BRUGGE_0010.EGRID")
group_id, group_name = rips_instance.commands.create_grid_case_group(case_paths=case_paths)
print(group_id, group_name)
def test_exportFlowCharacteristics(rips_instance, initializeTest):
casePath = dataroot.PATH + "/Case_with_10_timesteps/Real0/BRUGGE_0000.EGRID"
rips_instance.project.loadCase(casePath)
def test_exportFlowCharacteristics(rips_instance, initialize_test):
case_path = dataroot.PATH + "/Case_with_10_timesteps/Real0/BRUGGE_0000.EGRID"
rips_instance.project.load_case(case_path)
with tempfile.TemporaryDirectory(prefix="rips") as tmpdirname:
print("Temporary folder: ", tmpdirname)
fileName = tmpdirname + "/exportFlowChar.txt"
rips_instance.commands.exportFlowCharacteristics(caseId=0, timeSteps=8, producers=[], injectors = "I01", fileName = fileName)
file_name = tmpdirname + "/exportFlowChar.txt"
rips_instance.commands.export_flow_characteristics(case_id=0, time_steps=8, producers=[], injectors = "I01", file_name = file_name)
def test_loadNonExistingCase(rips_instance, initializeTest):
casePath = "Nonsense/Nonsense/Nonsense"
def test_loadNonExistingCase(rips_instance, initialize_test):
case_path = "Nonsense/Nonsense/Nonsense"
with pytest.raises(grpc.RpcError):
assert rips_instance.project.loadCase(casePath)
assert rips_instance.project.load_case(case_path)

View File

@ -6,10 +6,10 @@ import rips
import dataroot
def test_10k(rips_instance, initializeTest):
def test_10k(rips_instance, initialize_test):
casePath = dataroot.PATH + "/TEST10K_FLT_LGR_NNC/TEST10K_FLT_LGR_NNC.EGRID"
case = rips_instance.project.loadCase(path=casePath)
assert(case.gridCount() == 2)
case = rips_instance.project.load_case(path=casePath)
assert(case.grid_count() == 2)
grid = case.grid(index=0)
dimensions = grid.dimensions()
assert(dimensions.i == 90)

View File

@ -7,7 +7,7 @@ import rips
import dataroot
def test_loadProject(rips_instance, initializeTest):
def test_loadProject(rips_instance, initialize_test):
project = rips_instance.project.open(dataroot.PATH + "/TEST10K_FLT_LGR_NNC/10KWithWellLog.rsp")
case = project.case(id=0)
assert(case is not None)

View File

@ -8,11 +8,11 @@ import rips
import dataroot
def test_10kAsync(rips_instance, initializeTest):
def test_10kAsync(rips_instance, initialize_test):
casePath = dataroot.PATH + "/TEST10K_FLT_LGR_NNC/TEST10K_FLT_LGR_NNC.EGRID"
case = rips_instance.project.loadCase(path=casePath)
case = rips_instance.project.load_case(path=casePath)
resultChunks = case.properties.activeCellPropertyAsync('DYNAMIC_NATIVE', 'SOIL', 1)
resultChunks = case.properties.active_cell_property_async('DYNAMIC_NATIVE', 'SOIL', 1)
mysum = 0.0
count = 0
for chunk in resultChunks:
@ -23,42 +23,42 @@ def test_10kAsync(rips_instance, initializeTest):
assert(average != pytest.approx(0.0158893, abs=0.0000001))
assert(average == pytest.approx(0.0558893, abs=0.0000001))
def test_10kSync(rips_instance, initializeTest):
def test_10kSync(rips_instance, initialize_test):
casePath = dataroot.PATH + "/TEST10K_FLT_LGR_NNC/TEST10K_FLT_LGR_NNC.EGRID"
case = rips_instance.project.loadCase(path=casePath)
case = rips_instance.project.load_case(path=casePath)
results = case.properties.activeCellProperty('DYNAMIC_NATIVE', 'SOIL', 1)
results = case.properties.active_cell_property('DYNAMIC_NATIVE', 'SOIL', 1)
mysum = sum(results)
average = mysum / len(results)
assert(mysum == pytest.approx(621.768, abs=0.001))
assert(average != pytest.approx(0.0158893, abs=0.0000001))
assert(average == pytest.approx(0.0558893, abs=0.0000001))
def test_10k_set(rips_instance, initializeTest):
def test_10k_set(rips_instance, initialize_test):
casePath = dataroot.PATH + "/TEST10K_FLT_LGR_NNC/TEST10K_FLT_LGR_NNC.EGRID"
case = rips_instance.project.loadCase(path=casePath)
case = rips_instance.project.load_case(path=casePath)
results = case.properties.activeCellProperty('DYNAMIC_NATIVE', 'SOIL', 1)
case.properties.setActiveCellProperty(results, 'GENERATED', 'SOIL', 1)
results = case.properties.active_cell_property('DYNAMIC_NATIVE', 'SOIL', 1)
case.properties.set_active_cell_property(results, 'GENERATED', 'SOIL', 1)
def test_10k_set_out_of_bounds(rips_instance, initializeTest):
def test_10k_set_out_of_bounds(rips_instance, initialize_test):
casePath = dataroot.PATH + "/TEST10K_FLT_LGR_NNC/TEST10K_FLT_LGR_NNC.EGRID"
case = rips_instance.project.loadCase(path=casePath)
case = rips_instance.project.load_case(path=casePath)
results = case.properties.activeCellProperty('DYNAMIC_NATIVE', 'SOIL', 1)
results = case.properties.active_cell_property('DYNAMIC_NATIVE', 'SOIL', 1)
results.append(5.0)
with pytest.raises(grpc.RpcError):
assert case.properties.setActiveCellProperty(results, 'GENERATED', 'SOIL', 1)
assert case.properties.set_active_cell_property(results, 'GENERATED', 'SOIL', 1)
def test_10k_set_out_of_bounds_client(rips_instance, initializeTest):
def test_10k_set_out_of_bounds_client(rips_instance, initialize_test):
casePath = dataroot.PATH + "/TEST10K_FLT_LGR_NNC/TEST10K_FLT_LGR_NNC.EGRID"
case = rips_instance.project.loadCase(path=casePath)
case = rips_instance.project.load_case(path=casePath)
results = case.properties.activeCellProperty('DYNAMIC_NATIVE', 'SOIL', 1)
case.properties.chunkSize = len(results)
results = case.properties.active_cell_property('DYNAMIC_NATIVE', 'SOIL', 1)
case.properties.chunk_size = len(results)
results.append(5.0)
with pytest.raises(IndexError):
assert case.properties.setActiveCellProperty(results, 'GENERATED', 'SOIL', 1)
assert case.properties.set_active_cell_property(results, 'GENERATED', 'SOIL', 1)
def createResult(poroChunks, permxChunks):
for (poroChunk, permxChunk) in zip(poroChunks, permxChunks):
@ -72,18 +72,18 @@ def checkResults(poroValues, permxValues, poropermxValues):
recalc = poro * permx
assert(recalc == pytest.approx(poropermx, rel=1.0e-10))
def test_10k_PoroPermX(rips_instance, initializeTest):
def test_10k_PoroPermX(rips_instance, initialize_test):
casePath = dataroot.PATH + "/TEST10K_FLT_LGR_NNC/TEST10K_FLT_LGR_NNC.EGRID"
case = rips_instance.project.loadCase(path=casePath)
case = rips_instance.project.load_case(path=casePath)
poroChunks = case.properties.activeCellPropertyAsync('STATIC_NATIVE', 'PORO', 0)
permxChunks = case.properties.activeCellPropertyAsync('STATIC_NATIVE', 'PERMX', 0)
poroChunks = case.properties.active_cell_property_async('STATIC_NATIVE', 'PORO', 0)
permxChunks = case.properties.active_cell_property_async('STATIC_NATIVE', 'PERMX', 0)
case.properties.setActiveCellPropertyAsync(createResult(poroChunks, permxChunks), 'GENERATED', 'POROPERMXAS', 0)
case.properties.set_active_cell_property_async(createResult(poroChunks, permxChunks), 'GENERATED', 'POROPERMXAS', 0)
poro = case.properties.activeCellProperty('STATIC_NATIVE', 'PORO', 0)
permx = case.properties.activeCellProperty('STATIC_NATIVE', 'PERMX', 0)
poroPermX = case.properties.activeCellProperty('GENERATED', 'POROPERMXAS', 0)
poro = case.properties.active_cell_property('STATIC_NATIVE', 'PORO', 0)
permx = case.properties.active_cell_property('STATIC_NATIVE', 'PERMX', 0)
poroPermX = case.properties.active_cell_property('GENERATED', 'POROPERMXAS', 0)
checkResults(poro, permx, poroPermX)