Added riSetGridProperty

Some known issues related to parsing of the Octave arguments
p4#: 21747
This commit is contained in:
Magne Sjaastad
2013-05-28 10:43:32 +02:00
parent 1cfdb0ddb1
commit 5bca9b28c1
3 changed files with 524 additions and 1 deletions

View File

@@ -407,7 +407,6 @@ public:
m_currentScalarIndex = scalarResultIndex;
m_currentPropertyName = propertyName;
}
}
if (scalarResultFrames == NULL)
@@ -664,3 +663,309 @@ private:
static bool RiaSetActiveCellProperty_init = RiaSocketCommandFactory::instance()->registerCreator<RiaSetActiveCellProperty>(RiaSetActiveCellProperty::commandName());
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
class RiaSetGridProperty : public RiaSocketCommand
{
public:
RiaSetGridProperty() :
m_currentReservoir(NULL),
m_scalarResultsToAdd(NULL),
m_currentGridIndex(cvf::UNDEFINED_SIZE_T),
m_currentScalarIndex(cvf::UNDEFINED_SIZE_T),
m_timeStepCountToRead(0),
m_bytesPerTimeStepToRead(0),
m_currentTimeStepNumberToRead(0),
m_invalidDataDetected(false),
m_porosityModelEnum(RifReaderInterface::MATRIX_RESULTS)
{}
static QString commandName () { return QString("SetGridProperty"); }
virtual bool interpretCommand(RiaSocketServer* server, const QList<QByteArray>& args, QDataStream& socketStream)
{
int caseId = args[1].toInt();
RimCase* rimCase = server->findReservoir(caseId);
if (!rimCase)
{
server->errorMessageDialog()->showMessage(RiaSocketServer::tr("ResInsight SocketServer: \n") + RiaSocketServer::tr("Could not find the case with ID : \"%1\"").arg(caseId));
return true;
}
m_currentGridIndex = args[2].toInt();
QString propertyName = args[3];
QString porosityModelName = args[4];
if (porosityModelName == "Fracture")
{
m_porosityModelEnum = RifReaderInterface::FRACTURE_RESULTS;
}
// Find the requested data, Or create a set if we are setting data and it is not found
if (server->currentClient()->bytesAvailable() < (int)sizeof(quint64)*5) return true;
quint64 cellCountI = 0;
quint64 cellCountJ = 0;
quint64 cellCountK = 0;
socketStream >> cellCountI;
socketStream >> cellCountJ;
socketStream >> cellCountK;
socketStream >> m_timeStepCountToRead;
socketStream >> m_bytesPerTimeStepToRead;
size_t scalarResultIndex = cvf::UNDEFINED_SIZE_T;
std::vector< std::vector<double> >* scalarResultFrames = NULL;
if (rimCase && rimCase->results(m_porosityModelEnum))
{
scalarResultIndex = rimCase->results(m_porosityModelEnum)->findOrLoadScalarResult(RimDefines::GENERATED, propertyName);
if (scalarResultIndex == cvf::UNDEFINED_SIZE_T)
{
scalarResultIndex = rimCase->results(m_porosityModelEnum)->cellResults()->addEmptyScalarResult(RimDefines::GENERATED, propertyName, true);
}
if (scalarResultIndex != cvf::UNDEFINED_SIZE_T)
{
scalarResultFrames = &(rimCase->results(m_porosityModelEnum)->cellResults()->cellScalarResults(scalarResultIndex));
m_currentScalarIndex = scalarResultIndex;
m_currentPropertyName = propertyName;
}
}
if (scalarResultFrames == NULL)
{
server->errorMessageDialog()->showMessage(RiaSocketServer::tr("ResInsight SocketServer: \n") + RiaSocketServer::tr("Could not find the %1 model property named: \"%2\"").arg(porosityModelName).arg(propertyName));
return true;
}
// Create a list of all the requested timesteps
m_requestedTimesteps.clear();
if (args.size() <= 5)
{
// Select all
for (size_t tsIdx = 0; tsIdx < m_timeStepCountToRead; ++tsIdx)
{
m_requestedTimesteps.push_back(tsIdx);
}
}
else
{
bool timeStepReadError = false;
for (int argIdx = 5; argIdx < args.size(); ++argIdx)
{
bool conversionOk = false;
int tsIdx = args[argIdx].toInt(&conversionOk);
if (conversionOk)
{
m_requestedTimesteps.push_back(tsIdx);
}
else
{
timeStepReadError = true;
}
}
if (timeStepReadError)
{
server->errorMessageDialog()->showMessage(RiaSocketServer::tr("ResInsight SocketServer: riGetActiveCellProperty : \n") + RiaSocketServer::tr("An error occured while interpreting the requested timesteps."));
}
}
if (! m_requestedTimesteps.size())
{
server->errorMessageDialog()->showMessage(RiaSocketServer::tr("ResInsight SocketServer: \n") + RiaSocketServer::tr("No time steps specified").arg(porosityModelName).arg(propertyName));
return true;
}
// Resize the result container to be able to receive time steps at the specified time step indices
std::vector<size_t>::iterator maxTimeStepIt = std::max_element(m_requestedTimesteps.begin(), m_requestedTimesteps.end());
CVF_ASSERT(maxTimeStepIt != m_requestedTimesteps.end());
size_t maxTimeStepIdx = (*maxTimeStepIt);
if (scalarResultFrames->size() <= maxTimeStepIdx)
{
scalarResultFrames->resize(maxTimeStepIdx+1);
}
m_currentReservoir = rimCase;
m_scalarResultsToAdd = scalarResultFrames;
if (server->currentClient()->bytesAvailable())
{
return this->interpretMore(server, server->currentClient());
}
return false;
}
virtual bool interpretMore(RiaSocketServer* server, QTcpSocket* currentClient)
{
if (m_invalidDataDetected) return true;
if (!currentClient->bytesAvailable()) return false;
QDataStream socketStream(currentClient);
socketStream.setVersion(riOctavePlugin::qtDataStreamVersion);
RigGridBase* grid = m_currentReservoir->reservoirData()->grid(m_currentGridIndex);
if (!grid)
{
server->errorMessageDialog()->showMessage(RiaSocketServer::tr("ResInsight SocketServer: \n") +
RiaSocketServer::tr("No grid found") + ":\"" + m_currentReservoir->caseUserDescription() + "\"\n");
m_invalidDataDetected = true;
currentClient->abort();
return true;
}
// If we have not read the header and there are data enough: Read it.
// Do nothing if we have not enough data
if (m_timeStepCountToRead == 0 || m_bytesPerTimeStepToRead == 0)
{
server->errorMessageDialog()->showMessage(RiaSocketServer::tr("ResInsight SocketServer: \n") +
RiaSocketServer::tr("Zero data to read for ") + ":\"" + m_currentReservoir->caseUserDescription() + "\"\n");
m_invalidDataDetected = true;
currentClient->abort();
return true;
}
if (m_timeStepCountToRead != m_requestedTimesteps.size())
{
CVF_ASSERT(false);
}
// If nothing should be read, or we already have read everything, do nothing
if ((m_timeStepCountToRead == 0) || (m_currentTimeStepNumberToRead >= m_timeStepCountToRead) ) return true;
// Check if a complete timestep is available, return and whait for readyRead() if not
if (currentClient->bytesAvailable() < (int)m_bytesPerTimeStepToRead) return false;
size_t cellCountFromOctave = m_bytesPerTimeStepToRead / sizeof(double);
RigActiveCellInfo* activeCellInfo = m_currentReservoir->reservoirData()->activeCellInfo(m_porosityModelEnum);
size_t globalCellResultCount = activeCellInfo->globalCellResultCount();
// Make sure the size of the retreiving container is correct.
// If it is, this is noops
for (size_t tIdx = 0; tIdx < m_timeStepCountToRead; ++tIdx)
{
size_t tsId = m_requestedTimesteps[tIdx];
m_scalarResultsToAdd->at(tsId).resize(globalCellResultCount, HUGE_VAL);
}
if ((currentClient->bytesAvailable() >= (int)m_bytesPerTimeStepToRead) && (m_currentTimeStepNumberToRead < m_timeStepCountToRead))
{
// Read a single time step with data
std::vector<double> doubleValues(cellCountFromOctave);
qint64 bytesRead = currentClient->read((char*)(doubleValues.data()), m_bytesPerTimeStepToRead);
size_t doubleValueIndex = 0;
for (size_t k = 0; k < grid->cellCountK(); k++)
{
for (size_t j = 0; j < grid->cellCountJ(); j++)
{
for (size_t i = 0; i < grid->cellCountI(); i++)
{
size_t localCellIndex = grid->cellIndexFromIJK(i,j,k);
size_t gcIdx = grid->globalGridCellIndex(localCellIndex);
size_t resultIdx = activeCellInfo->cellResultIndex(gcIdx);
if (resultIdx < m_scalarResultsToAdd->at(m_requestedTimesteps[m_currentTimeStepNumberToRead]).size())
{
m_scalarResultsToAdd->at(m_requestedTimesteps[m_currentTimeStepNumberToRead])[resultIdx] = doubleValues[doubleValueIndex];
}
doubleValueIndex++;
}
}
}
++m_currentTimeStepNumberToRead;
}
// If we have read all the data, refresh the views
if (m_currentTimeStepNumberToRead == m_timeStepCountToRead)
{
if (m_currentReservoir != NULL)
{
// Create a new input property if we have an input reservoir
RimInputCase* inputRes = dynamic_cast<RimInputCase*>(m_currentReservoir);
if (inputRes)
{
RimInputProperty* inputProperty = NULL;
inputProperty = inputRes->m_inputPropertyCollection->findInputProperty(m_currentPropertyName);
if (!inputProperty)
{
inputProperty = new RimInputProperty;
inputProperty->resultName = m_currentPropertyName;
inputProperty->eclipseKeyword = "";
inputProperty->fileName = "";
inputRes->m_inputPropertyCollection->inputProperties.push_back(inputProperty);
RimUiTreeModelPdm* treeModel = RiuMainWindow::instance()->uiPdmModel();
treeModel->updateUiSubTree(inputRes->m_inputPropertyCollection());
}
inputProperty->resolvedState = RimInputProperty::RESOLVED_NOT_SAVED;
}
if( m_currentScalarIndex != cvf::UNDEFINED_SIZE_T &&
m_currentReservoir->reservoirData() &&
m_currentReservoir->reservoirData()->results(m_porosityModelEnum) )
{
m_currentReservoir->reservoirData()->results(m_porosityModelEnum)->recalculateMinMax(m_currentScalarIndex);
}
for (size_t i = 0; i < m_currentReservoir->reservoirViews.size(); ++i)
{
if (m_currentReservoir->reservoirViews[i])
{
m_currentReservoir->reservoirViews[i]->updateCurrentTimeStepAndRedraw();
}
}
}
return true;
}
return false;
}
private:
RimCase* m_currentReservoir;
std::vector< std::vector<double> >* m_scalarResultsToAdd;
size_t m_currentGridIndex;
size_t m_currentScalarIndex;
QString m_currentPropertyName;
std::vector<size_t> m_requestedTimesteps;
RifReaderInterface::PorosityModelResultType m_porosityModelEnum;
quint64 m_timeStepCountToRead;
quint64 m_bytesPerTimeStepToRead;
size_t m_currentTimeStepNumberToRead;
bool m_invalidDataDetected;
};
static bool RiaSetGridProperty_init = RiaSocketCommandFactory::instance()->registerCreator<RiaSetGridProperty>(RiaSetGridProperty::commandName());

View File

@@ -18,6 +18,7 @@ set(CPP_SOURCES
riGetCellCorners.cpp
riGetActiveCellCorners.cpp
riGetGridProperty.cpp
riSetGridProperty.cpp
)
if (${CMAKE_SYSTEM_NAME} MATCHES "Linux")
@@ -125,6 +126,7 @@ else()
"${CMAKE_CURRENT_BINARY_DIR}/riGetCellCorners.oct"
"${CMAKE_CURRENT_BINARY_DIR}/riGetActiveCellCorners.oct"
"${CMAKE_CURRENT_BINARY_DIR}/riGetGridProperty.oct"
"${CMAKE_CURRENT_BINARY_DIR}/riSetGridProperty.oct"
SOURCES ${CPP_SOURCES}
)

View File

@@ -0,0 +1,216 @@
#include <QtNetwork>
#include <octave/oct.h>
#include "riSettings.h"
void setEclipseProperty(const NDArray& propertyFrames, const QString &hostName, quint16 port,
const qint64& caseId, const qint64& gridIndex, QString propertyName, const int32NDArray& timeStepIndices, QString porosityModel)
{
QTcpSocket socket;
socket.connectToHost(hostName, port);
if (!socket.waitForConnected(riOctavePlugin::timeOutMilliSecs))
{
error((("Connection: ") + socket.errorString()).toLatin1().data());
return;
}
QDataStream socketStream(&socket);
socketStream.setVersion(riOctavePlugin::qtDataStreamVersion);
// Create command as a string with arguments , and send it:
QString command = QString("SetGridProperty %1 %2 %3 %4").arg(caseId).arg(gridIndex).arg(propertyName).arg(porosityModel);
for (int i = 0; i < timeStepIndices.length(); ++i)
{
if (i == 0) command += " ";
command += QString::number(static_cast<int>(timeStepIndices.elem(i)) - 1); // To make the index 0-based
if (i != timeStepIndices.length() -1) command += " ";
}
QByteArray cmdBytes = command.toLatin1();
socketStream << (qint64)(cmdBytes.size());
socket.write(cmdBytes);
// Write property data header
dim_vector mxDims = propertyFrames.dims();
qint64 cellCountI = mxDims.elem(0);
qint64 cellCountJ = mxDims.elem(1);
qint64 cellCountK = mxDims.elem(2);
qint64 timeStepCount = mxDims.elem(3);
qint64 singleTimeStepByteCount = cellCountI * cellCountJ * cellCountK * sizeof(double);
//octave_stdout << " Cell count I: " << cellCountI << " Cell count J: " << cellCountJ << " Cell count K: " << cellCountK << std::endl;
//octave_stdout << " Time step count: " << timeStepCount << std::endl;
socketStream << (qint64)(cellCountI);
socketStream << (qint64)(cellCountJ);
socketStream << (qint64)(cellCountK);
socketStream << (qint64)(timeStepCount);
socketStream << (qint64)singleTimeStepByteCount;
const double* internalData = propertyFrames.fortran_vec();
int dataWritten = socket.write((const char *)internalData, singleTimeStepByteCount*timeStepCount);
if (dataWritten == singleTimeStepByteCount*timeStepCount)
{
QString tmp = QString("riSetGridProperty : Wrote %1").arg(propertyName);
if (caseId == -1)
{
tmp += QString(" to current case.");
}
else
{
tmp += QString(" to case with Id = %1.").arg(caseId);
}
}
else
{
size_t cellCount = cellCountI * cellCountJ * cellCountK;
error("riSetGridProperty : Was not able to write the proper amount of data to ResInsight:");
octave_stdout << " Cell count : " << cellCount << "Time steps : " << timeStepCount << " Data Written: " << dataWritten << " Should have written: " << timeStepCount * cellCount * sizeof(double) << std::endl;
}
while(socket.bytesToWrite() && socket.state() == QAbstractSocket::ConnectedState)
{
// octave_stdout << "Bytes to write: " << socket.bytesToWrite() << std::endl;
socket.waitForBytesWritten(riOctavePlugin::timeOutMilliSecs);
OCTAVE_QUIT;
}
if (socket.bytesToWrite() && socket.state() != QAbstractSocket::ConnectedState)
{
error("riSetActiveCellProperty : ResInsight refused to accept the data. Maybe the dimensions or porosity model is wrong.\n");
}
return;
}
DEFUN_DLD (riSetGridProperty, args, nargout,
"Usage:\n"
"\n"
"\triSetGridProperty( Matrix[numI][numJ][numK][numTimeSteps], [CaseId], GridIndex, PropertyName, [TimeStepIndices], [PorosityModel = \"Matrix\"|\"Fracture\"] ) \n"
"\n"
"Interprets the supplied matrix as a property set defined for all cells in one of the grids in a case, and puts the data into ResInsight as a \"Generated\" property with the name \"PropertyName\".\n"
"If the CaseId is not defined, ResInsights Current Case is used.\n"
)
{
int nargin = args.length ();
if (nargin < 2)
{
error("riSetGridProperty: Too few arguments, required input parameters are the data matrix, grid index and property name.\n");
print_usage();
return octave_value_list ();
}
if (nargin > 6)
{
error("riSetGridProperty: Too many arguments.\n");
print_usage();
return octave_value_list ();
}
NDArray propertyFrames = args(0).array_value();
if (error_state)
{
error("riSetGridProperty: The supplied first argument is not a valid Matrix");
print_usage();
return octave_value_list ();
}
dim_vector mxDims = propertyFrames.dims();
if (mxDims.length() != 4)
{
error("riSetGridProperty: The supplied Data Matrix must have four dimensions: numI*numJ*numK*numTimeSteps");
print_usage();
return octave_value_list ();
}
std::vector<int> argIndices;
argIndices.push_back(0);
argIndices.push_back(1);
argIndices.push_back(2);
argIndices.push_back(3);
argIndices.push_back(4);
argIndices.push_back(5);
// Check if we have a CaseId:
if (!args(argIndices[1]).is_numeric_type())
{
argIndices[1] = -1;
for (size_t aIdx = 2; aIdx < argIndices.size(); ++aIdx)
--argIndices[aIdx];
}
// Check if we have a Requested TimeSteps
if (!(nargin > argIndices[4] && args(argIndices[4]).is_matrix_type()))
{
argIndices[4] = -1;
for (size_t aIdx = 5; aIdx < argIndices.size(); ++aIdx)
--argIndices[aIdx];
}
// Check if we have a PorosityModel
int lastArgumentIndex = argIndices[5] ;
if (!(nargin > argIndices[5] && args(argIndices[5]).is_string()))
{
argIndices[5] = -1;
for (size_t aIdx = 6; aIdx < argIndices.size(); ++aIdx)
--argIndices[aIdx];
}
// Check if we have more arguments than we should
if (nargin > lastArgumentIndex + 1)
{
error("riSetGridProperty: Unexpected argument after the PorosityModel.\n");
print_usage();
return octave_value_list ();
}
int caseId = -1;
int gridIndex = 0;
std::string propertyName = "UNDEFINED";
int32NDArray timeStepIndices;
std::string porosityModel = "Matrix";
if (argIndices[1] >= 0) caseId = args(argIndices[1]).int_value();
if (argIndices[2] >= 0) gridIndex = args(argIndices[2]).int_value();
if (argIndices[3] >= 0) propertyName = args(argIndices[3]).char_matrix_value().row_as_string(0);
if (argIndices[4] >= 0) timeStepIndices = args(argIndices[4]).int32_array_value();
if (argIndices[5] >= 0) porosityModel = args(argIndices[5]).string_value();
if (timeStepIndices.length())
{
int timeStepCount = mxDims.elem(1);
if (timeStepIndices.length() != timeStepCount)
{
error("riSetGridProperty: The number of time steps in the input matrix must match the number of time steps in the TimeStepIndices array.");
print_usage();
return octave_value_list ();
}
}
if (porosityModel != "Matrix" && porosityModel != "Fracture")
{
error("riSetActiveCellProperty: The value for \"PorosityModel\" is unknown. Please use either \"Matrix\" or \"Fracture\"\n");
print_usage();
return octave_value_list ();
}
setEclipseProperty(propertyFrames, "127.0.0.1", 40001, caseId, gridIndex, propertyName.c_str(), timeStepIndices, porosityModel.c_str());
return octave_value_list ();
}