#4430 Implement GetAvailableProperties() and GetActiveCellResults()

This commit is contained in:
Gaute Lindkvist 2019-05-21 13:40:42 +02:00
parent c4a4ceef29
commit 86e202aed0
8 changed files with 440 additions and 169 deletions

View File

@ -24,7 +24,7 @@ CONFIGURE_FILE( ${CMAKE_SOURCE_DIR}/ApplicationCode/Adm/RiaVersionInfo.h.cmake
${CMAKE_BINARY_DIR}/Generated/RiaVersionInfo.h ${CMAKE_BINARY_DIR}/Generated/RiaVersionInfo.h
) )
CONFIGURE_FILE( ${CMAKE_SOURCE_DIR}/ApplicationCode/Adm/RiaVersionInfo.py.cmake CONFIGURE_FILE( ${CMAKE_SOURCE_DIR}/ApplicationCode/Adm/RiaVersionInfo.py.cmake
${CMAKE_BINARY_DIR}/Python/generated/RiaVersionInfo.py ${CMAKE_SOURCE_DIR}/Python/generated/RiaVersionInfo.py
) )
if (MSVC AND (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 19.11)) if (MSVC AND (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 19.11))

View File

@ -9,6 +9,7 @@ set ( SOURCE_GROUP_HEADER_FILES
${CMAKE_CURRENT_LIST_DIR}/RiaGrpcProjectInfoService.h ${CMAKE_CURRENT_LIST_DIR}/RiaGrpcProjectInfoService.h
${CMAKE_CURRENT_LIST_DIR}/RiaGrpcCommandService.h ${CMAKE_CURRENT_LIST_DIR}/RiaGrpcCommandService.h
${CMAKE_CURRENT_LIST_DIR}/RiaGrpcResInfoService.h ${CMAKE_CURRENT_LIST_DIR}/RiaGrpcResInfoService.h
${CMAKE_CURRENT_LIST_DIR}/RiaGrpcPropertiesService.h
) )
set ( SOURCE_GROUP_SOURCE_FILES set ( SOURCE_GROUP_SOURCE_FILES
@ -18,6 +19,7 @@ set ( SOURCE_GROUP_SOURCE_FILES
${CMAKE_CURRENT_LIST_DIR}/RiaGrpcProjectInfoService.cpp ${CMAKE_CURRENT_LIST_DIR}/RiaGrpcProjectInfoService.cpp
${CMAKE_CURRENT_LIST_DIR}/RiaGrpcCommandService.cpp ${CMAKE_CURRENT_LIST_DIR}/RiaGrpcCommandService.cpp
${CMAKE_CURRENT_LIST_DIR}/RiaGrpcResInfoService.cpp ${CMAKE_CURRENT_LIST_DIR}/RiaGrpcResInfoService.cpp
${CMAKE_CURRENT_LIST_DIR}/RiaGrpcPropertiesService.cpp
) )
add_definitions(-DENABLE_GRPC) add_definitions(-DENABLE_GRPC)
@ -74,6 +76,7 @@ set(PROTO_FILES
"ProjectInfo" "ProjectInfo"
"Commands" "Commands"
"ResInfo" "ResInfo"
"Properties"
) )
set(GRPC_PYTHON_SOURCE_PATH "${CMAKE_SOURCE_DIR}/Python") set(GRPC_PYTHON_SOURCE_PATH "${CMAKE_SOURCE_DIR}/Python")
@ -139,6 +142,7 @@ endforeach(proto_file)
if (PYTHON_EXECUTABLE AND EXISTS ${PYTHON_EXECUTABLE}) if (PYTHON_EXECUTABLE AND EXISTS ${PYTHON_EXECUTABLE})
list(APPEND GRPC_PYTHON_SOURCES list(APPEND GRPC_PYTHON_SOURCES
${GRPC_PYTHON_GENERATED_SOURCES} ${GRPC_PYTHON_GENERATED_SOURCES}
"generated/RiaVersionInfo.py"
"api/__init__.py" "api/__init__.py"
"api/ResInsight.py" "api/ResInsight.py"
"examples/CommandExample.py" "examples/CommandExample.py"

View File

@ -0,0 +1,69 @@
syntax = "proto3";
import "Empty.proto";
import "CaseInfo.proto";
import "GridInfo.proto";
package rips;
service Properties
{
rpc GetAvailableProperties(PropertiesRequest) returns (AvailableProperties) {}
rpc GetActiveCellResults(ResultRequest) returns (stream ResultReplyArray) {}
rpc GetGridResults(ResultRequest) returns (stream ResultReplyArray) {}
rpc SetActiveCellResults(stream ResultRequestArray) returns (Empty) {}
rpc SetGridResults(stream ResultRequestArray) returns (Empty) {}
}
enum PropertyType
{
DYNAMIC_NATIVE = 0;
STATIC_NATIVE = 1;
SOURSIMRL = 2;
GENERATED = 3;
INPUT_PROPERTY = 4;
FORMATION_NAMES = 5;
FLOW_DIAGNOSTICS = 6;
INJECTION_FLOODING = 7;
REMOVED = 8;
UNDEFINED = 999;
}
message PropertiesRequest
{
Case request_case = 1;
PropertyType property_type = 2;
PorosityModelType porosity_model = 3;
}
message AvailableProperties
{
repeated string property_names = 1;
}
message ResultRequest
{
Case request_case = 1;
PropertyType property_type = 2;
string property_name = 3;
int32 time_step = 4;
int32 grid_index = 5;
PorosityModelType porosity_model = 6;
}
message TimeStep
{
int32 index = 1;
}
message ResultRequestArray
{
repeated double values = 1;
Case request_case = 2;
TimeStep time_step = 3;
}
message ResultReplyArray
{
repeated double values = 1;
}

View File

@ -41,9 +41,8 @@ class RimEclipseCase;
//================================================================================================== //==================================================================================================
class RiaActiveCellInfoStateHandler class RiaActiveCellInfoStateHandler
{ {
public:
typedef grpc::Status Status; typedef grpc::Status Status;
public:
RiaActiveCellInfoStateHandler(); RiaActiveCellInfoStateHandler();
Status init(const rips::ActiveCellInfoRequest* request); Status init(const rips::ActiveCellInfoRequest* request);

View File

@ -0,0 +1,145 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2019- Equinor ASA
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// ResInsight is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE.
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
//////////////////////////////////////////////////////////////////////////////////
#include "RiaGrpcPropertiesService.h"
#include "RiaGrpcGridInfoService.h"
#include "RiaGrpcCallbacks.h"
#include "RigCaseCellResultsData.h"
#include "RigEclipseCaseData.h"
#include "RigEclipseResultAddress.h"
#include "RimEclipseCase.h"
using namespace rips;
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RiaActiveCellResultsStateHandler::RiaActiveCellResultsStateHandler()
: m_request(nullptr)
, m_resultValues(nullptr)
, m_currentCellIdx(0u)
{
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
grpc::Status RiaActiveCellResultsStateHandler::init(const ResultRequest* request)
{
int caseId = request->request_case().id();
RimEclipseCase* eclipseCase = dynamic_cast<RimEclipseCase*>(RiaGrpcServiceInterface::findCase(caseId));
if (eclipseCase)
{
auto porosityModel = static_cast<RiaDefines::PorosityModelType>(request->porosity_model());
auto resultData = eclipseCase->eclipseCaseData()->results(porosityModel);
auto resultType = static_cast<RiaDefines::ResultCatType>(request->property_type());
size_t timeStep = static_cast<size_t>(request->time_step());
RigEclipseResultAddress resAddr(resultType, QString::fromStdString(request->property_name()));
if (resultData->hasResultEntry(resAddr))
{
if (timeStep < (int)resultData->timeStepCount(resAddr))
{
m_resultValues = &resultData->cellScalarResults(resAddr, timeStep);
return grpc::Status::OK;
}
return grpc::Status(grpc::NOT_FOUND, "No such time step");
}
return grpc::Status(grpc::NOT_FOUND, "No such result");
}
return grpc::Status(grpc::NOT_FOUND, "Couldn't find an Eclipse case matching the case Id");
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
grpc::Status RiaActiveCellResultsStateHandler::assignReply(ResultReplyArray* reply)
{
if (m_resultValues)
{
const size_t packageSize = RiaGrpcServiceInterface::numberOfMessagesForByteCount(sizeof(rips::ResultReplyArray));
size_t packageIndex = 0u;
reply->mutable_values()->Reserve((int)packageSize);
for (; packageIndex < packageSize && m_currentCellIdx < m_resultValues->size(); ++packageIndex, ++m_currentCellIdx)
{
reply->add_values(m_resultValues->at(m_currentCellIdx));
}
if (packageIndex > 0u)
{
return grpc::Status::OK;
}
return grpc::Status(grpc::OUT_OF_RANGE, "We've reached the end. This is not an error but means transmission is finished");
}
return grpc::Status(grpc::NOT_FOUND, "No result values found");
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
grpc::Status RiaGrpcPropertiesService::GetAvailableProperties(grpc::ServerContext* context,
const PropertiesRequest* request,
AvailableProperties* reply)
{
int caseId = request->request_case().id();
RimEclipseCase* eclipseCase = dynamic_cast<RimEclipseCase*>(RiaGrpcServiceInterface::findCase(caseId));
if (eclipseCase)
{
auto porosityModel = static_cast<RiaDefines::PorosityModelType>(request->porosity_model());
auto resultData = eclipseCase->eclipseCaseData()->results(porosityModel);
auto resultType = static_cast<RiaDefines::ResultCatType>(request->property_type());
QStringList resultNames = resultData->resultNames(resultType);
if (!resultNames.empty())
{
for (QString resultName : resultNames)
{
reply->add_property_names(resultName.toStdString());
}
return grpc::Status::OK;
}
return grpc::Status(grpc::NOT_FOUND, "Could not find any results matching result type");
}
return grpc::Status(grpc::NOT_FOUND, "No such case");
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
grpc::Status RiaGrpcPropertiesService::GetActiveCellResults(grpc::ServerContext* context,
const ResultRequest* request,
ResultReplyArray* reply,
RiaActiveCellResultsStateHandler* stateHandler)
{
return stateHandler->assignReply(reply);
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
std::vector<RiaAbstractGrpcCallback*> RiaGrpcPropertiesService::createCallbacks()
{
typedef RiaGrpcPropertiesService Self;
return { new RiaGrpcCallback<Self, PropertiesRequest, AvailableProperties>(this, &Self::GetAvailableProperties, &Self::RequestGetAvailableProperties),
new RiaGrpcStreamCallback<Self, ResultRequest, ResultReplyArray, RiaActiveCellResultsStateHandler>(
this, &Self::GetActiveCellResults, &Self::RequestGetActiveCellResults, new RiaActiveCellResultsStateHandler)
};
}
static bool RiaGrpcPropertiesService_init = RiaGrpcServiceFactory::instance()->registerCreator<RiaGrpcPropertiesService>(typeid(RiaGrpcPropertiesService).hash_code());

View File

@ -0,0 +1,59 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2019- Equinor ASA
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// ResInsight is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE.
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
//////////////////////////////////////////////////////////////////////////////////
#pragma once
#include "RiaGrpcServiceInterface.h"
#include "Properties.grpc.pb.h"
#include <grpcpp/grpcpp.h>
#include <vector>
class RiaActiveCellResultsStateHandler
{
typedef grpc::Status Status;
public:
RiaActiveCellResultsStateHandler();
Status init(const rips::ResultRequest* request);
Status assignReply(rips::ResultReplyArray* reply);
private:
const rips::ResultRequest* m_request;
const std::vector<double>* m_resultValues;
size_t m_currentCellIdx;
};
//==================================================================================================
//
// gRPC-service answering requests about property information for a given case and time step
//
//==================================================================================================
class RiaGrpcPropertiesService final : public rips::Properties::AsyncService, public RiaGrpcServiceInterface
{
public:
grpc::Status GetAvailableProperties(grpc::ServerContext* context,
const rips::PropertiesRequest* request,
rips::AvailableProperties* reply) override;
grpc::Status GetActiveCellResults(grpc::ServerContext* context,
const rips::ResultRequest* request,
rips::ResultReplyArray* reply,
RiaActiveCellResultsStateHandler* stateHandler);
std::vector<RiaAbstractGrpcCallback*> createCallbacks() override;
};

View File

@ -7,7 +7,7 @@ import socket
sys.path.insert(1, os.path.join(sys.path[0], '../generated')) sys.path.insert(1, os.path.join(sys.path[0], '../generated'))
import Empty_pb2 from Empty_pb2 import Empty
import CaseInfo_pb2 import CaseInfo_pb2
import CaseInfo_pb2_grpc import CaseInfo_pb2_grpc
import Commands_pb2 import Commands_pb2
@ -18,142 +18,163 @@ import ProjectInfo_pb2
import ProjectInfo_pb2_grpc import ProjectInfo_pb2_grpc
import ResInfo_pb2 import ResInfo_pb2
import ResInfo_pb2_grpc import ResInfo_pb2_grpc
import Properties_pb2
import Properties_pb2_grpc
import RiaVersionInfo import RiaVersionInfo
MAX_MESSAGE_LENGTH = 128 * 1024 * 1024
class ResInfo: class ResInfo:
def __init__(self, channel): def __init__(self, channel):
self.resInfo = ResInfo_pb2_grpc.ResInfoStub(channel) self.resInfo = ResInfo_pb2_grpc.ResInfoStub(channel)
def versionMessage(self): def versionMessage(self):
return self.resInfo.GetVersion(Empty_pb2.Empty()) return self.resInfo.GetVersion(Empty())
def majorVersion(self): def majorVersion(self):
return self.versionMessage().major_version return self.versionMessage().major_version
def minorVersion(self): def minorVersion(self):
return self.versionMessage().minor_version return self.versionMessage().minor_version
def patchVersion(self): def patchVersion(self):
return self.versionMessage().patch_version return self.versionMessage().patch_version
def versionString(self): def versionString(self):
return str(self.majorVersion()) + "." + str(self.minorVersion()) + "." + str(self.patchVersion()) return str(self.majorVersion()) + "." + str(self.minorVersion()) + "." + str(self.patchVersion())
class CommandExecutor: class CommandExecutor:
def __init__(self, channel): def __init__(self, channel):
self.commands = Commands_pb2_grpc.CommandsStub(channel) self.commands = Commands_pb2_grpc.CommandsStub(channel)
def execute(self, commandParams): def execute(self, commandParams):
try: try:
self.commands.Execute(commandParams) self.commands.Execute(commandParams)
except grpc.RpcError as e: except grpc.RpcError as e:
if e.code() == grpc.StatusCode.NOT_FOUND: if e.code() == grpc.StatusCode.NOT_FOUND:
print("Command not found") print("Command not found")
else: else:
print("Other error") print("Other error")
def setTimeStep(self, caseId, timeStep): def setTimeStep(self, caseId, timeStep):
return self.execute(Commands_pb2.CommandParams(setTimeStep=Commands_pb2.SetTimeStepParams(caseId=caseId, timeStep=timeStep))) return self.execute(Commands_pb2.CommandParams(setTimeStep=Commands_pb2.SetTimeStepParams(caseId=caseId, timeStep=timeStep)))
def setMainWindowSize(self, width, height): def setMainWindowSize(self, width, height):
return self.execute(Commands_pb2.CommandParams(setMainWindowSize=Commands_pb2.SetMainWindowSizeParams(width=width, height=height))) return self.execute(Commands_pb2.CommandParams(setMainWindowSize=Commands_pb2.SetMainWindowSizeParams(width=width, height=height)))
def openProject(self, path): def openProject(self, path):
return self.execute(Commands_pb2.CommandParams(openProject=Commands_pb2.FilePathRequest(path=path))) return self.execute(Commands_pb2.CommandParams(openProject=Commands_pb2.FilePathRequest(path=path)))
def loadCase(self, path): def loadCase(self, path):
return self.execute(Commands_pb2.CommandParams(loadCase=Commands_pb2.FilePathRequest(path=path))) return self.execute(Commands_pb2.CommandParams(loadCase=Commands_pb2.FilePathRequest(path=path)))
def closeProject(self): def closeProject(self):
return self.execute(Commands_pb2.CommandParams(closeProject=Empty_pb2.Empty())) return self.execute(Commands_pb2.CommandParams(closeProject=Empty()))
class GridInfo: class GridInfo:
def __init__(self, channel): def __init__(self, channel):
self.gridInfo = GridInfo_pb2_grpc.GridInfoStub(channel) self.gridInfo = GridInfo_pb2_grpc.GridInfoStub(channel)
def getGridCount(self, caseId=0): def getGridCount(self, caseId=0):
return self.gridInfo.GetGridCount(CaseInfo_pb2.Case(id=caseId)).count return self.gridInfo.GetGridCount(CaseInfo_pb2.Case(id=caseId)).count
def getGridDimensions(self, caseId=0): def getGridDimensions(self, caseId=0):
return self.gridInfo.GetGridDimensions(CaseInfo_pb2.Case(id=caseId)).dimensions return self.gridInfo.GetGridDimensions(CaseInfo_pb2.Case(id=caseId)).dimensions
def streamActiveCellInfo(self, caseId=0): def streamActiveCellInfo(self, caseId=0):
return self.gridInfo.StreamActiveCellInfo(CaseInfo_pb2.Case(id=caseId)) return self.gridInfo.StreamActiveCellInfo(CaseInfo_pb2.Case(id=caseId))
class ProjectInfo: class ProjectInfo:
def __init__(self, channel): def __init__(self, channel):
self.projectInfo = ProjectInfo_pb2_grpc.ProjectInfoStub(channel) self.projectInfo = ProjectInfo_pb2_grpc.ProjectInfoStub(channel)
def selectedCases(self): def selectedCases(self):
selected = self.projectInfo.SelectedCases(Empty_pb2.Empty()) selected = self.projectInfo.SelectedCases(Empty())
if selected is not None: if selected is not None:
return selected.case_info return selected.case_info
else: else:
return None return None
def allCases(self): def allCases(self):
cases = self.projectInfo.AllCases(Empty_pb2.Empty()) cases = self.projectInfo.AllCases(Empty())
if cases is not None: if cases is not None:
return allCases.case_info return allCases.case_info
else: else:
return None return None
class Properties:
def __init__(self, channel):
self.properties = Properties_pb2_grpc.PropertiesStub(channel)
def availableProperties(self, caseId, propertyType, porosityModel = 'MATRIX_MODEL'):
propertyTypeEnum = Properties_pb2.PropertyType.Value(propertyType)
porosityModelEnum = GridInfo_pb2.PorosityModelType.Value(porosityModel)
request = Properties_pb2.PropertiesRequest (request_case = CaseInfo_pb2.Case(id=caseId),
property_type = propertyTypeEnum,
porosity_model = porosityModelEnum)
return self.properties.GetAvailableProperties(request).property_names
def activeCellResults(self, caseId, propertyType, propertyName, timeStep, porosityModel = 'MATRIX_MODEL'):
propertyTypeEnum = Properties_pb2.PropertyType.Value(propertyType)
porosityModelEnum = GridInfo_pb2.PorosityModelType.Value(porosityModel)
request = Properties_pb2.ResultRequest(request_case = CaseInfo_pb2.Case(id=caseId),
property_type = propertyTypeEnum,
property_name = propertyName,
time_step = timeStep,
porosity_model = porosityModelEnum)
return self.properties.GetActiveCellResults(request)
class Instance: class Instance:
@staticmethod @staticmethod
def is_port_in_use(port): def is_port_in_use(port):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.settimeout(0.2) s.settimeout(0.2)
return s.connect_ex(('localhost', port)) == 0 return s.connect_ex(('localhost', port)) == 0
@staticmethod @staticmethod
def launch(): def launch():
port = 50051 port = 50051
portEnv = os.environ.get('RESINSIGHT_GRPC_PORT') portEnv = os.environ.get('RESINSIGHT_GRPC_PORT')
if portEnv: if portEnv:
port = int(portEnv) port = int(portEnv)
resInsightExecutable = os.environ.get('RESINSIGHT_EXECUTABLE') resInsightExecutable = os.environ.get('RESINSIGHT_EXECUTABLE')
if resInsightExecutable is None: if resInsightExecutable is None:
print('Error: Could not launch any ResInsight instances because RESINSIGHT_EXECUTABLE is not set') print('Error: Could not launch any ResInsight instances because RESINSIGHT_EXECUTABLE is not set')
return None return None
while Instance.is_port_in_use(port): while Instance.is_port_in_use(port):
port += 1 port += 1
print('Port ' + str(port)) print('Port ' + str(port))
print('Trying to launch', resInsightExecutable) print('Trying to launch', resInsightExecutable)
pid = os.spawnl(os.P_NOWAIT, resInsightExecutable, " --grpcserver " + str(port)) pid = os.spawnl(os.P_NOWAIT, resInsightExecutable, " --grpcserver " + str(port))
print(pid) print(pid)
return Instance(port) return Instance(port)
@staticmethod @staticmethod
def find(startPort = 50051, endPort = 50071): def find(startPort = 50051, endPort = 50071):
portEnv = os.environ.get('RESINSIGHT_GRPC_PORT') portEnv = os.environ.get('RESINSIGHT_GRPC_PORT')
if portEnv: if portEnv:
startPort = int(portEnv) startPort = int(portEnv)
endPort = startPort + 20 endPort = startPort + 20
for tryPort in range(startPort, endPort): for tryPort in range(startPort, endPort):
if Instance.is_port_in_use(tryPort): if Instance.is_port_in_use(tryPort):
return Instance(tryPort) return Instance(tryPort)
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(startPort) + ' and ' + str(endPort))
return None return None
def __init__(self, port = 50051): def __init__(self, port = 50051):
location = "localhost:" + str(port) location = "localhost:" + str(port)
self.channel = grpc.insecure_channel(location, options=[('grpc.max_receive_message_length', MAX_MESSAGE_LENGTH)]) self.channel = grpc.insecure_channel(location)
# Main version check package # Main version check package
self.resInfo = ResInfo(self.channel) self.resInfo = ResInfo(self.channel)
try: try:
majorVersionOk = self.resInfo.majorVersion() == int(RiaVersionInfo.RESINSIGHT_MAJOR_VERSION) majorVersionOk = self.resInfo.majorVersion() == int(RiaVersionInfo.RESINSIGHT_MAJOR_VERSION)
minorVersionOk = self.resInfo.minorVersion() == int(RiaVersionInfo.RESINSIGHT_MINOR_VERSION) minorVersionOk = self.resInfo.minorVersion() == int(RiaVersionInfo.RESINSIGHT_MINOR_VERSION)
if not (majorVersionOk and minorVersionOk): if not (majorVersionOk and minorVersionOk):
raise Exception('Version of ResInsight does not match version of Python API') raise Exception('Version of ResInsight does not match version of Python API')
except grpc.RpcError as e: except grpc.RpcError as e:
if e.code() == grpc.StatusCode.UNAVAILABLE: if e.code() == grpc.StatusCode.UNAVAILABLE:
print('Info: Could not find any instances at port ' + str(port)) print('Info: Could not find any instances at port ' + str(port))
except Exception as e: except Exception as e:
print('Error:', e) print('Error:', e)
# Service packages # Service packages
self.commands = CommandExecutor(self.channel) self.commands = CommandExecutor(self.channel)
self.gridInfo = GridInfo(self.channel) self.gridInfo = GridInfo(self.channel)
self.projectInfo = ProjectInfo(self.channel) self.projectInfo = ProjectInfo(self.channel)
self.properties = Properties(self.channel)

View File

@ -1,45 +1,19 @@
from ResInsight import ResInsight
import grpc
import logging
import sys import sys
import os
def run(): sys.path.insert(1, os.path.join(sys.path[0], '../api'))
# NOTE(gRPC Python Team): .close() is possible on a channel and should be import ResInsight
# used in circumstances in which the with statement does not fit the needs
# of the code.
logging.basicConfig()
try:
port = 50051
if len(sys.argv) > 1:
port = sys.argv[1]
resInsight = ResInsight("localhost:" + port)
timeStepsInfo = resInsight.grid.numberOfTimeSteps(ResInsight.Case(id=0))
print ("Number of time steps: " + str(timeStepsInfo.value))
resultsAllTimeSteps = []
for timeStep in range(0, timeStepsInfo.value - 1):
results = resInsight.grid.results(ResInsight.ResultRequest(ResInsight.Case(id=0), ResInsight.ResultAddress(0, "SOIL"), timeStep))
print ("Got " + str(len(results.value)) + " values")
resultsAllTimeSteps.append(results.value)
print("Have stored results array containing " + str(len(resultsAllTimeSteps)) + " time steps") resInsight = ResInsight.Instance.find()
#gridCount = resInsight.gridInfo.getGridCount(caseId=0)
#gridDimensions = resInsight.gridInfo.getAllGridDimensions(caseId=0)
print("Looking for first cell with a decent SOIL value") resultChunks = resInsight.properties.activeCellResults(0, 'DYNAMIC_NATIVE', 'SOIL', 2)
indexFirstProperCell = 0
for i in range(0, len(resultsAllTimeSteps[0])):
result = resultsAllTimeSteps[0][i]
if indexFirstProperCell == 0 and result > 0.01:
indexFirstProperCell = i
for resultsForTimeStep in resultsAllTimeSteps:
print ("Result for cell " + str(indexFirstProperCell) + ": " + str(resultsForTimeStep[indexFirstProperCell]))
except grpc.RpcError as e:
if e.code() == grpc.StatusCode.NOT_FOUND:
print("Case id not found")
else:
logging.error('Other error: %s', e)
results = []
if __name__ == '__main__': for resultChunk in resultChunks:
run() for value in resultChunk.values:
results.append(value)
print("Number of active cells: " + str(len(results)))
print("15th active cell: ")
for result in results:
print(result)