Merge pull request #52 from OPM/internal

Update to 0.9.26
This commit is contained in:
Magne Sjaastad 2013-09-09 05:56:27 -07:00
commit 3097c3fe5d
269 changed files with 11203 additions and 6297 deletions

View File

@ -154,6 +154,7 @@ RiaApplication::RiaApplication(int& argc, char** argv)
// The creation of a font is time consuming, so make sure you really need your own font
// instead of using the application font
m_standardFont = new cvf::FixedAtlasFont(cvf::FixedAtlasFont::STANDARD);
m_resViewUpdateTimer = NULL;
}
@ -1612,3 +1613,68 @@ QString RiaApplication::commandLineParameterHelp() const
return text;
}
//--------------------------------------------------------------------------------------------------
/// Schedule a creation of the Display model and redraw of the reservoir view
/// The redraw will happen as soon as the event loop is entered
//--------------------------------------------------------------------------------------------------
void RiaApplication::scheduleDisplayModelUpdateAndRedraw(RimReservoirView* resViewToUpdate)
{
m_resViewsToUpdate.push_back(resViewToUpdate);
if (!m_resViewUpdateTimer)
{
m_resViewUpdateTimer = new QTimer(this);
connect(m_resViewUpdateTimer, SIGNAL(timeout()), this, SLOT(slotUpdateScheduledDisplayModels()));
}
if (!m_resViewUpdateTimer->isActive())
{
m_resViewUpdateTimer->setSingleShot(true);
m_resViewUpdateTimer->start(0);
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaApplication::slotUpdateScheduledDisplayModels()
{
// Compress to remove duplicates
std::set<RimReservoirView*> resViewsToUpdate;
for (size_t i = 0; i < m_resViewsToUpdate.size(); ++i)
{
resViewsToUpdate.insert(m_resViewsToUpdate[i]);
}
for (std::set<RimReservoirView*>::iterator it = resViewsToUpdate.begin(); it != resViewsToUpdate.end(); ++it )
{
if (*it)
{
(*it)->createDisplayModelAndRedraw();
}
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaApplication::setCacheDataObject(const QString& key, const QVariant& dataObject)
{
m_sessionCache[key] = dataObject;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QVariant RiaApplication::cacheDataObject(const QString& key) const
{
QMap<QString, QVariant>::const_iterator it = m_sessionCache.find(key);
if (it != m_sessionCache.end())
{
return it.value();
}
return QVariant();
}

View File

@ -68,6 +68,8 @@ public:
RimReservoirView* activeReservoirView();
const RimReservoirView* activeReservoirView() const;
void scheduleDisplayModelUpdateAndRedraw(RimReservoirView* resViewToUpdate);
RimProject* project();
void createMockModel();
@ -128,6 +130,9 @@ public:
QString commandLineParameterHelp() const;
void showFormattedTextInMessageBox(const QString& text);
void setCacheDataObject(const QString& key, const QVariant& dataObject);
QVariant cacheDataObject(const QString& key) const;
private:
void onProjectOpenedOrClosed();
void setWindowCaptionFromAppState();
@ -137,11 +142,15 @@ private:
private slots:
void slotWorkerProcessFinished(int exitCode, QProcess::ExitStatus exitStatus);
void slotUpdateScheduledDisplayModels();
private:
caf::PdmPointer<RimReservoirView> m_activeReservoirView;
caf::PdmPointer<RimProject> m_project;
std::vector<caf::PdmPointer<RimReservoirView> > m_resViewsToUpdate;
QTimer* m_resViewUpdateTimer;
RiaSocketServer* m_socketServer;
caf::UiProcess* m_workerProcess;
@ -151,11 +160,12 @@ private:
QString m_currentProgram;
QStringList m_currentArguments;
RiaPreferences* m_preferences;
std::map<QString, QString> m_fileDialogDefaultDirectories;
QString m_startupDefaultDirectory;
cvf::ref<cvf::Font> m_standardFont;
QMap<QString, QVariant> m_sessionCache; // Session cache used to store username/passwords per session
};

View File

@ -19,6 +19,7 @@ include_directories(
${CMAKE_CURRENT_SOURCE_DIR}/UserInterface
${CMAKE_CURRENT_SOURCE_DIR}/ProjectDataModel
${CMAKE_CURRENT_SOURCE_DIR}/ReservoirDataModel
${CMAKE_CURRENT_SOURCE_DIR}/WellPathImportSsihub
${CMAKE_BINARY_DIR}/Generated
${CMAKE_CURRENT_BINARY_DIR}
)
@ -54,6 +55,7 @@ set( SOCKET_INTERFACE_FILES
SocketInterface/RiaCaseInfoCommands.cpp
SocketInterface/RiaGeometryCommands.cpp
SocketInterface/RiaPropertyDataCommands.cpp
SocketInterface/RiaWellDataCommands.cpp
SocketInterface/RiaSocketTools.cpp
)
@ -82,7 +84,7 @@ list( APPEND CPP_SOURCES
${CODE_SOURCE_FILES}
)
add_subdirectory(ssihubInterface)
add_subdirectory(WellPathImportSsihub)
# Define files for MOC-ing
@ -217,6 +219,8 @@ add_executable( ResInsight ${EXE_FILES} )
set( LINK_LIBRARIES
WellPathImportSsihub
cafPdmCvf
cafUserInterface
cafProjectDataModel
@ -229,8 +233,6 @@ set( LINK_LIBRARIES
LibGeometry
LibCore
ssihubInterface
ecl
ert_util
ert_geometry
@ -275,50 +277,50 @@ set (RESINSIGHT_LICENSE_FILES
)
# bundle libraries together with private installation
if (PRIVATE_INSTALL)
if (RESINSIGHT_PRIVATE_INSTALL)
if (${CMAKE_SYSTEM_NAME} MATCHES "Linux")
# tell binary to first attempt to load libraries from its own directory
set_target_properties (ResInsight PROPERTIES INSTALL_RPATH "\$ORIGIN")
if (${CMAKE_SYSTEM_NAME} MATCHES "Linux")
# tell binary to first attempt to load libraries from its own directory
set_target_properties (ResInsight PROPERTIES INSTALL_RPATH "\$ORIGIN")
# Find Qt libraries and sym links
file (GLOB RESINSIGHT_FILES
${QT_LIBRARY_DIR}/libQtCore.so*
${QT_LIBRARY_DIR}/libQtGui.so*
${QT_LIBRARY_DIR}/libQtOpenGL.so*
${QT_LIBRARY_DIR}/libQtNetwork.so*
${QT_LIBRARY_DIR}/libQtScript.so*
${QT_LIBRARY_DIR}/libQtScriptTools.so*
)
# Find Qt libraries and sym links
file (GLOB RESINSIGHT_FILES
${QT_LIBRARY_DIR}/libQtCore.so*
${QT_LIBRARY_DIR}/libQtGui.so*
${QT_LIBRARY_DIR}/libQtOpenGL.so*
${QT_LIBRARY_DIR}/libQtNetwork.so*
${QT_LIBRARY_DIR}/libQtScript.so*
${QT_LIBRARY_DIR}/libQtScriptTools.so*
)
endif()
endif()
if (${CMAKE_SYSTEM_NAME} MATCHES "Windows")
# put a .exe.local file in the target directory to pick up DLLs from there
install (CODE "exec_program (${CMAKE_COMMAND} ARGS -E touch \$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}${RESINSIGHT_FINAL_NAME}/ResInsight${CMAKE_EXECUTABLE_SUFFIX}.local)")
if (${CMAKE_SYSTEM_NAME} MATCHES "Windows")
# put a .exe.local file in the target directory to pick up DLLs from there
install (CODE "exec_program (${CMAKE_COMMAND} ARGS -E touch \$ENV{DESTDIR}${CMAKE_INSTALL_PREFIX}${RESINSIGHT_FINAL_NAME}/ResInsight${CMAKE_EXECUTABLE_SUFFIX}.local)")
set (RESINSIGHT_FILES
${QT_BINARY_DIR}/QtCore4.dll
${QT_BINARY_DIR}/QtGui4.dll
${QT_BINARY_DIR}/QtOpenGL4.dll
${QT_BINARY_DIR}/QtNetwork4.dll
${QT_BINARY_DIR}/QtScript4.dll
${QT_BINARY_DIR}/QtScriptTools4.dll
)
endif()
set (RESINSIGHT_FILES
${QT_BINARY_DIR}/QtCore4.dll
${QT_BINARY_DIR}/QtGui4.dll
${QT_BINARY_DIR}/QtOpenGL4.dll
${QT_BINARY_DIR}/QtNetwork4.dll
${QT_BINARY_DIR}/QtScript4.dll
${QT_BINARY_DIR}/QtScriptTools4.dll
)
endif()
set (RESINSIGHT_FILES ${RESINSIGHT_FILES} ${RESINSIGHT_LICENSE_FILES})
set (RESINSIGHT_FILES ${RESINSIGHT_FILES} ${RESINSIGHT_LICENSE_FILES})
install(TARGETS ResInsight DESTINATION ${RESINSIGHT_FINAL_NAME})
install(TARGETS ResInsight DESTINATION ${RESINSIGHT_FINAL_NAME})
install(FILES ${RESINSIGHT_FILES} DESTINATION ${RESINSIGHT_FINAL_NAME} )
install(FILES ${RESINSIGHT_FILES} DESTINATION ${RESINSIGHT_FINAL_NAME} )
if (${CMAKE_SYSTEM_NAME} MATCHES "Linux")
install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/resinsight DESTINATION ${RESINSIGHT_FINAL_NAME} PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE )
endif()
if (${CMAKE_SYSTEM_NAME} MATCHES "Linux")
install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/resinsight DESTINATION ${RESINSIGHT_FINAL_NAME} PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE )
endif()
else (PRIVATE_INSTALL)
else (RESINSIGHT_PRIVATE_INSTALL)
# binaries go in /usr/bin
install (TARGETS ResInsight
DESTINATION bin
@ -343,4 +345,4 @@ else (PRIVATE_INSTALL)
install (FILES ${CMAKE_CURRENT_BINARY_DIR}/resinsight.desktop
DESTINATION share/applications
)
endif (PRIVATE_INSTALL)
endif (RESINSIGHT_PRIVATE_INSTALL)

View File

@ -154,9 +154,9 @@ bool transferGridCellData(RigMainGrid* mainGrid, RigActiveCellInfo* activeCellIn
const ecl_grid_type* subGrid = ecl_grid_get_cell_lgr1(localEclGrid, localCellIdx);
if (subGrid != NULL)
{
int subGridFileIndex = ecl_grid_get_lgr_nr(subGrid);
CVF_ASSERT(subGridFileIndex > 0);
cell.setSubGrid(static_cast<RigLocalGrid*>(mainGrid->gridByIndex(subGridFileIndex)));
int subGridId = ecl_grid_get_lgr_nr(subGrid);
CVF_ASSERT(subGridId > 0);
cell.setSubGrid(static_cast<RigLocalGrid*>(mainGrid->gridById(subGridId)));
}
// Mark inactive long pyramid looking cells as invalid
@ -260,12 +260,15 @@ bool RifReaderEclipseOutput::transferGeometry(const ecl_grid_type* mainEclGrid,
ecl_grid_type* localEclGrid = ecl_grid_iget_lgr(mainEclGrid, lgrIdx);
std::string lgrName = ecl_grid_get_name(localEclGrid);
int lgrId = ecl_grid_get_lgr_nr(localEclGrid);
cvf::Vec3st gridPointDim(0,0,0);
gridPointDim.x() = ecl_grid_get_nx(localEclGrid) + 1;
gridPointDim.y() = ecl_grid_get_ny(localEclGrid) + 1;
gridPointDim.z() = ecl_grid_get_nz(localEclGrid) + 1;
RigLocalGrid* localGrid = new RigLocalGrid(mainGrid);
localGrid->setGridId(lgrId);
mainGrid->addLocalGrid(localGrid);
localGrid->setIndexToStartOfCells(totalCellCount);

View File

@ -218,7 +218,7 @@ void RivReservoirViewPartMgr::appendDynamicGeometryPartsToModel(cvf::ModelBasicL
{
if (frameIndex >= m_propFilteredGeometryFramesNeedsRegen.size() || m_propFilteredGeometryFramesNeedsRegen[frameIndex])
{
createPropertyFilteredGeometry(frameIndex);
createPropertyFilteredNoneWellCellGeometry(frameIndex);
}
m_propFilteredGeometryFrames[frameIndex]->appendPartsToModel(model, gridIndices);
}
@ -381,7 +381,7 @@ void RivReservoirViewPartMgr::computeVisibility(cvf::UByteArray* cellVisibility,
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RivReservoirViewPartMgr::createPropertyFilteredGeometry(size_t frameIndex)
void RivReservoirViewPartMgr::createPropertyFilteredNoneWellCellGeometry(size_t frameIndex)
{
RigCaseData* res = m_reservoirView->eclipseCase()->reservoirData();
@ -390,13 +390,17 @@ void RivReservoirViewPartMgr::createPropertyFilteredGeometry(size_t frameIndex)
m_propFilteredGeometryFrames.resize(frameIndex + 1);
m_propFilteredGeometryFramesNeedsRegen.resize(frameIndex + 1, true);
}
if ( m_propFilteredGeometryFrames[frameIndex].isNull()) m_propFilteredGeometryFrames[frameIndex] = new RivReservoirPartMgr;
m_propFilteredGeometryFrames[frameIndex]->clearAndSetReservoir(res);
m_propFilteredGeometryFrames[frameIndex]->setTransform(m_scaleTransform.p());
std::vector<RigGridBase*> grids;
res->allGrids(&grids);
bool hasActiveRangeFilters = m_reservoirView->rangeFilterCollection()->hasActiveIncludeFilters() || m_reservoirView->wellCollection()->hasVisibleWellCells();
bool hasActiveRangeFilters = m_reservoirView->rangeFilterCollection()->hasActiveFilters();
bool hasVisibleWellCells = m_reservoirView->wellCollection()->hasVisibleWellCells();
for (size_t gIdx = 0; gIdx < grids.size(); ++gIdx)
{
@ -405,11 +409,35 @@ void RivReservoirViewPartMgr::createPropertyFilteredGeometry(size_t frameIndex)
cvf::ref<cvf::UByteArray> fenceVisibility;
cvf::cref<cvf::UByteArray> isWellCell = res->wellCellsInGrid(gIdx);
if (m_geometriesNeedsRegen[RANGE_FILTERED]) createGeometry(RANGE_FILTERED);
if (m_geometriesNeedsRegen[VISIBLE_WELL_FENCE_CELLS_OUTSIDE_RANGE_FILTER]) createGeometry(VISIBLE_WELL_FENCE_CELLS_OUTSIDE_RANGE_FILTER);
if (hasActiveRangeFilters && hasVisibleWellCells)
{
if (m_geometriesNeedsRegen[RANGE_FILTERED]) createGeometry(RANGE_FILTERED);
if (m_geometriesNeedsRegen[VISIBLE_WELL_FENCE_CELLS_OUTSIDE_RANGE_FILTER]) createGeometry(VISIBLE_WELL_FENCE_CELLS_OUTSIDE_RANGE_FILTER);
rangeVisibility = m_geometries[RANGE_FILTERED].cellVisibility(gIdx);
fenceVisibility = m_geometries[VISIBLE_WELL_FENCE_CELLS_OUTSIDE_RANGE_FILTER].cellVisibility(gIdx);
rangeVisibility = m_geometries[RANGE_FILTERED].cellVisibility(gIdx);
fenceVisibility = m_geometries[VISIBLE_WELL_FENCE_CELLS_OUTSIDE_RANGE_FILTER].cellVisibility(gIdx);
}
else if (hasActiveRangeFilters && !hasVisibleWellCells)
{
if (m_geometriesNeedsRegen[RANGE_FILTERED]) createGeometry(RANGE_FILTERED);
rangeVisibility = m_geometries[RANGE_FILTERED].cellVisibility(gIdx);
fenceVisibility = m_geometries[RANGE_FILTERED].cellVisibility(gIdx);
}
else if (!hasActiveRangeFilters && hasVisibleWellCells)
{
if (m_geometriesNeedsRegen[VISIBLE_WELL_FENCE_CELLS]) createGeometry(VISIBLE_WELL_FENCE_CELLS);
rangeVisibility = m_geometries[VISIBLE_WELL_FENCE_CELLS].cellVisibility(gIdx);
fenceVisibility = m_geometries[VISIBLE_WELL_FENCE_CELLS].cellVisibility(gIdx);
}
else if (!hasActiveRangeFilters && !hasVisibleWellCells)
{
if (m_geometriesNeedsRegen[ACTIVE]) createGeometry(ACTIVE);
rangeVisibility = m_geometries[ACTIVE].cellVisibility(gIdx);
fenceVisibility = m_geometries[ACTIVE].cellVisibility(gIdx);
}
cellVisibility->resize(rangeVisibility->size());
@ -418,6 +446,7 @@ void RivReservoirViewPartMgr::createPropertyFilteredGeometry(size_t frameIndex)
{
(*cellVisibility)[cellIdx] = (*rangeVisibility)[cellIdx] || (*fenceVisibility)[cellIdx];
}
computePropertyVisibility(cellVisibility.p(), grids[gIdx], frameIndex, cellVisibility.p(), m_reservoirView->propertyFilterCollection());
m_propFilteredGeometryFrames[frameIndex]->setCellVisibility(gIdx, cellVisibility.p());
@ -447,29 +476,63 @@ void RivReservoirViewPartMgr::createPropertyFilteredWellGeometry(size_t frameInd
std::vector<RigGridBase*> grids;
res->allGrids(&grids);
bool hasActiveRangeFilters = m_reservoirView->rangeFilterCollection()->hasActiveFilters() || m_reservoirView->wellCollection()->hasVisibleWellCells();
bool hasActiveRangeFilters = m_reservoirView->rangeFilterCollection()->hasActiveFilters();
bool hasVisibleWellCells = m_reservoirView->wellCollection()->hasVisibleWellCells();
for (size_t gIdx = 0; gIdx < grids.size(); ++gIdx)
{
cvf::ref<cvf::UByteArray> cellVisibility = m_propFilteredWellGeometryFrames[frameIndex]->cellVisibility(gIdx);
cvf::ref<cvf::UByteArray> rangeVisibility;
cvf::ref<cvf::UByteArray> wellCellsOutsideVisibility;
cvf::cref<cvf::UByteArray> cellIsWellCellStatuses = res->wellCellsInGrid(gIdx);
cvf::ref<cvf::UByteArray> wellCellsOutsideRange;
cvf::ref<cvf::UByteArray> wellFenceCells;
if (hasActiveRangeFilters && hasVisibleWellCells)
{
if (m_geometriesNeedsRegen[RANGE_FILTERED_WELL_CELLS]) createGeometry(RANGE_FILTERED_WELL_CELLS);
rangeVisibility = m_geometries[RANGE_FILTERED_WELL_CELLS].cellVisibility(gIdx);
if (m_geometriesNeedsRegen[RANGE_FILTERED_WELL_CELLS]) createGeometry(RANGE_FILTERED_WELL_CELLS);
rangeVisibility = m_geometries[RANGE_FILTERED_WELL_CELLS].cellVisibility(gIdx);
if (m_geometriesNeedsRegen[VISIBLE_WELL_CELLS_OUTSIDE_RANGE_FILTER]) createGeometry(VISIBLE_WELL_CELLS_OUTSIDE_RANGE_FILTER);
wellCellsOutsideRange = m_geometries[VISIBLE_WELL_CELLS_OUTSIDE_RANGE_FILTER].cellVisibility(gIdx);
if (m_geometriesNeedsRegen[VISIBLE_WELL_CELLS_OUTSIDE_RANGE_FILTER]) createGeometry(VISIBLE_WELL_CELLS_OUTSIDE_RANGE_FILTER);
wellCellsOutsideVisibility = m_geometries[VISIBLE_WELL_CELLS_OUTSIDE_RANGE_FILTER].cellVisibility(gIdx);
if (m_geometriesNeedsRegen[VISIBLE_WELL_FENCE_CELLS_OUTSIDE_RANGE_FILTER]) createGeometry(VISIBLE_WELL_FENCE_CELLS_OUTSIDE_RANGE_FILTER);
wellFenceCells = m_geometries[VISIBLE_WELL_FENCE_CELLS_OUTSIDE_RANGE_FILTER].cellVisibility(gIdx);
}
else if (hasActiveRangeFilters && !hasVisibleWellCells)
{
if (m_geometriesNeedsRegen[RANGE_FILTERED_WELL_CELLS]) createGeometry(RANGE_FILTERED_WELL_CELLS);
rangeVisibility = m_geometries[RANGE_FILTERED_WELL_CELLS].cellVisibility(gIdx);
wellCellsOutsideRange = rangeVisibility;
wellFenceCells = rangeVisibility;
}
else if (!hasActiveRangeFilters && hasVisibleWellCells)
{
if (m_geometriesNeedsRegen[VISIBLE_WELL_CELLS]) createGeometry(VISIBLE_WELL_CELLS);
wellCellsOutsideRange = m_geometries[VISIBLE_WELL_CELLS].cellVisibility(gIdx);
if (m_geometriesNeedsRegen[VISIBLE_WELL_FENCE_CELLS]) createGeometry(VISIBLE_WELL_FENCE_CELLS);
wellFenceCells = m_geometries[VISIBLE_WELL_FENCE_CELLS].cellVisibility(gIdx);
rangeVisibility = wellCellsOutsideRange;
}
else if (!hasActiveRangeFilters && !hasVisibleWellCells)
{
if (m_geometriesNeedsRegen[ALL_WELL_CELLS]) createGeometry(ALL_WELL_CELLS);
wellFenceCells = m_geometries[ALL_WELL_CELLS].cellVisibility(gIdx);
wellCellsOutsideRange = wellFenceCells;
rangeVisibility = wellFenceCells;
}
cellVisibility->resize(rangeVisibility->size());
#pragma omp parallel for
for (int cellIdx = 0; cellIdx < static_cast<int>(cellVisibility->size()); ++cellIdx)
{
(*cellVisibility)[cellIdx] = (!hasActiveRangeFilters && (*cellIsWellCellStatuses)[cellIdx]) || (*rangeVisibility)[cellIdx] || (*wellCellsOutsideVisibility)[cellIdx];
(*cellVisibility)[cellIdx] = (*wellFenceCells)[cellIdx] || (*rangeVisibility)[cellIdx] || (*wellCellsOutsideRange)[cellIdx];
}
computePropertyVisibility(cellVisibility.p(), grids[gIdx], frameIndex, cellVisibility.p(), m_reservoirView->propertyFilterCollection());
m_propFilteredWellGeometryFrames[frameIndex]->setCellVisibility(gIdx, cellVisibility.p());
}

View File

@ -39,18 +39,18 @@ public:
enum ReservoirGeometryCacheType
{
ACTIVE,
ALL_WELL_CELLS,
VISIBLE_WELL_CELLS,
VISIBLE_WELL_FENCE_CELLS,
INACTIVE,
RANGE_FILTERED,
RANGE_FILTERED_INACTIVE,
RANGE_FILTERED_WELL_CELLS,
VISIBLE_WELL_CELLS_OUTSIDE_RANGE_FILTER,
VISIBLE_WELL_FENCE_CELLS_OUTSIDE_RANGE_FILTER,
PROPERTY_FILTERED,
PROPERTY_FILTERED_WELL_CELLS // Includes RANGE_FILTERED_WELL_CELLS and VISIBLE_WELL_CELLS_OUTSIDE_RANGE_FILTER and VISIBLE_WELL_FENCE_CELLS_OUTSIDE_RANGE_FILTER
ACTIVE, ///< All Active cells without ALL_WELL_CELLS
ALL_WELL_CELLS, ///< All cells ever having a connection to a well (Might be inactive cells as well. Wellhead cells typically)
VISIBLE_WELL_CELLS, ///< ALL_WELL_CELLS && visible well cells including Fence
VISIBLE_WELL_FENCE_CELLS, ///< (! ALL_WELL_CELLS) && visible well cells including Fence
INACTIVE, ///< All inactive cells, but invalid cells might or might not be included
RANGE_FILTERED, ///< ACTIVE Filtered by the set of range filters
RANGE_FILTERED_INACTIVE, ///< INACTIVE Filtered by the set of range filters
RANGE_FILTERED_WELL_CELLS, ///< ALL_WELL_CELLS Filtered by the set of range filters
VISIBLE_WELL_CELLS_OUTSIDE_RANGE_FILTER, ///< VISIBLE_WELL_CELLS && !RANGE_FILTERED_WELL_CELLS
VISIBLE_WELL_FENCE_CELLS_OUTSIDE_RANGE_FILTER, ///< VISIBLE_WELL_FENCE_CELLS && !RANGE_FILTERED
PROPERTY_FILTERED, ///< (RANGE_FILTERED || VISIBLE_WELL_FENCE_CELLS_OUTSIDE_RANGE_FILTER) && !ExcludedByPropFilter && IncludedByPropFilter
PROPERTY_FILTERED_WELL_CELLS ///< (!(hasActiveRangeFilters || visibleWellCells) && (*ALL_WELL_CELLS)) || RANGE_FILTERED_WELL_CELLS || VISIBLE_WELL_CELLS_OUTSIDE_RANGE_FILTER
};
void clearGeometryCache();
@ -72,7 +72,7 @@ private:
void createGeometry(ReservoirGeometryCacheType geometryType);
void computeVisibility(cvf::UByteArray* cellVisibility, ReservoirGeometryCacheType geometryType, RigGridBase* grid, size_t gridIdx);
void createPropertyFilteredGeometry(size_t frameIndex);
void createPropertyFilteredNoneWellCellGeometry(size_t frameIndex);
void createPropertyFilteredWellGeometry(size_t frameIndex);
void clearGeometryCache(ReservoirGeometryCacheType geomType);

View File

@ -49,6 +49,8 @@ RimCellPropertyFilter::RimCellPropertyFilter()
CAF_PDM_InitObject("Cell Property Filter", ":/CellFilter_Values.png", "", "");
CAF_PDM_InitFieldNoDefault(&evaluationRegion, "EvaluationRegion", "Evaluation region", "", "", "");
evaluationRegion.setUiHidden(true);
evaluationRegion.setIOWritable(false);
CAF_PDM_InitFieldNoDefault(&resultDefinition, "ResultDefinition", "Result definition", "", "", "");
resultDefinition = new RimResultDefinition();

View File

@ -42,8 +42,8 @@ RimCellRangeFilterCollection::RimCellRangeFilterCollection()
CAF_PDM_InitObject("Cell Range Filters", ":/CellFilter_Range.png", "", "");
CAF_PDM_InitFieldNoDefault(&rangeFilters, "RangeFilters", "Range Filters", "", "", "");
CAF_PDM_InitField(&active, "Active", true, "Active", "", "", "");
active.setUiHidden(true);
CAF_PDM_InitField(&isActive, "Active", true, "Active", "", "", "");
isActive.setUiHidden(true);
}
//--------------------------------------------------------------------------------------------------
@ -146,14 +146,14 @@ RigActiveCellInfo* RimCellRangeFilterCollection::activeCellInfo() const
//--------------------------------------------------------------------------------------------------
void RimCellRangeFilterCollection::fieldChangedByUi(const caf::PdmFieldHandle* changedField, const QVariant& oldValue, const QVariant& newValue)
{
updateUiIconFromState(active);
updateUiIconFromState(isActive);
CVF_ASSERT(m_reservoirView);
m_reservoirView->scheduleGeometryRegen(RivReservoirViewPartMgr::RANGE_FILTERED);
m_reservoirView->scheduleGeometryRegen(RivReservoirViewPartMgr::RANGE_FILTERED_INACTIVE);
m_reservoirView->createDisplayModelAndRedraw();
m_reservoirView->scheduleCreateDisplayModelAndRedraw();
}
@ -209,7 +209,7 @@ void RimCellRangeFilterCollection::remove(RimCellRangeFilter* rangeFilter)
//--------------------------------------------------------------------------------------------------
bool RimCellRangeFilterCollection::hasActiveFilters() const
{
if (!active) return false;
if (!isActive()) return false;
std::list< caf::PdmPointer< RimCellRangeFilter > >::const_iterator it;
for (it = rangeFilters.v().begin(); it != rangeFilters.v().end(); ++it)
@ -225,7 +225,7 @@ bool RimCellRangeFilterCollection::hasActiveFilters() const
//--------------------------------------------------------------------------------------------------
caf::PdmFieldHandle* RimCellRangeFilterCollection::objectToggleField()
{
return &active;
return &isActive;
}
//--------------------------------------------------------------------------------------------------
@ -233,7 +233,7 @@ caf::PdmFieldHandle* RimCellRangeFilterCollection::objectToggleField()
//--------------------------------------------------------------------------------------------------
bool RimCellRangeFilterCollection::hasActiveIncludeFilters() const
{
if (!active) return false;
if (!isActive) return false;
std::list< caf::PdmPointer< RimCellRangeFilter > >::const_iterator it;
for (it = rangeFilters.v().begin(); it != rangeFilters.v().end(); ++it)

View File

@ -35,7 +35,7 @@ public:
virtual ~RimCellRangeFilterCollection();
// Fields
caf::PdmField<bool> active;
caf::PdmField<bool> isActive;
caf::PdmField< std::list< caf::PdmPointer< RimCellRangeFilter > > > rangeFilters;
// Methods

View File

@ -71,6 +71,10 @@ RimProject::RimProject(void)
CAF_PDM_InitFieldNoDefault(&treeViewState, "TreeViewState", "", "", "", "");
treeViewState.setUiHidden(true);
CAF_PDM_InitFieldNoDefault(&wellPathImport, "WellPathImport", "WellPathImport", "", "", "");
wellPathImport = new RimWellPathImport();
wellPathImport.setUiHidden(true);
CAF_PDM_InitFieldNoDefault(&currentModelIndexPath, "TreeViewCurrentModelIndexPath", "", "", "", "");
currentModelIndexPath.setUiHidden(true);
@ -115,6 +119,8 @@ void RimProject::close()
casesObsolete.deleteAllChildObjects();
caseGroupsObsolete.deleteAllChildObjects();
wellPathImport = new RimWellPathImport();
fileName = "";
nextValidCaseId = 0;
@ -410,7 +416,7 @@ void RimProject::createDisplayModelAndRedrawAllViews()
for (size_t viewIdx = 0; viewIdx < rimCase->reservoirViews.size(); viewIdx++)
{
RimReservoirView* reservoirView = rimCase->reservoirViews[viewIdx];
reservoirView->createDisplayModelAndRedraw();
reservoirView->scheduleCreateDisplayModelAndRedraw();
}
}
}
@ -429,9 +435,8 @@ RimOilField* RimProject::activeOilField()
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RimProject::computeUtmAreaOfInterest(double* north, double* south, double* east, double* west)
void RimProject::computeUtmAreaOfInterest()
{
CVF_ASSERT(north && south && east && west);
std::vector<RimCase*> cases;
allCases(cases);
@ -454,11 +459,18 @@ void RimProject::computeUtmAreaOfInterest(double* north, double* south, double*
if (projectBB.isValid())
{
*north = projectBB.max().y();
*south = projectBB.min().y();
double north, south, east, west;
*west = projectBB.min().x();
*east = projectBB.max().x();
north = projectBB.max().y();
south = projectBB.min().y();
west = projectBB.min().x();
east = projectBB.max().x();
wellPathImport->north = north;
wellPathImport->south = south;
wellPathImport->east = east;
wellPathImport->west = west;
}
}

View File

@ -19,6 +19,7 @@
#pragma once
#include "cafPdmDocument.h"
#include "RimWellPathImport.h"
class RimOilField;
class RimCase;
@ -43,6 +44,7 @@ public:
caf::PdmPointersField<RimOilField*> oilFields;
caf::PdmField<RimScriptCollection*> scriptCollection;
caf::PdmField<RimWellPathImport*> wellPathImport;
caf::PdmField<QString> treeViewState;
caf::PdmField<QString> currentModelIndexPath;
caf::PdmField<int> nextValidCaseId; // Unique case ID within a project, used to identify a case from Octave scripts
@ -62,7 +64,7 @@ public:
void allCases(std::vector<RimCase*>& cases); // VL endre impl
void createDisplayModelAndRedrawAllViews(); // VL endre impl
void computeUtmAreaOfInterest(double* north, double* south, double* east, double* west);
void computeUtmAreaOfInterest();
RimOilField* activeOilField();

View File

@ -311,6 +311,15 @@ void RimReservoirView::clampCurrentTimestep()
if (m_currentTimeStep < 0 ) m_currentTimeStep = 0;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RimReservoirView::scheduleCreateDisplayModelAndRedraw()
{
RiaApplication::instance()->scheduleDisplayModelUpdateAndRedraw(this);
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
@ -449,13 +458,13 @@ void RimReservoirView::fieldChangedByUi(const caf::PdmFieldHandle* changedField,
m_reservoirGridPartManager->scheduleGeometryRegen(RivReservoirViewPartMgr::RANGE_FILTERED);
m_reservoirGridPartManager->scheduleGeometryRegen(RivReservoirViewPartMgr::RANGE_FILTERED_INACTIVE);
createDisplayModelAndRedraw();
scheduleCreateDisplayModelAndRedraw();
}
else if ( changedField == &propertyFilterCollection)
{
m_reservoirGridPartManager->scheduleGeometryRegen(RivReservoirViewPartMgr::PROPERTY_FILTERED);
createDisplayModelAndRedraw();
scheduleCreateDisplayModelAndRedraw();
}
else if (changedField == &meshMode)
{
@ -496,8 +505,9 @@ void RimReservoirView::createDisplayModel()
{
if (m_viewer.isNull()) return;
// static int callCount = 0;
// qDebug() << "RimReservoirView::createDisplayModel()" << callCount++;
//static int callCount = 0;
//std::cout << "RimReservoirView::createDisplayModel() " << callCount++ << std::endl;
//RiuMainWindow::instance()->setResultInfo(QString ("RimReservoirView::createDisplayModel() ") + QString::number(callCount++));
if (!(m_reservoir && m_reservoir->reservoirData())) return;
@ -560,8 +570,8 @@ void RimReservoirView::createDisplayModel()
if (! this->propertyFilterCollection()->hasActiveFilters())
{
std::vector<RivReservoirViewPartMgr::ReservoirGeometryCacheType> geometryTypesToAdd;
if (this->rangeFilterCollection()->hasActiveFilters() || this->wellCollection()->hasVisibleWellCells())
if (this->rangeFilterCollection()->hasActiveFilters() && this->wellCollection()->hasVisibleWellCells())
{
geometryTypesToAdd.push_back(RivReservoirViewPartMgr::RANGE_FILTERED);
geometryTypesToAdd.push_back(RivReservoirViewPartMgr::RANGE_FILTERED_WELL_CELLS);
@ -572,6 +582,20 @@ void RimReservoirView::createDisplayModel()
geometryTypesToAdd.push_back(RivReservoirViewPartMgr::RANGE_FILTERED_INACTIVE);
}
}
else if (!this->rangeFilterCollection()->hasActiveFilters() && this->wellCollection()->hasVisibleWellCells())
{
geometryTypesToAdd.push_back(RivReservoirViewPartMgr::VISIBLE_WELL_CELLS);
geometryTypesToAdd.push_back(RivReservoirViewPartMgr::VISIBLE_WELL_FENCE_CELLS);
}
else if (this->rangeFilterCollection()->hasActiveFilters() && !this->wellCollection()->hasVisibleWellCells())
{
geometryTypesToAdd.push_back(RivReservoirViewPartMgr::RANGE_FILTERED);
geometryTypesToAdd.push_back(RivReservoirViewPartMgr::RANGE_FILTERED_WELL_CELLS);
if (this->showInactiveCells())
{
geometryTypesToAdd.push_back(RivReservoirViewPartMgr::RANGE_FILTERED_INACTIVE);
}
}
else
{
geometryTypesToAdd.push_back(RivReservoirViewPartMgr::ALL_WELL_CELLS); // Should be all well cells
@ -657,7 +681,6 @@ void RimReservoirView::createDisplayModel()
//--------------------------------------------------------------------------------------------------
void RimReservoirView::updateCurrentTimeStep()
{
//printf("########## updateCurrentTimeStep for frame %i ##########\n", m_currentTimeStep.v());
std::vector<RivReservoirViewPartMgr::ReservoirGeometryCacheType> geometriesToRecolor;
if (this->propertyFilterCollection()->hasActiveFilters())
@ -667,7 +690,6 @@ void RimReservoirView::updateCurrentTimeStep()
std::vector<size_t> gridIndices;
this->indicesToVisibleGrids(&gridIndices);
geometriesToRecolor.push_back( RivReservoirViewPartMgr::PROPERTY_FILTERED);
m_reservoirGridPartManager->appendDynamicGeometryPartsToModel(frameParts.p(), RivReservoirViewPartMgr::PROPERTY_FILTERED, m_currentTimeStep, gridIndices);
@ -683,8 +705,8 @@ void RimReservoirView::updateCurrentTimeStep()
{
std::vector<size_t> gridIndices;
this->indicesToVisibleGrids(&gridIndices);
if (this->rangeFilterCollection()->hasActiveFilters() || this->wellCollection()->hasVisibleWellCells())
if (this->rangeFilterCollection()->hasActiveFilters() ) // Wells not considered, because we do not have a INACTIVE_WELL_CELLS group yet.
{
m_reservoirGridPartManager->appendStaticGeometryPartsToModel(frameParts.p(), RivReservoirViewPartMgr::RANGE_FILTERED_INACTIVE, gridIndices);
}
@ -707,19 +729,28 @@ void RimReservoirView::updateCurrentTimeStep()
m_visibleGridParts = geometriesToRecolor;
}
else if (rangeFilterCollection->hasActiveFilters() || this->wellCollection()->hasVisibleWellCells())
else if (this->rangeFilterCollection()->hasActiveFilters() && this->wellCollection()->hasVisibleWellCells())
{
geometriesToRecolor.push_back(RivReservoirViewPartMgr::RANGE_FILTERED);
geometriesToRecolor.push_back(RivReservoirViewPartMgr::RANGE_FILTERED_WELL_CELLS);
geometriesToRecolor.push_back(RivReservoirViewPartMgr::VISIBLE_WELL_CELLS_OUTSIDE_RANGE_FILTER);
geometriesToRecolor.push_back(RivReservoirViewPartMgr::VISIBLE_WELL_FENCE_CELLS_OUTSIDE_RANGE_FILTER);
}
else if (!this->rangeFilterCollection()->hasActiveFilters() && this->wellCollection()->hasVisibleWellCells())
{
geometriesToRecolor.push_back(RivReservoirViewPartMgr::VISIBLE_WELL_CELLS);
geometriesToRecolor.push_back(RivReservoirViewPartMgr::VISIBLE_WELL_FENCE_CELLS);
}
else if (this->rangeFilterCollection()->hasActiveFilters() && !this->wellCollection()->hasVisibleWellCells())
{
geometriesToRecolor.push_back(RivReservoirViewPartMgr::RANGE_FILTERED);
geometriesToRecolor.push_back(RivReservoirViewPartMgr::RANGE_FILTERED_WELL_CELLS);
}
else
{
geometriesToRecolor.push_back(RivReservoirViewPartMgr::ACTIVE);
geometriesToRecolor.push_back(RivReservoirViewPartMgr::ALL_WELL_CELLS);
}
for (size_t i = 0; i < geometriesToRecolor.size(); ++i)
@ -1392,7 +1423,7 @@ void RimReservoirView::calculateVisibleWellCellsIncFence(cvf::UByteArray* visibl
for (size_t wIdx = 0; wIdx < this->wellCollection()->wells().size(); ++wIdx)
{
RimWell* well = this->wellCollection()->wells()[wIdx];
if (this->wellCollection()->wellCellsToRangeFilterMode() == RimWellCollection::RANGE_ADD_ALL || well->showWellCells())
if (this->wellCollection()->wellCellsToRangeFilterMode() == RimWellCollection::RANGE_ADD_ALL || (well->showWell() && well->showWellCells()) )
{
RigSingleWellResultsData* wres = well->wellResults();
if (!wres) continue;

View File

@ -158,6 +158,8 @@ public:
public:
void loadDataAndUpdate();
void createDisplayModelAndRedraw();
void scheduleCreateDisplayModelAndRedraw();
void scheduleGeometryRegen(unsigned short geometryType);
void scheduleReservoirGridGeometryRegen();
void schedulePipeGeometryRegen();

View File

@ -55,6 +55,7 @@
#include "RimWellPathCollection.h"
#include "RimOilField.h"
#include "RimAnalysisModels.h"
#include "RimUiTreeView.h"
@ -1001,14 +1002,13 @@ RimCase* RimUiTreeModelPdm::caseFromItemIndex(const QModelIndex& itemIndex)
//--------------------------------------------------------------------------------------------------
/// Set toggle state for list of model indices.
///
/// NOTE: Set toggle state directly on object, does not use setValueFromUi()
/// The caller must make sure the relevant dependencies are updated
//--------------------------------------------------------------------------------------------------
void RimUiTreeModelPdm::setObjectToggleStateForSelection(QModelIndexList selectedIndexes, int state)
{
bool toggleOn = (state == Qt::Checked);
std::set<RimReservoirView*> resViewsToUpdate;
foreach (QModelIndex index, selectedIndexes)
{
if (!index.isValid())
@ -1022,17 +1022,65 @@ void RimUiTreeModelPdm::setObjectToggleStateForSelection(QModelIndexList selecte
caf::PdmObject* obj = treeItem->dataObject();
assert(obj);
if (obj && obj->objectToggleField())
if (selectedIndexes.size() != 1)
{
caf::PdmField<bool>* field = dynamic_cast<caf::PdmField<bool>* >(obj->objectToggleField());
if (field)
if (obj && obj->objectToggleField())
{
// Does not use setValueFromUi(), so the caller must make sure dependencies are updated
field->v() = toggleOn;
caf::PdmField<bool>* field = dynamic_cast<caf::PdmField<bool>* >(obj->objectToggleField());
if (field)
{
if (state == RimUiTreeView::TOGGLE_ON) field->setValueFromUi(true);
if (state == RimUiTreeView::TOGGLE_OFF) field->setValueFromUi(false);
if (state == RimUiTreeView::TOGGLE) field->setValueFromUi(!(field->v()));
}
}
}
else
{
// If only one item is selected, loop over its children, and toggle them instead of the
// selected item directly
emitDataChanged(index);
for (int cIdx = 0; cIdx < treeItem->childCount(); ++ cIdx)
{
caf::PdmUiTreeItem* child = treeItem->child(cIdx);
if (!child) continue;
caf::PdmObject* childObj = child->dataObject();
if (childObj && childObj->objectToggleField())
{
caf::PdmField<bool>* field = dynamic_cast<caf::PdmField<bool>* >(childObj->objectToggleField());
if (field)
{
if (state == RimUiTreeView::TOGGLE_ON) field->setValueFromUi(true);
if (state == RimUiTreeView::TOGGLE_OFF) field->setValueFromUi(false);
if (state == RimUiTreeView::TOGGLE) field->setValueFromUi(!(field->v()));
}
}
}
}
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RimUiTreeModelPdm::deleteAllWellPaths(const QModelIndex& itemIndex)
{
if (!itemIndex.isValid()) return;
caf::PdmUiTreeItem* uiItem = getTreeItemFromIndex(itemIndex);
if (!uiItem) return;
caf::PdmObject* object = uiItem->dataObject().p();
RimWellPathCollection* wellPathCollection = dynamic_cast<RimWellPathCollection*>(object);
if (!wellPathCollection) return;
// Remove item from UI tree model before delete of project data structure
removeRows_special(0, uiItem->childCount(), itemIndex);
wellPathCollection->wellPaths.deleteAllChildObjects();
clearClipboard();
}

View File

@ -55,6 +55,7 @@ public:
bool deleteReservoirView(const QModelIndex& itemIndex);
void deleteInputProperty(const QModelIndex& itemIndex);
void deleteReservoir(RimCase* reservoir);
void deleteAllWellPaths(const QModelIndex& itemIndex);
RimCellPropertyFilter* addPropertyFilter(const QModelIndex& itemIndex, QModelIndex& insertedModelIndex);
RimCellRangeFilter* addRangeFilter(const QModelIndex& itemIndex, QModelIndex& insertedModelIndex);

View File

@ -220,6 +220,10 @@ void RimUiTreeView::contextMenuEvent(QContextMenuEvent* event)
menu.addAction(QString("Add Script Path"), this, SLOT(slotAddScriptPath()));
menu.addAction(QString("Delete Script Path"), this, SLOT(slotDeleteScriptPath()));
}
else if (dynamic_cast<RimWellPathCollection*>(uiItem->dataObject().p()))
{
menu.addAction(QString("Delete All Well Paths"), this, SLOT(slotDeleteAllWellPaths()));
}
// Execute script on selection of cases
RiuMainWindow* ruiMainWindow = RiuMainWindow::instance();
@ -545,6 +549,8 @@ void RimUiTreeView::slotExecuteScript()
QStringList arguments;
arguments.append("--path");
arguments << octaveFunctionSearchPath;
arguments.append("--path");
arguments << QApplication::applicationDirPath();
arguments.append("-q");
arguments << calcScript->absolutePath();
@ -597,6 +603,8 @@ void RimUiTreeView::slotExecuteScriptForSelectedCases()
QStringList arguments;
arguments.append("--path");
arguments << octaveFunctionSearchPath;
arguments.append("--path");
arguments << QApplication::applicationDirPath();
arguments.append("-q");
arguments << calcScript->absolutePath();
@ -1472,9 +1480,23 @@ void RimUiTreeView::appendToggleItemActions(QMenu& contextMenu)
contextMenu.addSeparator();
}
contextMenu.addAction(QString("Toggle"), this, SLOT(slotToggleItems()));
contextMenu.addAction(QString("Toggle All On"), this, SLOT(slotToggleItemsOn()));
contextMenu.addAction(QString("Toggle All Off"), this, SLOT(slotToggleItemsOff()));
if (selectionModel()->selectedIndexes().size() > 1)
{
contextMenu.addAction(QString("On"), this, SLOT(slotToggleItemsOn()));
contextMenu.addAction(QString("Off"), this, SLOT(slotToggleItemsOff()));
contextMenu.addAction(QString("Toggle"), this, SLOT(slotToggleItems()));
}
else
{
QModelIndex mIdx = selectionModel()->selectedIndexes()[0];
caf::PdmUiTreeItem* treeItem = caf::UiTreeModelPdm::getTreeItemFromIndex(mIdx);
if (treeItem && treeItem->childCount())
{
contextMenu.addAction(QString("Sub Items On"), this, SLOT(slotToggleItemsOn()));
contextMenu.addAction(QString("Sub Items Off"), this, SLOT(slotToggleItemsOff()));
contextMenu.addAction(QString("Toggle Sub items"), this, SLOT(slotToggleItems()));
}
}
}
}
@ -1491,70 +1513,11 @@ void RimUiTreeView::slotToggleItems()
//--------------------------------------------------------------------------------------------------
void RimUiTreeView::executeSelectionToggleOperation(SelectionToggleType toggleState)
{
int nextCheckBoxState = 0;
if (toggleState == TOGGLE_ON)
{
nextCheckBoxState = Qt::Checked;
}
else if (toggleState == TOGGLE_OFF)
{
nextCheckBoxState = Qt::Unchecked;
}
else if (toggleState == TOGGLE)
{
QModelIndex curr = currentIndex();
// Check if the current model index supports checkable items
if (model()->flags(curr) & Qt::ItemIsUserCheckable)
{
QModelIndexList selectedIndexes = selectionModel()->selectedIndexes();
if (selectedIndexes.contains(curr))
{
QVariant currentState = model()->data(curr, Qt::CheckStateRole);
int state = currentState.toInt();
if (state == Qt::Checked)
{
nextCheckBoxState = Qt::Unchecked;
}
else
{
nextCheckBoxState = Qt::Checked;
}
}
}
}
RimUiTreeModelPdm* myModel = dynamic_cast<RimUiTreeModelPdm*>(model());
caf::PdmUiTreeItem* uiItem = myModel->getTreeItemFromIndex(currentIndex());
// Special handling for wells
// Set toggle state for all wells without triggering model update,
// and perform a single display model update at last
RimWell* well = dynamic_cast<RimWell*>(uiItem->dataObject().p());
if (well)
{
myModel->setObjectToggleStateForSelection(selectionModel()->selectedIndexes(), nextCheckBoxState);
myModel->setObjectToggleStateForSelection(selectionModel()->selectedIndexes(), toggleState);
RimReservoirView* reservoirView = NULL;
well->firstAncestorOfType(reservoirView);
if (reservoirView)
{
reservoirView->createDisplayModelAndRedraw();
}
return;
}
foreach (QModelIndex index, selectionModel()->selectedIndexes())
{
if (!index.isValid())
{
continue;
}
myModel->setData(index, nextCheckBoxState, Qt::CheckStateRole);
}
return;
}
//--------------------------------------------------------------------------------------------------
@ -1633,3 +1596,16 @@ void RimUiTreeView::appendScriptItems(QMenu* menu, RimScriptCollection* scriptCo
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RimUiTreeView::slotDeleteAllWellPaths()
{
RimUiTreeModelPdm* myModel = dynamic_cast<RimUiTreeModelPdm*>(model());
if (myModel)
{
myModel->deleteAllWellPaths(currentIndex());
}
}

View File

@ -101,10 +101,12 @@ private slots:
void slotToggleItemsOn();
void slotToggleItemsOff();
void slotDeleteAllWellPaths();
signals:
void selectedObjectChanged( caf::PdmObject* pdmObject );
private:
public:
enum SelectionToggleType
{
TOGGLE_ON,

View File

@ -43,6 +43,8 @@ RimWell::RimWell()
CAF_PDM_InitObject("Well", ":/Well.png", "", "");
CAF_PDM_InitFieldNoDefault(&name, "WellName", "Name", "", "", "");
CAF_PDM_InitField(&showWell, "ShowWell", true, "Show well ", "", "", "");
showWell.setUiHidden(true);
CAF_PDM_InitField(&showWellLabel, "ShowWellLabel", true, "Show well label", "", "", "");
@ -93,7 +95,15 @@ void RimWell::fieldChangedByUi(const caf::PdmFieldHandle* changedField, const QV
{
if (m_reservoirView)
{
m_reservoirView->createDisplayModelAndRedraw();
m_reservoirView->scheduleCreateDisplayModelAndRedraw();
}
}
else if (&showWell == changedField)
{
if (m_reservoirView)
{
m_reservoirView->scheduleGeometryRegen(RivReservoirViewPartMgr::VISIBLE_WELL_CELLS);
m_reservoirView->scheduleCreateDisplayModelAndRedraw();
}
}
else if (&showWellCells == changedField)
@ -101,7 +111,7 @@ void RimWell::fieldChangedByUi(const caf::PdmFieldHandle* changedField, const QV
if (m_reservoirView)
{
m_reservoirView->scheduleGeometryRegen(RivReservoirViewPartMgr::VISIBLE_WELL_CELLS);
m_reservoirView->createDisplayModelAndRedraw();
m_reservoirView->scheduleCreateDisplayModelAndRedraw();
}
}
@ -110,24 +120,24 @@ void RimWell::fieldChangedByUi(const caf::PdmFieldHandle* changedField, const QV
if (m_reservoirView)
{
m_reservoirView->scheduleGeometryRegen(RivReservoirViewPartMgr::VISIBLE_WELL_CELLS);
m_reservoirView->createDisplayModelAndRedraw();
m_reservoirView->scheduleCreateDisplayModelAndRedraw();
}
}
else if (&showWellPipes == changedField)
{
if (m_reservoirView) m_reservoirView->createDisplayModelAndRedraw();
if (m_reservoirView) m_reservoirView->scheduleCreateDisplayModelAndRedraw();
}
else if (&wellPipeColor == changedField)
{
if (m_reservoirView) m_reservoirView->createDisplayModelAndRedraw();
if (m_reservoirView) m_reservoirView->scheduleCreateDisplayModelAndRedraw();
}
else if (&pipeRadiusScaleFactor == changedField)
{
if (m_reservoirView)
{
m_reservoirView->schedulePipeGeometryRegen();
m_reservoirView->createDisplayModelAndRedraw();
m_reservoirView->scheduleCreateDisplayModelAndRedraw();
}
}
}
@ -137,7 +147,7 @@ void RimWell::fieldChangedByUi(const caf::PdmFieldHandle* changedField, const QV
//--------------------------------------------------------------------------------------------------
caf::PdmFieldHandle* RimWell::objectToggleField()
{
return &showWellPipes;
return &showWell;
}
//--------------------------------------------------------------------------------------------------
@ -168,6 +178,9 @@ bool RimWell::calculateWellPipeVisibility(size_t frameIndex)
if (m_reservoirView->wellCollection()->wellPipeVisibility() == RimWellCollection::PIPES_FORCE_ALL_OFF)
return false;
if ( this->showWell() == false )
return false;
if ( this->showWellPipes() == false )
return false;
@ -188,10 +201,13 @@ bool RimWell::calculateWellPipeVisibility(size_t frameIndex)
size_t gridIndex = wrsf.m_wellHead.m_gridIndex;
size_t gridCellIndex = wrsf.m_wellHead.m_gridCellIndex;
cvf::cref<cvf::UByteArray> cellVisibility = rvMan->cellVisibility(visGridParts[gpIdx], gridIndex, frameIndex);
if ((*cellVisibility)[gridCellIndex])
if (gridIndex != cvf::UNDEFINED_SIZE_T && gridCellIndex != cvf::UNDEFINED_SIZE_T)
{
return true;
cvf::cref<cvf::UByteArray> cellVisibility = rvMan->cellVisibility(visGridParts[gpIdx], gridIndex, frameIndex);
if ((*cellVisibility)[gridCellIndex])
{
return true;
}
}
// Then check the rest of the well, with all the branches

View File

@ -55,6 +55,8 @@ public:
virtual void fieldChangedByUi(const caf::PdmFieldHandle* changedField, const QVariant& oldValue, const QVariant& newValue);
virtual void defineUiOrdering(QString uiConfigName, caf::PdmUiOrdering& uiOrdering);
caf::PdmField<bool> showWell;
caf::PdmField<QString> name;
caf::PdmField<bool> showWellLabel;

View File

@ -149,7 +149,7 @@ bool RimWellCollection::hasVisibleWellCells()
for (size_t i = 0 ; !hasCells && i < this->wells().size(); ++i)
{
RimWell* well = this->wells()[i];
if ( well && well->wellResults() && (well->showWellCells() || this->wellCellsToRangeFilterMode() == RANGE_ADD_ALL) )
if ( well && well->wellResults() && ((well->showWell() && well->showWellCells()) || this->wellCellsToRangeFilterMode() == RANGE_ADD_ALL) )
{
for (size_t tIdx = 0; !hasCells && tIdx < well->wellResults()->m_wellCellsTimeSteps.size(); ++tIdx )
{
@ -197,7 +197,7 @@ void RimWellCollection::fieldChangedByUi(const caf::PdmFieldHandle* changedField
if (m_reservoirView)
{
m_reservoirView->scheduleGeometryRegen(RivReservoirViewPartMgr::VISIBLE_WELL_CELLS);
m_reservoirView->createDisplayModelAndRedraw();
m_reservoirView->scheduleCreateDisplayModelAndRedraw();
}
}
if (&wellCellsToRangeFilterMode == changedField)
@ -205,7 +205,7 @@ void RimWellCollection::fieldChangedByUi(const caf::PdmFieldHandle* changedField
if (m_reservoirView)
{
m_reservoirView->scheduleGeometryRegen(RivReservoirViewPartMgr::VISIBLE_WELL_CELLS);
m_reservoirView->createDisplayModelAndRedraw();
m_reservoirView->scheduleCreateDisplayModelAndRedraw();
}
}
else if (&showWellCellFences == changedField)
@ -213,14 +213,14 @@ void RimWellCollection::fieldChangedByUi(const caf::PdmFieldHandle* changedField
if (m_reservoirView)
{
m_reservoirView->scheduleGeometryRegen(RivReservoirViewPartMgr::VISIBLE_WELL_CELLS);
m_reservoirView->createDisplayModelAndRedraw();
m_reservoirView->scheduleCreateDisplayModelAndRedraw();
}
}
else if (&wellCellTransparencyLevel == changedField)
{
if (m_reservoirView)
{
m_reservoirView->createDisplayModelAndRedraw();
m_reservoirView->scheduleCreateDisplayModelAndRedraw();
}
}
else if (&wellCellFenceType == changedField)
@ -228,14 +228,14 @@ void RimWellCollection::fieldChangedByUi(const caf::PdmFieldHandle* changedField
if (m_reservoirView)
{
m_reservoirView->scheduleGeometryRegen(RivReservoirViewPartMgr::VISIBLE_WELL_CELLS);
m_reservoirView->createDisplayModelAndRedraw();
m_reservoirView->scheduleCreateDisplayModelAndRedraw();
}
}
else if (&wellPipeVisibility == changedField)
{
if (m_reservoirView)
{
m_reservoirView->createDisplayModelAndRedraw();
m_reservoirView->scheduleCreateDisplayModelAndRedraw();
}
}
else if ( &pipeCrossSectionVertexCount == changedField
@ -248,7 +248,7 @@ void RimWellCollection::fieldChangedByUi(const caf::PdmFieldHandle* changedField
if (m_reservoirView)
{
m_reservoirView->schedulePipeGeometryRegen();
m_reservoirView->createDisplayModelAndRedraw();
m_reservoirView->scheduleCreateDisplayModelAndRedraw();
}
}
}
@ -275,6 +275,7 @@ void RimWellCollection::defineUiOrdering(QString uiConfigName, caf::PdmUiOrderin
wellHeadGroup->add(&showWellHead);
wellHeadGroup->add(&wellHeadScaleFactor);
wellHeadGroup->add(&showWellLabel);
wellHeadGroup->add(&wellHeadPosition);
caf::PdmUiGroup* wellPipe = uiOrdering.addNewGroup("Well pipe");
wellPipe->add(&wellPipeVisibility);

View File

@ -164,9 +164,11 @@ void RigCaseData::computeWellCellsPrGrid()
size_t gridIndex = wellCells.m_wellHead.m_gridIndex;
size_t gridCellIndex = wellCells.m_wellHead.m_gridCellIndex;
CVF_ASSERT(gridIndex < m_wellCellsInGrid.size() && gridCellIndex < m_wellCellsInGrid[gridIndex]->size());
m_wellCellsInGrid[gridIndex]->set(gridCellIndex, true);
m_gridCellToWellIndex[gridIndex]->set(gridCellIndex, static_cast<cvf::uint>(wIdx));
if (gridIndex != cvf::UNDEFINED_SIZE_T && gridCellIndex != cvf::UNDEFINED_SIZE_T)
{
m_wellCellsInGrid[gridIndex]->set(gridCellIndex, true);
m_gridCellToWellIndex[gridIndex]->set(gridCellIndex, static_cast<cvf::uint>(wIdx));
}
size_t sIdx;
for (sIdx = 0; sIdx < wellCells.m_wellResultBranches.size(); ++sIdx)

View File

@ -33,10 +33,12 @@ RigGridBase::RigGridBase(RigMainGrid* mainGrid):
if (mainGrid == NULL)
{
m_gridIndex = 0;
m_gridId = 0;
}
else
{
m_gridIndex = cvf::UNDEFINED_SIZE_T;
m_gridId = cvf::UNDEFINED_INT;
}
}
@ -395,10 +397,9 @@ void RigGridBase::computeFaults()
// Check if vertices are matching
double tolerance = 1e-6;
size_t i;
for (i = 0; i < 4; i++)
for (size_t cellFaceIdx = 0; cellFaceIdx < 4; cellFaceIdx++)
{
if (currentCellFaceVertices[i].pointDistance(neighbourCellFaceVertices[i]) > tolerance )
if (currentCellFaceVertices[cellFaceIdx].pointDistance(neighbourCellFaceVertices[cellFaceIdx]) > tolerance )
{
sharedFaceVertices = false;
}

View File

@ -57,6 +57,9 @@ public:
void setGridIndex(size_t index) { m_gridIndex = index; }
size_t gridIndex() const { return m_gridIndex; }
void setGridId(int id) { m_gridId = id; }
int gridId() const { return m_gridId; }
double characteristicIJCellSize();
std::string gridName() const;
@ -108,6 +111,7 @@ private:
cvf::Vec3st m_gridPointDimensions;
size_t m_indexToStartOfCells; ///< Index into the global cell array stored in main-grid where this grids cells starts.
size_t m_gridIndex; ///< The LGR index of this grid. Starts with 1. Main grid has index 0.
int m_gridId; ///< The LGR id of this grid. Main grid has id 0.
RigMainGrid* m_mainGrid;
cvf::BoundingBox m_boundingBox;

View File

@ -129,6 +129,20 @@ private:
};
class StructGridScalarDataAccessHugeVal : public cvf::StructGridScalarDataAccess
{
public:
virtual double cellScalar(size_t cellIndex) const
{
return HUGE_VAL;
}
virtual void setCellScalar(size_t cellIndex, double value)
{
}
};
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
@ -152,6 +166,17 @@ cvf::ref<cvf::StructGridScalarDataAccess> RigGridScalarDataAccessFactory::create
std::vector< std::vector<double> >& scalarSetResults = eclipseCase->results(porosityModel)->cellScalarResults(scalarSetIndex);
// A generated result with a generated results for a subset of time steps, will end up with a result container with less entries than time steps
// See RiaSetGridProperty command in RiaPropertyDataCommands
//
// Some functions requires a valid data access object to be present, these might be rewritten to avoid this dummy object always returning HUGE_VAL
if (timeStepIndex >= scalarSetResults.size())
{
cvf::ref<cvf::StructGridScalarDataAccess> object = new StructGridScalarDataAccessHugeVal;
return object;
}
std::vector<double>* resultValues = NULL;
if (timeStepIndex < scalarSetResults.size())
{

View File

@ -26,6 +26,9 @@ RigMainGrid::RigMainGrid(void)
m_displayModelOffset = cvf::Vec3d::ZERO;
m_gridIndex = 0;
m_gridId = 0;
m_gridIdToIndexMapping.push_back(0);
m_flipXAxis = false;
m_flipYAxis = false;
}
@ -40,8 +43,19 @@ RigMainGrid::~RigMainGrid(void)
//--------------------------------------------------------------------------------------------------
void RigMainGrid::addLocalGrid(RigLocalGrid* localGrid)
{
CVF_ASSERT(localGrid && localGrid->gridId() != cvf::UNDEFINED_INT); // The grid ID must be set.
CVF_ASSERT(localGrid->gridId() >= 0); // We cant handle negative ID's if they exist.
m_localGrids.push_back(localGrid);
localGrid->setGridIndex(m_localGrids.size()); // Maingrid itself has grid index 0
if (m_gridIdToIndexMapping.size() <= localGrid->gridId())
{
m_gridIdToIndexMapping.resize(localGrid->gridId() + 1, cvf::UNDEFINED_SIZE_T);
}
m_gridIdToIndexMapping[localGrid->gridId()] = localGrid->gridIndex();
}
//--------------------------------------------------------------------------------------------------
@ -156,3 +170,12 @@ void RigMainGrid::setFlipAxis(bool flipXAxis, bool flipYAxis)
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RigGridBase* RigMainGrid::gridById(int localGridId)
{
CVF_ASSERT (localGridId >= 0 && localGridId < m_gridIdToIndexMapping.size());
return this->gridByIndex(m_gridIdToIndexMapping[localGridId]);
}

View File

@ -44,7 +44,8 @@ public:
size_t gridCount() const { return m_localGrids.size() + 1; }
RigGridBase* gridByIndex(size_t localGridIndex);
const RigGridBase* gridByIndex(size_t localGridIndex) const;
RigGridBase* gridById(int localGridId);
void computeCachedData();
// Overrides
@ -62,6 +63,7 @@ private:
std::vector<cvf::Vec3d> m_nodes; ///< Global vertex table
std::vector<RigCell> m_cells; ///< Global array of all cells in the reservoir (including the ones in LGR's)
cvf::Collection<RigLocalGrid> m_localGrids; ///< List of all the LGR's in this reservoir
std::vector<size_t> m_gridIdToIndexMapping; ///< Mapping from LGR Id to index.
cvf::Vec3d m_displayModelOffset;

View File

@ -85,6 +85,11 @@ void RigSingleWellResultsData::computeMappingFromResultTimeIndicesToWellTimeIndi
//--------------------------------------------------------------------------------------------------
bool RigSingleWellResultsData::hasWellResult(size_t resultTimeStepIndex) const
{
if (resultTimeStepIndex >= m_resultTimeStepIndexToWellTimeStepIndex.size())
{
return false;
}
size_t wellTimeStepIndex = m_resultTimeStepIndexToWellTimeStepIndex[resultTimeStepIndex];
return wellTimeStepIndex != cvf::UNDEFINED_SIZE_T;

View File

@ -904,7 +904,7 @@ public:
qint64 bytesRead = currentClient->read((char*)(doubleValues.data()), m_bytesPerTimeStepToRead);
size_t doubleValueIndex = 0;
cvf::ref<cvf::StructGridScalarDataAccess> cellCenterDataAccessObject = m_currentReservoir->reservoirData()->dataAccessObject(grid, m_porosityModelEnum, m_currentTimeStepNumberToRead, m_currentScalarIndex);
cvf::ref<cvf::StructGridScalarDataAccess> cellCenterDataAccessObject = m_currentReservoir->reservoirData()->dataAccessObject(grid, m_porosityModelEnum, m_requestedTimesteps[m_currentTimeStepNumberToRead], m_currentScalarIndex);
if (!cellCenterDataAccessObject.isNull())
{
for (size_t cellIdx = 0; static_cast<size_t>(cellIdx) < cellCountFromOctave; cellIdx++)
@ -981,3 +981,81 @@ private:
static bool RiaSetGridProperty_init = RiaSocketCommandFactory::instance()->registerCreator<RiaSetGridProperty>(RiaSetGridProperty::commandName());
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
class RiaGetPropertyNames : public RiaSocketCommand
{
public:
static QString commandName () { return QString("GetPropertyNames"); }
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;
}
QString porosityModelName = args[2];
RifReaderInterface::PorosityModelResultType porosityModelEnum = RifReaderInterface::MATRIX_RESULTS;
if (porosityModelName == "Fracture")
{
porosityModelEnum = RifReaderInterface::FRACTURE_RESULTS;
}
std::vector<QString> propNames;
std::vector<QString> propTypes;
RigCaseCellResultsData* results = rimCase->reservoirData()->results(porosityModelEnum);
std::vector<RimDefines::ResultCatType> resTypes;
std::vector<QString> resTypeNames;
resTypes.push_back(RimDefines::DYNAMIC_NATIVE);
resTypeNames.push_back("DynamicNative");
resTypes.push_back(RimDefines::STATIC_NATIVE );
resTypeNames.push_back("StaticNative");
resTypes.push_back(RimDefines::GENERATED );
resTypeNames.push_back("Generated");
resTypes.push_back(RimDefines::INPUT_PROPERTY);
resTypeNames.push_back("Input");
for (size_t rtIdx = 0; rtIdx < resTypes.size(); ++rtIdx)
{
RimDefines::ResultCatType resType = resTypes[rtIdx];
QStringList names = results->resultNames(resType);
for (int pnIdx = 0; pnIdx < names.size(); ++pnIdx){
propNames.push_back(names[pnIdx]);
propTypes.push_back(resTypeNames[rtIdx]);
}
}
quint64 byteCount = sizeof(quint64);
quint64 propCount = propNames.size();
for (size_t rtIdx = 0; rtIdx < propCount; rtIdx++)
{
byteCount += propNames[rtIdx].size() * sizeof(QChar);
byteCount += propTypes[rtIdx].size() * sizeof(QChar);
}
socketStream << byteCount;
socketStream << propCount;
for (size_t rtIdx = 0; rtIdx < propCount; rtIdx++)
{
socketStream << propNames[rtIdx];
socketStream << propTypes[rtIdx];
}
return true;
}
};
static bool RiaGetPropertyNames_init = RiaSocketCommandFactory::instance()->registerCreator<RiaGetPropertyNames>(RiaGetPropertyNames::commandName());

View File

@ -0,0 +1,348 @@
//
// Copyright (C) 2011-2012 Statoil ASA, Ceetron AS
//
// 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 "RiaStdInclude.h"
#include "RiaSocketCommand.h"
#include "RiaSocketServer.h"
#include "RiaSocketTools.h"
#include "RiuMainWindow.h"
#include "RigCaseData.h"
#include "RigCaseCellResultsData.h"
#include "RimReservoirCellResultsCacher.h"
#include "RimCase.h"
#include "RimInputCase.h"
#include "RimInputPropertyCollection.h"
#include "RimUiTreeModelPdm.h"
#include "RimReservoirView.h"
#include "RimResultSlot.h"
#include "RimCellEdgeResultSlot.h"
#include "RimCellRangeFilterCollection.h"
#include "RimCellPropertyFilterCollection.h"
#include "RimWellCollection.h"
#include "Rim3dOverlayInfoConfig.h"
#include <QTcpSocket>
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
class RiaGetWellNames : public RiaSocketCommand
{
public:
static QString commandName () { return QString("GetWellNames"); }
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;
}
std::vector<QString> wellNames;
const cvf::Collection<RigSingleWellResultsData>& wells = rimCase->reservoirData()->wellResults();
for (size_t wIdx = 0; wIdx < wells.size(); ++wIdx)
{
wellNames.push_back(wells[wIdx]->m_wellName);
}
quint64 byteCount = sizeof(quint64);
quint64 wellCount = wellNames.size();
for (size_t wIdx = 0; wIdx < wellCount; wIdx++)
{
byteCount += wellNames[wIdx].size() * sizeof(QChar);
}
socketStream << byteCount;
socketStream << wellCount;
for (size_t wIdx = 0; wIdx < wellCount; wIdx++)
{
socketStream << wellNames[wIdx];
}
return true;
}
};
static bool RiaGetWellNames_init = RiaSocketCommandFactory::instance()->registerCreator<RiaGetWellNames>(RiaGetWellNames::commandName());
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
class RiaGetWellStatus : public RiaSocketCommand
{
public:
static QString commandName () { return QString("GetWellStatus"); }
virtual bool interpretCommand(RiaSocketServer* server, const QList<QByteArray>& args, QDataStream& socketStream)
{
int caseId = args[1].toInt();
QString wellName = args[2];
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;
}
// Create a list of all the requested time steps
std::vector<size_t> requestedTimesteps;
//First find the well result for the correct well
const cvf::Collection<RigSingleWellResultsData>& allWellRes = rimCase->reservoirData()->wellResults();
cvf::ref<RigSingleWellResultsData> currentWellResult;
for (size_t tsIdx = 0; tsIdx < allWellRes.size(); ++tsIdx)
{
if (allWellRes[tsIdx]->m_wellName == wellName)
{
currentWellResult = allWellRes[tsIdx];
break;
}
}
if (currentWellResult.isNull())
{
server->errorMessageDialog()->showMessage(
RiaSocketServer::tr("ResInsight SocketServer: \n") + RiaSocketServer::tr("Could not find the well with name : \"%1\"").arg(wellName));
return true;
}
if (args.size() <= 3)
{
// Select all timesteps.
for (size_t tsIdx = 0; tsIdx < currentWellResult->m_resultTimeStepIndexToWellTimeStepIndex.size(); ++tsIdx)
{
requestedTimesteps.push_back(tsIdx);
}
}
else
{
bool timeStepReadError = false;
for (int argIdx = 3; argIdx < args.size(); ++argIdx)
{
bool conversionOk = false;
int tsIdx = args[argIdx].toInt(&conversionOk);
if (conversionOk)
{
requestedTimesteps.push_back(tsIdx);
}
else
{
timeStepReadError = true;
}
}
if (timeStepReadError)
{
server->errorMessageDialog()->showMessage(RiaSocketServer::tr("ResInsight SocketServer: riGetGridProperty : \n")
+ RiaSocketServer::tr("An error occured while interpreting the requested timesteps."));
}
}
std::vector<QString> wellTypes;
std::vector<qint32> wellStatuses;
for (size_t tsIdx = 0; tsIdx < requestedTimesteps.size(); ++tsIdx)
{
QString wellType = "NotDefined";
qint32 wellStatus = 0;
if (currentWellResult->hasWellResult(tsIdx))
{
switch(currentWellResult->wellResultFrame(tsIdx).m_productionType)
{
case RigWellResultFrame::PRODUCER:
wellType = "Producer";
break;
case RigWellResultFrame::OIL_INJECTOR:
wellType = "OilInjector";
break;
case RigWellResultFrame::WATER_INJECTOR:
wellType = "WaterInjector";
break;
case RigWellResultFrame::GAS_INJECTOR:
wellType = "GasInjector";
break;
}
wellStatus = currentWellResult->wellResultFrame(tsIdx).m_isOpen ? 1 : 0;
}
wellTypes.push_back(wellType);
wellStatuses.push_back(wellStatus);
}
quint64 byteCount = sizeof(quint64);
quint64 timeStepCount = wellTypes.size();
for (size_t tsIdx = 0; tsIdx < timeStepCount; tsIdx++)
{
byteCount += wellTypes[tsIdx].size() * sizeof(QChar);
byteCount += sizeof(qint32);
}
socketStream << byteCount;
socketStream << timeStepCount;
for (size_t tsIdx = 0; tsIdx < timeStepCount; tsIdx++)
{
socketStream << wellTypes[tsIdx];
socketStream << wellStatuses[tsIdx];
}
return true;
}
};
static bool RiaGetWellStatus_init = RiaSocketCommandFactory::instance()->registerCreator<RiaGetWellStatus>(RiaGetWellStatus::commandName());
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
class RiaGetWellCells : public RiaSocketCommand
{
public:
static QString commandName () { return QString("GetWellCells"); }
virtual bool interpretCommand(RiaSocketServer* server, const QList<QByteArray>& args, QDataStream& socketStream)
{
int caseId = args[1].toInt();
QString wellName = args[2];
size_t timeStepIdx = args[3].toInt() - 1; // Interpret timeStepIdx from octave as 1-based
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));
socketStream << (quint64)0;
return true;
}
const cvf::Collection<RigSingleWellResultsData>& allWellRes = rimCase->reservoirData()->wellResults();
cvf::ref<RigSingleWellResultsData> currentWellResult;
for (size_t cIdx = 0; cIdx < allWellRes.size(); ++cIdx)
{
if (allWellRes[cIdx]->m_wellName == wellName)
{
currentWellResult = allWellRes[cIdx];
break;
}
}
if (currentWellResult.isNull())
{
server->errorMessageDialog()->showMessage(
RiaSocketServer::tr("ResInsight SocketServer: \n") + RiaSocketServer::tr("Could not find the well with name : \"%1\"").arg(wellName));
socketStream << (quint64)0;
return true;
}
if (!currentWellResult->hasWellResult(timeStepIdx))
{
socketStream << (quint64)0;
return true;
}
std::vector<qint32> cellIs;
std::vector<qint32> cellJs;
std::vector<qint32> cellKs;
std::vector<qint32> gridIndices;
std::vector<qint32> cellStatuses;
std::vector<qint32> branchIds;
std::vector<qint32> segmentIds;
// Fetch results
const RigWellResultFrame& wellResFrame = currentWellResult->wellResultFrame(timeStepIdx);
std::vector<RigGridBase*> grids;
rimCase->reservoirData()->allGrids(&grids);
for (size_t bIdx = 0; bIdx < wellResFrame.m_wellResultBranches.size(); ++bIdx)
{
const std::vector<RigWellResultPoint>& branchResPoints = wellResFrame.m_wellResultBranches[bIdx].m_branchResultPoints;
for (size_t rpIdx = 0; rpIdx < branchResPoints.size(); ++rpIdx)
{
const RigWellResultPoint& resPoint = branchResPoints[rpIdx];
if (resPoint.isCell())
{
size_t i;
size_t j;
size_t k;
size_t gridIdx = resPoint.m_gridIndex ;
grids[gridIdx]->ijkFromCellIndex(resPoint.m_gridCellIndex, &i, &j, &k);
bool isOpen = resPoint.m_isOpen;
int branchId = resPoint.m_ertBranchId;
int segmentId = resPoint.m_ertSegmentId;
cellIs .push_back( static_cast<qint32>(i) );
cellJs .push_back( static_cast<qint32>(j) );
cellKs .push_back( static_cast<qint32>(k) );
gridIndices .push_back( static_cast<qint32>(gridIdx) );
cellStatuses.push_back( static_cast<qint32>(isOpen) );
branchIds .push_back( branchId );
segmentIds .push_back( segmentId);
}
}
}
quint64 byteCount = sizeof(quint64);
quint64 cellCount = cellIs.size();
byteCount += cellCount*( 7 * sizeof(qint32));
socketStream << byteCount;
socketStream << cellCount;
for (size_t cIdx = 0; cIdx < cellCount; cIdx++)
{
socketStream << cellIs[cIdx];
socketStream << cellJs[cIdx];
socketStream << cellKs[cIdx];
socketStream << gridIndices[cIdx];
socketStream << cellStatuses[cIdx];
socketStream << branchIds[cIdx];
socketStream << segmentIds[cIdx];
}
return true;
}
};
static bool RiaGetWellCells_init = RiaSocketCommandFactory::instance()->registerCreator<RiaGetWellCells>(RiaGetWellCells::commandName());

View File

@ -58,8 +58,7 @@
#include "RimCellEdgeResultSlot.h"
#include "RimCellRangeFilterCollection.h"
#include "Rim3dOverlayInfoConfig.h"
#include "ssihubInterface/ssihubInterface.h"
#include "RiuWellImportWizard.h"
@ -100,8 +99,6 @@ RiuMainWindow::RiuMainWindow()
m_treeModelPdm = new RimUiTreeModelPdm(this);
m_ssihubInterface = new ssihub::Interface;
createActions();
createMenus();
createToolBars();
@ -1601,8 +1598,6 @@ void RiuMainWindow::selectedCases(std::vector<RimCase*>& cases)
//--------------------------------------------------------------------------------------------------
void RiuMainWindow::slotImportWellPathsFromSSIHub()
{
CVF_ASSERT(m_ssihubInterface);
RiaApplication* app = RiaApplication::instance();
if (!app->project())
{
@ -1614,6 +1609,9 @@ void RiuMainWindow::slotImportWellPathsFromSSIHub()
return;
}
// Update the UTM bounding box from the reservoir
app->project()->computeUtmAreaOfInterest();
QString wellPathsFolderPath;
QString projectFileName = app->project()->fileName();
QFileInfo fileInfo(projectFileName);
@ -1625,29 +1623,32 @@ void RiuMainWindow::slotImportWellPathsFromSSIHub()
wellPathsFolderPath += "/" + wellPathFolderName;
m_ssihubInterface->setWebServiceAddress(app->preferences()->ssihubAddress);
m_ssihubInterface->setJsonDestinationFolder(wellPathsFolderPath);
double north = cvf::UNDEFINED_DOUBLE;
double south = cvf::UNDEFINED_DOUBLE;
double east = cvf::UNDEFINED_DOUBLE;
double west = cvf::UNDEFINED_DOUBLE;
RimWellPathImport* copyOfWellPathImport = dynamic_cast<RimWellPathImport*>(app->project()->wellPathImport->deepCopy());
app->project()->computeUtmAreaOfInterest(&north, &south, &east, &west);
if (north != cvf::UNDEFINED_DOUBLE &&
south != cvf::UNDEFINED_DOUBLE &&
east != cvf::UNDEFINED_DOUBLE &&
west != cvf::UNDEFINED_DOUBLE)
RiuWellImportWizard wellImportwizard(app->preferences()->ssihubAddress, wellPathsFolderPath, copyOfWellPathImport, this);
// Get password/username from application cache
{
m_ssihubInterface->setRegion(north, south, east, west);
QString ssihubUsername = app->cacheDataObject("ssihub_username").toString();
QString ssihubPassword = app->cacheDataObject("ssihub_password").toString();
wellImportwizard.setCredentials(ssihubUsername, ssihubPassword);
}
QStringList wellPaths = m_ssihubInterface->jsonWellPaths();
if (wellPaths.size() > 0)
if (QDialog::Accepted == wellImportwizard.exec())
{
app->addWellPathsToModel(wellPaths);
if (app->project()) app->project()->createDisplayModelAndRedrawAllViews();
QStringList wellPaths = wellImportwizard.absoluteFilePathsToWellPaths();
if (wellPaths.size() > 0)
{
app->addWellPathsToModel(wellPaths);
app->project()->createDisplayModelAndRedrawAllViews();
}
app->project()->wellPathImport = copyOfWellPathImport;
app->setCacheDataObject("ssihub_username", wellImportwizard.field("username"));
app->setCacheDataObject("ssihub_password", wellImportwizard.field("password"));
}
}

View File

@ -262,6 +262,4 @@ private:
std::vector<QPointer<QDockWidget> > additionalProjectTrees;
std::vector<QPointer<QDockWidget> > additionalPropertyEditors;
ssihub::Interface* m_ssihubInterface;
};

View File

@ -1,17 +1,14 @@
cmake_minimum_required (VERSION 2.8)
project (ssihubInterface)
project (WellPathImportSsihub)
# These headers need to go through Qt's MOC compiler
set( QOBJECT_HEADERS
ssihubWebServiceInterface.h
ssihubDialog.h
httpwindow.h
RiuWellImportWizard.h
)
set( QT_UI_FILES
authenticationdialog.ui
)
if ( (${CMAKE_VERSION} VERSION_LESS 2.8.6) OR (NOT CMAKE_AUTOMOC) )
@ -23,17 +20,26 @@ include_directories(
${CMAKE_CURRENT_BINARY_DIR}
${CMAKE_CURRENT_SOURCE_DIR}/../FileInterface
${CMAKE_CURRENT_SOURCE_DIR}/../../cafProjectDataModel
${CMAKE_CURRENT_SOURCE_DIR}/../../cafUserInterface
)
add_library( ${PROJECT_NAME}
ssihubInterface.cpp
ssihubWebServiceInterface.cpp
ssihubDialog.cpp
httpwindow.cpp
RimWellPathImport.h
RimWellPathImport.cpp
RimOilRegionEntry.h
RimOilRegionEntry.cpp
RimOilFieldEntry.h
RimOilFieldEntry.cpp
RimWellsEntry.h
RimWellsEntry.cpp
RiuWellImportWizard.h
RiuWellImportWizard.cpp
${CMAKE_CURRENT_SOURCE_DIR}/../FileInterface/RifJsonEncodeDecode.cpp
${MOC_FILES_CPP}
${FORM_FILES_CPP}
${HEADER_FILES}
)

View File

@ -0,0 +1,119 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2011-2012 Statoil ASA, Ceetron AS
//
// 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 "RimOilFieldEntry.h"
#include "RimWellPathImport.h"
#include "RifJsonEncodeDecode.h"
#include <QFile>
#include <QFileInfo>
#include <QMap>
#include <QDebug>
CAF_PDM_SOURCE_INIT(RimOilFieldEntry, "RimOilFieldEntry");
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RimOilFieldEntry::RimOilFieldEntry()
{
CAF_PDM_InitObject("OilFieldEntry", "", "", "");
CAF_PDM_InitFieldNoDefault(&name, "OilFieldName", "OilFieldName", "", "", "");
CAF_PDM_InitFieldNoDefault(&edmId, "EdmId", "EdmId", "", "", "");
CAF_PDM_InitField(&selected, "Selected", true, "Selected", "", "", "");
CAF_PDM_InitFieldNoDefault(&wellsFilePath, "wellsFilePath", "wellsFilePath", "", "", "");
CAF_PDM_InitFieldNoDefault(&wells, "Wells", "", "", "", "");
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
caf::PdmFieldHandle* RimOilFieldEntry::userDescriptionField()
{
return &name;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
caf::PdmFieldHandle* RimOilFieldEntry::objectToggleField()
{
return &selected;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RimOilFieldEntry::fieldChangedByUi(const caf::PdmFieldHandle* changedField, const QVariant& oldValue, const QVariant& newValue)
{
if (changedField == &selected)
{
updateEnabledState();
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RimOilFieldEntry::initAfterRead()
{
updateEnabledState();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RimOilFieldEntry::updateEnabledState()
{
bool wellsReadOnly = !selected;
if (this->isUiReadOnly())
{
wellsReadOnly = true;
}
for (size_t i = 0; i < wells.size(); i++)
{
wells[i]->setUiReadOnly(wellsReadOnly);
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RimWellPathEntry* RimOilFieldEntry::find(const QString& name, RimWellPathEntry::WellTypeEnum wellPathType)
{
for (size_t i = 0; i < wells.size(); i++)
{
RimWellPathEntry* wellPathEntry = wells[i];
if (wellPathEntry->name == name && wellPathEntry->wellPathType == wellPathType)
{
return wellPathEntry;
}
}
return NULL;
}

View File

@ -0,0 +1,56 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2011-2012 Statoil ASA, Ceetron AS
//
// 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 "cafPdmObject.h"
#include "cafPdmField.h"
#include "RimWellsEntry.h"
class RimOilFieldEntry : public caf::PdmObject
{
CAF_PDM_HEADER_INIT;
public:
RimOilFieldEntry();
caf::PdmField<QString> name;
caf::PdmField<QString> edmId;
caf::PdmField<bool> selected;
caf::PdmField<QString> wellsFilePath; // Location of the response file from request "/wells"
caf::PdmPointersField<RimWellPathEntry*> wells;
RimWellPathEntry* find(const QString& name, RimWellPathEntry::WellTypeEnum wellPathType);
virtual caf::PdmFieldHandle* userDescriptionField();
virtual caf::PdmFieldHandle* objectToggleField();
virtual void fieldChangedByUi(const caf::PdmFieldHandle* changedField, const QVariant& oldValue, const QVariant& newValue);
virtual void initAfterRead();
//private:
void updateEnabledState();
};

View File

@ -16,71 +16,66 @@
//
/////////////////////////////////////////////////////////////////////////////////
#include "ssihubInterface.h"
#include "ssihubDialog.h"
#include "ssihubWebServiceInterface.h"
#include "RimOilRegionEntry.h"
#include "RimOilFieldEntry.h"
#include <math.h>
CAF_PDM_SOURCE_INIT(RimOilRegionEntry, "RimOilRegionEntry");
namespace ssihub {
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
Interface::Interface()
RimOilRegionEntry::RimOilRegionEntry()
{
m_north = HUGE_VAL;
m_south = HUGE_VAL;
m_east = HUGE_VAL;
m_west = HUGE_VAL;
}
CAF_PDM_InitObject("OilRegionEntry", "", "", "");
CAF_PDM_InitFieldNoDefault(&name, "OilRegionEntry", "OilRegionEntry", "", "", "");
CAF_PDM_InitFieldNoDefault(&fields, "Fields", "", "", "", "");
CAF_PDM_InitField(&selected, "Selected", true, "Selected", "", "", "");
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void Interface::setWebServiceAddress(const QString wsAdress)
{
m_webServiceAddress = wsAdress;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void Interface::setJsonDestinationFolder(const QString folder)
caf::PdmFieldHandle* RimOilRegionEntry::userDescriptionField()
{
m_jsonDestinationFolder = folder;
return &name;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void Interface::setRegion(int north, int south, int east, int west)
caf::PdmFieldHandle* RimOilRegionEntry::objectToggleField()
{
m_east = east;
m_west = west;
m_north = north;
m_south = south;
return &selected;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QStringList Interface::jsonWellPaths()
void RimOilRegionEntry::fieldChangedByUi(const caf::PdmFieldHandle* changedField, const QVariant& oldValue, const QVariant& newValue)
{
FetchWellPathsDialog fetchWellPaths;
fetchWellPaths.setSsiHubUrl(m_webServiceAddress);
fetchWellPaths.setDestinationFolder(m_jsonDestinationFolder);
fetchWellPaths.setRegion(m_north, m_south, m_east, m_west);
QStringList importedWellPathFiles;
if (fetchWellPaths.exec() == QDialog::Accepted)
if (&selected == changedField)
{
importedWellPathFiles = fetchWellPaths.downloadedJsonWellPathFiles();
updateState();
}
return importedWellPathFiles;
}
}; // namespace ssihub
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RimOilRegionEntry::updateState()
{
for (size_t i = 0; i < fields.size(); i++)
{
fields[i]->setUiReadOnly(!selected);
fields[i]->updateEnabledState();
}
}

View File

@ -18,38 +18,32 @@
#pragma once
#include <QString>
#include <QVariant>
#include <QMap>
#include "cafPdmObject.h"
#include "cafPdmField.h"
class QNetworkReply;
class QNetworkAccessManager;
#include "RimOilFieldEntry.h"
namespace ssihub {
class WebServiceInterface : public QObject
class RimOilRegionEntry : public caf::PdmObject
{
Q_OBJECT
CAF_PDM_HEADER_INIT;
public:
WebServiceInterface(QObject *parent = 0);
~WebServiceInterface();
RimOilRegionEntry();
void setUrl(const QString& url);
virtual caf::PdmFieldHandle* userDescriptionField();
virtual caf::PdmFieldHandle* objectToggleField();
QStringList fetchData(const QString& method, const QMap<QString, QVariant>& arguments);
virtual void fieldChangedByUi(const caf::PdmFieldHandle* changedField, const QVariant& oldValue, const QVariant& newValue);
private slots:
void onResult(QNetworkReply* reply);
caf::PdmField<QString> name;
caf::PdmField<bool> selected;
caf::PdmPointersField<RimOilFieldEntry*> fields;
private:
QString m_httpAddress;
QNetworkAccessManager* m_networkManager;
void updateState();
};
}

View File

@ -0,0 +1,188 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2011-2012 Statoil ASA, Ceetron AS
//
// 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 "RimWellPathImport.h"
namespace caf {
template<>
void caf::AppEnum< RimWellPathImport::UtmFilterEnum >::setUp()
{
addItem(RimWellPathImport::UTM_FILTER_OFF, "UTM_FILTER_OFF", "Off");
addItem(RimWellPathImport::UTM_FILTER_PROJECT, "UTM_FILTER_PROJECT", "Project");
addItem(RimWellPathImport::UTM_FILTER_CUSTOM, "UTM_FILTER_CUSTOM", "Custom");
setDefault(RimWellPathImport::UTM_FILTER_PROJECT);
}
} // End namespace caf
CAF_PDM_SOURCE_INIT(RimWellPathImport, "RimWellPathImport");
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RimWellPathImport::RimWellPathImport()
{
CAF_PDM_InitObject("RimWellPathImport", "", "", "");
CAF_PDM_InitField(&wellTypeSurvey, "WellTypeSurvey", true, "Survey", "", "", "");
CAF_PDM_InitField(&wellTypePlans, "WellTypePlans", true, "Plans", "", "", "");
caf::AppEnum<RimWellPathImport::UtmFilterEnum> defaultUtmMode = UTM_FILTER_OFF;
CAF_PDM_InitField(&utmFilterMode, "UtmMode", defaultUtmMode, "Utm filter", "", "", "");
CAF_PDM_InitField(&north, "UtmNorth", 0.0, "North", "", "", "");
CAF_PDM_InitField(&south, "UtmSouth", 0.0, "South", "", "", "");
CAF_PDM_InitField(&east, "UtmEast", 0.0, "East", "", "", "");
CAF_PDM_InitField(&west, "UtmWest", 0.0, "West", "", "", "");
CAF_PDM_InitFieldNoDefault(&regions, "Regions", "", "", "", "");
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RimWellPathImport::updateRegions(const QStringList& regionStrings, const QStringList& fieldStrings, const QStringList& edmIds)
{
assert(regionStrings.size() == fieldStrings.size() && regionStrings.size() == edmIds.size());
std::vector<RimOilRegionEntry*> regionsToRemove;
// Remove regions and fields not present in last request
for (size_t regionIdx = 0; regionIdx < this->regions.size(); regionIdx++)
{
if (!regionStrings.contains(this->regions[regionIdx]->name))
{
regionsToRemove.push_back(this->regions[regionIdx]);
}
else
{
std::vector<RimOilFieldEntry*> fieldsToRemove;
for (size_t fIdx = 0; fIdx < this->regions[regionIdx]->fields.size(); fIdx++)
{
if (!fieldStrings.contains(this->regions[regionIdx]->fields[fIdx]->name))
{
fieldsToRemove.push_back(this->regions[regionIdx]->fields[fIdx]);
}
}
for (size_t i = 0; i < fieldsToRemove.size(); i++)
{
this->regions[regionIdx]->fields.removeChildObject(fieldsToRemove[i]);
delete fieldsToRemove[i];
}
}
}
for (size_t i = 0; i < regionsToRemove.size(); i++)
{
this->regions.removeChildObject(regionsToRemove[i]);
delete regionsToRemove[i];
}
for (int i = 0; i < regionStrings.size(); i++)
{
RimOilRegionEntry* oilRegionEntry = NULL;
RimOilFieldEntry* oilFieldEntry = NULL;
for (size_t regionIdx = 0; regionIdx < this->regions.size(); regionIdx++)
{
if (this->regions[regionIdx]->name == regionStrings[i])
{
oilRegionEntry = this->regions[regionIdx];
for (size_t fIdx = 0; fIdx < this->regions[regionIdx]->fields.size(); fIdx++)
{
if (this->regions[regionIdx]->fields[fIdx]->edmId == edmIds[i])
{
oilFieldEntry = this->regions[regionIdx]->fields[fIdx];
}
}
}
}
if (!oilRegionEntry)
{
oilRegionEntry = new RimOilRegionEntry;
oilRegionEntry->name = regionStrings[i];
this->regions.push_back(oilRegionEntry);
}
assert(oilRegionEntry);
if (!oilFieldEntry)
{
RimOilFieldEntry* oilFieldEntry = new RimOilFieldEntry;
oilFieldEntry->name = fieldStrings[i];
oilFieldEntry->edmId = edmIds[i];
oilRegionEntry->fields.push_back(oilFieldEntry);
}
}
updateFieldVisibility();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RimWellPathImport::initAfterRead()
{
updateFieldVisibility();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RimWellPathImport::updateFieldVisibility()
{
if (utmFilterMode == UTM_FILTER_CUSTOM)
{
north.setUiReadOnly(false);
south.setUiReadOnly(false);
east.setUiReadOnly(false);
west.setUiReadOnly(false);
}
else
{
north.setUiReadOnly(true);
south.setUiReadOnly(true);
east.setUiReadOnly(true);
west.setUiReadOnly(true);
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RimWellPathImport::fieldChangedByUi(const caf::PdmFieldHandle* changedField, const QVariant& oldValue, const QVariant& newValue)
{
if (changedField == &utmFilterMode)
{
updateFieldVisibility();
}
}

View File

@ -0,0 +1,65 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2011-2012 Statoil ASA, Ceetron AS
//
// 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 "cafPdmObject.h"
#include "cafPdmField.h"
#include "cafAppEnum.h"
#include "RimOilRegionEntry.h"
class RimWellPathImport : public caf::PdmObject
{
CAF_PDM_HEADER_INIT;
public:
enum UtmFilterEnum
{
UTM_FILTER_OFF,
UTM_FILTER_PROJECT,
UTM_FILTER_CUSTOM
};
public:
RimWellPathImport();
caf::PdmField<bool> wellTypeSurvey;
caf::PdmField<bool> wellTypePlans;
caf::PdmField< caf::AppEnum< UtmFilterEnum > > utmFilterMode;
caf::PdmField<double> north;
caf::PdmField<double> south;
caf::PdmField<double> east;
caf::PdmField<double> west;
caf::PdmPointersField<RimOilRegionEntry*> regions;
void updateRegions(const QStringList& regions, const QStringList& fields, const QStringList& edmIds);
virtual void initAfterRead();
virtual void fieldChangedByUi( const caf::PdmFieldHandle* changedField, const QVariant& oldValue, const QVariant& newValue );
//private:
void updateFieldVisibility();
};

View File

@ -0,0 +1,123 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2011-2012 Statoil ASA, Ceetron AS
//
// 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 "RimWellsEntry.h"
#include "cafAppEnum.h"
namespace caf {
template<>
void caf::AppEnum< RimWellPathEntry::WellTypeEnum >::setUp()
{
addItem(RimWellPathEntry::WELL_ALL, "WELL_ALL", "All");
addItem(RimWellPathEntry::WELL_SURVEY, "WELL_SURVEY", "Survey");
addItem(RimWellPathEntry::WELL_PLAN, "WELL_PLAN", "Plan");
setDefault(RimWellPathEntry::WELL_ALL);
}
} // End namespace caf
CAF_PDM_SOURCE_INIT(RimWellPathEntry, "RimWellPathEntry");
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RimWellPathEntry::RimWellPathEntry()
{
CAF_PDM_InitObject("WellPathEntry", "", "", "");
CAF_PDM_InitFieldNoDefault(&name, "Name", "Name", "", "", "");
CAF_PDM_InitField(&selected, "Selected", true, "Selected", "", "", "");
caf::AppEnum< RimWellPathEntry::WellTypeEnum > wellType = WELL_ALL;
CAF_PDM_InitField(&wellPathType, "WellPathType", wellType, "Well path type", "", "", "");
CAF_PDM_InitFieldNoDefault(&surveyType, "surveyType", "surveyType", "", "", "");
CAF_PDM_InitFieldNoDefault(&requestUrl, "requestUrl", "requestUrl", "", "", "");
CAF_PDM_InitFieldNoDefault(&wellPathFilePath, "wellPathFilePath", "wellPathFilePath", "", "", "");
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
caf::PdmFieldHandle* RimWellPathEntry::userDescriptionField()
{
return &name;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
caf::PdmFieldHandle* RimWellPathEntry::objectToggleField()
{
return &selected;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RimWellPathEntry* RimWellPathEntry::createWellPathEntry(const QString& name, const QString& surveyType, const QString& requestUrl, const QString& absolutePath, WellTypeEnum wellType)
{
RimWellPathEntry* entry = new RimWellPathEntry();
entry->name = name;
entry->surveyType = surveyType;
entry->requestUrl = requestUrl;
entry->wellPathType = wellType;
QString responseFilePath = undefinedWellPathLocation();
int strIndex = requestUrl.indexOf("edm/");
if (strIndex >= 0)
{
QString lastPart = requestUrl.right(requestUrl.size() - strIndex);
lastPart = lastPart.replace('/', '_');
responseFilePath = absolutePath + "/" + lastPart + ".json";
}
entry->wellPathFilePath = responseFilePath;
return entry;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString RimWellPathEntry::undefinedWellPathLocation()
{
return "UNDEFIED_WELLPATH_FILE";
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool RimWellPathEntry::isWellPathValid()
{
return (wellPathFilePath().compare(undefinedWellPathLocation()) != 0);
}

View File

@ -0,0 +1,64 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2011-2012 Statoil ASA, Ceetron AS
//
// 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 "cafPdmObject.h"
#include "cafPdmField.h"
#include "cafAppEnum.h"
class RimWellPathEntry : public caf::PdmObject
{
CAF_PDM_HEADER_INIT;
public:
enum WellTypeEnum
{
WELL_SURVEY,
WELL_PLAN,
WELL_ALL
};
public:
RimWellPathEntry();
static RimWellPathEntry* createWellPathEntry(const QString& name, const QString& surveyType, const QString& requestUrl, const QString& absolutePath, WellTypeEnum wellType);
virtual caf::PdmFieldHandle* userDescriptionField();
virtual caf::PdmFieldHandle* objectToggleField();
caf::PdmField<QString> name;
caf::PdmField<bool> selected;
caf::PdmField< caf::AppEnum< WellTypeEnum > > wellPathType;
caf::PdmField<QString> surveyType;
caf::PdmField<QString> requestUrl;
bool isWellPathValid();
caf::PdmField<QString> wellPathFilePath; // Location of the well path response
private:
static QString undefinedWellPathLocation();
};

View File

@ -0,0 +1,973 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2011-2012 Statoil ASA, Ceetron AS
//
// 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 "RiuWellImportWizard.h"
#include <QObject>
#include <QtGui>
#include <QtNetwork>
#include "cafPdmUiPropertyView.h"
#include "cafPdmUiTreeView.h"
#include "cafPdmDocument.h"
#include "cafPdmUiListViewEditor.h"
#include "cafPdmUiListView.h"
#include "cafUiTreeModelPdm.h"
#include "RimWellPathImport.h"
#include "RifJsonEncodeDecode.h"
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RiuWellImportWizard::RiuWellImportWizard(const QString& webServiceAddress, const QString& downloadFolder, RimWellPathImport* wellPathImportObject, QWidget *parent /*= 0*/)
: QWizard(parent)
{
m_wellPathImportObject = wellPathImportObject;
m_destinationFolder = downloadFolder;
m_webServiceAddress = webServiceAddress;
m_progressDialog = new QProgressDialog(this);
m_firstTimeRequestingAuthentication = true;
addPage(new AuthenticationPage(webServiceAddress, this));
m_fieldSelectionPageId = addPage(new FieldSelectionPage(m_wellPathImportObject, this));
m_wellSelectionPageId = addPage(new WellSelectionPage(m_wellPathImportObject, this));
m_wellSummaryPageId = addPage(new WellSummaryPage(m_wellPathImportObject, this));
connect(this, SIGNAL(currentIdChanged(int)), SLOT(slotCurrentIdChanged(int)));
connect(&m_networkAccessManager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)),
this, SLOT(slotAuthenticationRequired(QNetworkReply*,QAuthenticator*)));
#ifndef QT_NO_OPENSSL
connect(&m_networkAccessManager, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)),
this, SLOT(sslErrors(QNetworkReply*,QList<QSslError>)));
#endif
connect(m_progressDialog, SIGNAL(canceled()), this, SLOT(cancelDownload()));
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString RiuWellImportWizard::jsonFieldsFilePath()
{
return m_destinationFolder + "/fields.json";
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString RiuWellImportWizard::jsonWellsFilePath()
{
return m_destinationFolder + "/wellpaths.json";
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiuWellImportWizard::downloadFields()
{
QString wellFileName = jsonWellsFilePath();
if (QFile::exists(wellFileName))
{
QFile::remove(wellFileName);
}
QString completeUrlText = m_webServiceAddress + "/resinsight/projects";
QString destinationFileName = jsonFieldsFilePath();
m_currentDownloadState = DOWNLOAD_FIELDS;
issueHttpRequestToFile(completeUrlText, destinationFileName);
return;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiuWellImportWizard::issueHttpRequestToFile(QString completeUrlText, QString destinationFileName)
{
setUrl(completeUrlText);
m_file = new QFile(destinationFileName);
if (!m_file->open(QIODevice::WriteOnly)) {
QMessageBox::information(this, tr("HTTP"),
tr("Unable to save the file %1: %2.")
.arg(destinationFileName).arg(m_file->errorString()));
delete m_file;
m_file = 0;
return;
}
m_progressDialog->setWindowTitle(tr("HTTP"));
m_progressDialog->setLabelText(tr("Downloading %1.").arg(destinationFileName));
// schedule the request
m_httpRequestAborted = false;
startRequest(m_url);
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiuWellImportWizard::cancelDownload()
{
//m_statusLabel->setText(tr("Download canceled."));
m_httpRequestAborted = true;
m_reply->abort();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiuWellImportWizard::httpFinished()
{
if (m_httpRequestAborted) {
if (m_file) {
m_file->close();
m_file->remove();
delete m_file;
m_file = 0;
}
m_reply->deleteLater();
m_progressDialog->hide();
return;
}
m_file->flush();
m_file->close();
QVariant redirectionTarget = m_reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
if (m_reply->error()) {
m_file->remove();
QMessageBox::information(this, tr("HTTP"),
tr("Download failed: %1.")
.arg(m_reply->errorString()));
} else if (!redirectionTarget.isNull()) {
QUrl newUrl = m_url.resolved(redirectionTarget.toUrl());
if (QMessageBox::question(this, tr("HTTP"),
tr("Redirect to %1 ?").arg(newUrl.toString()),
QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) {
m_url = newUrl;
m_reply->deleteLater();
m_file->open(QIODevice::WriteOnly);
m_file->resize(0);
startRequest(m_url);
return;
}
} else {
//m_statusLabel->setText(tr("Downloaded data to %1.").arg(m_destinationFolder));
}
if (m_currentDownloadState == DOWNLOAD_WELL_PATH)
{
QString singleWellPathFilePath = m_file->fileName();
QFile file(singleWellPathFilePath);
if (file.open(QFile::ReadOnly))
{
QString singleWellPathContent = file.readAll();
// Strip leading and trailing []
if (singleWellPathContent.indexOf('{') > 0)
{
singleWellPathContent = singleWellPathContent.right(singleWellPathContent.size() - singleWellPathContent.indexOf('{'));
}
if (singleWellPathContent[singleWellPathContent.size() - 1] == ']')
{
singleWellPathContent = singleWellPathContent.left(singleWellPathContent.size() - 1);
}
QString wellPathName = getValue("name", singleWellPathContent);
if (!singleWellPathContent.isEmpty() && !wellPathName.isEmpty())
{
// Write out the content without leading/trailing []
file.close();
file.remove(singleWellPathFilePath);
if (file.open(QFile::WriteOnly))
{
QTextStream out(&file);
out << singleWellPathContent;
}
}
}
}
m_reply->deleteLater();
m_reply = 0;
delete m_file;
m_file = 0;
if (m_currentDownloadState == DOWNLOAD_WELLS || m_currentDownloadState == DOWNLOAD_WELL_PATH)
{
checkDownloadQueueAndIssueRequests();
}
else if (m_currentDownloadState == DOWNLOAD_FIELDS)
{
updateFieldsModel();
m_currentDownloadState = DOWNLOAD_UNDEFINED;
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiuWellImportWizard::httpReadyRead()
{
// this slot gets called every time the QNetworkReply has new data.
// We read all of its new data and write it into the file.
// That way we use less RAM than when reading it at the finished()
// signal of the QNetworkReply
if (m_file)
m_file->write(m_reply->readAll());
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiuWellImportWizard::updateDataReadProgress(qint64 bytesRead, qint64 totalBytes)
{
if (m_httpRequestAborted)
return;
m_progressDialog->setMaximum(totalBytes);
m_progressDialog->setValue(bytesRead);
}
//--------------------------------------------------------------------------------------------------
/// This slot will be called for the first network reply that will need authentication.
/// If the authentication is successful, the username/password is cached in the QNetworkAccessManager
//--------------------------------------------------------------------------------------------------
void RiuWellImportWizard::slotAuthenticationRequired(QNetworkReply* networkReply, QAuthenticator* authenticator)
{
if (m_firstTimeRequestingAuthentication)
{
// Use credentials from first wizard page
authenticator->setUser(field("username").toString());
authenticator->setPassword(field("password").toString());
m_firstTimeRequestingAuthentication = false;
}
else
{
QMessageBox::information(this, "Authentication failed", "Failed to authenticate credentials. You will now be directed back to the first wizard page.");
m_firstTimeRequestingAuthentication = true;
restart();
}
}
#ifndef QT_NO_OPENSSL
void RiuWellImportWizard::sslErrors(QNetworkReply*,const QList<QSslError> &errors)
{
QString errorString;
foreach (const QSslError &error, errors) {
if (!errorString.isEmpty())
errorString += ", ";
errorString += error.errorString();
}
if (QMessageBox::warning(this, tr("HTTP"),
tr("One or more SSL errors has occurred: %1").arg(errorString),
QMessageBox::Ignore | QMessageBox::Abort) == QMessageBox::Ignore) {
m_reply->ignoreSslErrors();
}
}
#endif
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiuWellImportWizard::setUrl(const QString& httpAddress)
{
m_url = httpAddress;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiuWellImportWizard::startRequest(QUrl url)
{
m_reply = m_networkAccessManager.get(QNetworkRequest(url));
connect(m_reply, SIGNAL(finished()),
this, SLOT(httpFinished()));
connect(m_reply, SIGNAL(readyRead()),
this, SLOT(httpReadyRead()));
connect(m_reply, SIGNAL(downloadProgress(qint64,qint64)),
this, SLOT(updateDataReadProgress(qint64,qint64)));
}
//--------------------------------------------------------------------------------------------------
/// Search for string, and find the associated value inside the next quoted string
// text content : "A" : "B"
// A search for key "A" returns B
//--------------------------------------------------------------------------------------------------
QString RiuWellImportWizard::getValue(const QString& key, const QString& stringContent)
{
QString quotedKey = "\"" + key + "\"";
int pos = stringContent.indexOf(quotedKey);
if (pos >=0)
{
int valueStartPos = stringContent.indexOf("\"", pos + quotedKey.size());
int valueEndPos = stringContent.indexOf("\"", valueStartPos + 1);
if (valueStartPos >= 0 && valueEndPos > valueStartPos)
{
return stringContent.mid(valueStartPos + 1, valueEndPos - valueStartPos - 1);
}
}
return QString();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiuWellImportWizard::updateFieldsModel()
{
QString fileName = jsonFieldsFilePath();
if (QFile::exists(fileName))
{
JsonReader jsonReader;
QMap<QString, QVariant> jsonMap = jsonReader.decodeFile(fileName);
QStringList regions;
QStringList fields;
QStringList edmIds;
QMapIterator<QString, QVariant> it(jsonMap);
while (it.hasNext())
{
it.next();
// If we have an array, skip to next node
if (it.key() == "length")
continue;
QMap<QString, QVariant> fieldMap = it.value().toMap();
regions.push_back(fieldMap["region"].toString());
fields.push_back(fieldMap["name"].toString());
edmIds.push_back(fieldMap["edmId"].toString());
}
m_wellPathImportObject->updateRegions(regions, fields, edmIds);
m_wellPathImportObject->updateConnectedEditors();
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiuWellImportWizard::downloadWells()
{
for (size_t rIdx = 0; rIdx < m_wellPathImportObject->regions.size(); rIdx++)
{
RimOilRegionEntry* oilRegion = m_wellPathImportObject->regions[rIdx];
if (oilRegion->selected)
{
for (size_t fIdx = 0; fIdx < oilRegion->fields.size(); fIdx++)
{
RimOilFieldEntry* oilField = oilRegion->fields[fIdx];
if (oilField->selected)
{
DownloadEntity urlToFile;
QString wellRequest;
if (m_wellPathImportObject->utmFilterMode == RimWellPathImport::UTM_FILTER_OFF)
{
wellRequest = QString("/resinsight/projects/%1/wells").arg(oilField->edmId);
}
else
{
wellRequest = QString("/resinsight/projects/%1/wellsInArea?north=%2&south=%3&east=%4&west=%5&utmZone=32N")
.arg(oilField->edmId)
.arg(QString::number(m_wellPathImportObject->north, 'g', 10))
.arg(QString::number(m_wellPathImportObject->south, 'g', 10))
.arg(QString::number(m_wellPathImportObject->east, 'g', 10))
.arg(QString::number(m_wellPathImportObject->west, 'g', 10));
}
urlToFile.requestUrl = m_webServiceAddress + wellRequest;
urlToFile.responseFilename = m_destinationFolder + QString("/wells_%1.json").arg(oilField->edmId);
oilField->wellsFilePath = urlToFile.responseFilename;
m_wellRequestQueue.push_back(urlToFile);
}
}
}
}
m_currentDownloadState = DOWNLOAD_WELLS;
checkDownloadQueueAndIssueRequests();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiuWellImportWizard::downloadWellPaths()
{
for (size_t rIdx = 0; rIdx < m_wellPathImportObject->regions.size(); rIdx++)
{
RimOilRegionEntry* oilRegion = m_wellPathImportObject->regions[rIdx];
if (oilRegion->selected)
{
for (size_t fIdx = 0; fIdx < oilRegion->fields.size(); fIdx++)
{
RimOilFieldEntry* oilField = oilRegion->fields[fIdx];
if (oilField->selected)
{
for (size_t wIdx = 0; wIdx < oilField->wells.size(); wIdx++)
{
RimWellPathEntry* wellPathEntry = oilField->wells[wIdx];
if (!wellPathEntry->isWellPathValid())
continue;
DownloadEntity urlToFile;
urlToFile.requestUrl = wellPathEntry->requestUrl;
urlToFile.responseFilename = wellPathEntry->wellPathFilePath;
m_wellRequestQueue.push_back(urlToFile);
}
}
}
}
}
m_currentDownloadState = DOWNLOAD_WELL_PATH;
checkDownloadQueueAndIssueRequests();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiuWellImportWizard::checkDownloadQueueAndIssueRequests()
{
if (m_wellRequestQueue.size() > 0)
{
DownloadEntity firstItem = m_wellRequestQueue[0];
m_wellRequestQueue.pop_front();
QString completeUrlText = firstItem.requestUrl;
QString absoluteFilePath = firstItem.responseFilename;
issueHttpRequestToFile(completeUrlText, absoluteFilePath);
return;
}
if (m_currentDownloadState == DOWNLOAD_WELLS)
{
// Update UI with downloaded wells
for (size_t rIdx = 0; rIdx < m_wellPathImportObject->regions.size(); rIdx++)
{
RimOilRegionEntry* oilRegion = m_wellPathImportObject->regions[rIdx];
if (oilRegion->selected)
{
for (size_t fIdx = 0; fIdx < oilRegion->fields.size(); fIdx++)
{
RimOilFieldEntry* oilField = oilRegion->fields[fIdx];
if (oilField->selected)
{
parseWellsResponse(oilField);
}
}
}
}
m_wellPathImportObject->updateConnectedEditors();
}
else if (m_currentDownloadState == DOWNLOAD_WELL_PATH)
{
WellSummaryPage* wellSummaryPage = dynamic_cast<WellSummaryPage*>(page(m_wellSummaryPageId));
if (wellSummaryPage)
{
wellSummaryPage->updateSummaryPage();
}
}
m_currentDownloadState = DOWNLOAD_UNDEFINED;
m_progressDialog->hide();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiuWellImportWizard::resetAuthenticationCount()
{
m_firstTimeRequestingAuthentication = true;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QStringList RiuWellImportWizard::absoluteFilePathsToWellPaths() const
{
QStringList filePaths;
for (size_t rIdx = 0; rIdx < m_wellPathImportObject->regions.size(); rIdx++)
{
RimOilRegionEntry* oilRegion = m_wellPathImportObject->regions[rIdx];
if (oilRegion->selected)
{
for (size_t fIdx = 0; fIdx < oilRegion->fields.size(); fIdx++)
{
RimOilFieldEntry* oilField = oilRegion->fields[fIdx];
if (oilField->selected)
{
for (size_t wIdx = 0; wIdx < oilField->wells.size(); wIdx++)
{
RimWellPathEntry* wellPathEntry = oilField->wells[wIdx];
QString wellStatus;
if (QFile::exists(oilField->wells[wIdx]->wellPathFilePath))
{
filePaths += oilField->wells[wIdx]->wellPathFilePath;
}
}
}
}
}
}
return filePaths;
}
//--------------------------------------------------------------------------------------------------
/// Set wells hidden from the field selection page
/// TODO: This can be refactored when UIOrdering for objects is created
//--------------------------------------------------------------------------------------------------
void RiuWellImportWizard::slotCurrentIdChanged(int currentId)
{
bool hideWells = true;
if (currentId == m_wellSelectionPageId) hideWells = false;
for (size_t rIdx = 0; rIdx < m_wellPathImportObject->regions.size(); rIdx++)
{
RimOilRegionEntry* oilRegion = m_wellPathImportObject->regions[rIdx];
{
for (size_t fIdx = 0; fIdx < oilRegion->fields.size(); fIdx++)
{
RimOilFieldEntry* oilField = oilRegion->fields[fIdx];
oilField->wells.setUiHidden(hideWells);
}
}
}
// Update the editors to propagate the changes to UI
m_wellPathImportObject->updateConnectedEditors();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiuWellImportWizard::parseWellsResponse(RimOilFieldEntry* oilFieldEntry)
{
QStringList surveyNames;
QStringList planNames;
if (QFile::exists(oilFieldEntry->wellsFilePath))
{
JsonReader jsonReader;
QMap<QString, QVariant> jsonMap = jsonReader.decodeFile(oilFieldEntry->wellsFilePath);
QMapIterator<QString, QVariant> it(jsonMap);
while (it.hasNext())
{
it.next();
// If we have an array, skip to next node
if (it.key() == "length")
continue;
QMap<QString, QVariant> rootMap = it.value().toMap();
if (m_wellPathImportObject->wellTypeSurvey)
{
QMap<QString, QVariant> surveyMap = rootMap["survey"].toMap();
QString name = surveyMap["name"].toString();
if (!oilFieldEntry->find(name, RimWellPathEntry::WELL_SURVEY))
{
QMap<QString, QVariant> linksMap = surveyMap["links"].toMap();
QString requestUrl = m_webServiceAddress + linksMap["entity"].toString();
QString surveyType = surveyMap["surveyType"].toString();
RimWellPathEntry* surveyWellPathEntry = RimWellPathEntry::createWellPathEntry(name, surveyType, requestUrl, m_destinationFolder, RimWellPathEntry::WELL_SURVEY);
oilFieldEntry->wells.push_back(surveyWellPathEntry);
}
surveyNames.push_back(name);
}
if (m_wellPathImportObject->wellTypePlans)
{
QList<QVariant> plansList = rootMap["plans"].toList();
QListIterator<QVariant> planIt(plansList);
while (planIt.hasNext())
{
QMap<QString, QVariant> planMap = planIt.next().toMap();
QString name = planMap["name"].toString();
if (!oilFieldEntry->find(name, RimWellPathEntry::WELL_PLAN))
{
QMap<QString, QVariant> linksMap = planMap["links"].toMap();
QString requestUrl = m_webServiceAddress + linksMap["entity"].toString();
QString surveyType = planMap["surveyType"].toString();
RimWellPathEntry* surveyWellPathEntry = RimWellPathEntry::createWellPathEntry(name, surveyType, requestUrl, m_destinationFolder, RimWellPathEntry::WELL_PLAN);
oilFieldEntry->wells.push_back(surveyWellPathEntry);
}
planNames.push_back(name);
}
}
}
}
// Delete the well path entries in the model that are not part of the reply from the web service
std::vector<RimWellPathEntry*> wellsToRemove;
for (size_t i = 0; i < oilFieldEntry->wells.size(); i++)
{
RimWellPathEntry* wellPathEntry = oilFieldEntry->wells[i];
if (wellPathEntry->wellPathType == RimWellPathEntry::WELL_PLAN)
{
if (!planNames.contains(wellPathEntry->name))
{
wellsToRemove.push_back(wellPathEntry);
}
}
else
{
if (!surveyNames.contains(wellPathEntry->name))
{
wellsToRemove.push_back(wellPathEntry);
}
}
}
for (size_t i = 0; i < wellsToRemove.size(); i++)
{
oilFieldEntry->wells.removeChildObject(wellsToRemove[i]);
delete wellsToRemove[i];
}
WellSelectionPage* wellSelectionPage = dynamic_cast<WellSelectionPage*>(page(m_wellSelectionPageId));
if (wellSelectionPage)
wellSelectionPage->expandAllTreeNodes();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiuWellImportWizard::setCredentials(const QString& username, const QString& password)
{
// Set the initial value of the fields defined in the Authorization page
setField("username", username);
setField("password", password);
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
AuthenticationPage::AuthenticationPage(const QString& webServiceAddress, QWidget *parent /*= 0*/) : QWizardPage(parent)
{
setTitle("SSIHUB - Login");
QVBoxLayout* layout = new QVBoxLayout;
QLabel* label = new QLabel("Please enter your login information for SSIHUB at : " + webServiceAddress);
layout->addWidget(label);
QFormLayout* formLayout = new QFormLayout;
layout->addLayout(formLayout);
QLineEdit* usernameLineEdit = new QLineEdit("", this);
QLineEdit* passwordlLineEdit = new QLineEdit("", this);
passwordlLineEdit->setEchoMode(QLineEdit::Password);
formLayout->addRow("&Username:", usernameLineEdit);
formLayout->addRow("&Password:", passwordlLineEdit);
setLayout(layout);
// Make variables accessible to other pages in wizard
// Use * at end of field name to indicate mandatory field
registerField("username", usernameLineEdit);
registerField("password", passwordlLineEdit);
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void AuthenticationPage::initializePage()
{
RiuWellImportWizard* wiz = dynamic_cast<RiuWellImportWizard*>(wizard());
wiz->resetAuthenticationCount();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
FieldSelectionPage::FieldSelectionPage(RimWellPathImport* wellPathImport, QWidget *parent /*= 0*/)
{
setTitle("Field Selection");
QVBoxLayout* layout = new QVBoxLayout;
setLayout(layout);
QLabel* label = new QLabel("Select fields");
layout->addWidget(label);
// Tree view
caf::PdmUiTreeView* treeView = new caf::PdmUiTreeView(this);
treeView->setPdmObject(wellPathImport);
layout->addWidget(treeView);
layout->setStretchFactor(treeView, 10);
// Property view
caf::PdmUiPropertyView* propertyView = new caf::PdmUiPropertyView(this);
layout->addWidget(propertyView);
propertyView->showProperties(wellPathImport);
setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding));
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void FieldSelectionPage::initializePage()
{
RiuWellImportWizard* wiz = dynamic_cast<RiuWellImportWizard*>(wizard());
wiz->downloadFields();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
WellSelectionPage::WellSelectionPage(RimWellPathImport* wellPathImport, QWidget* parent /*= 0*/)
{
QVBoxLayout* layout = new QVBoxLayout;
setLayout(layout);
QLabel* label = new QLabel("Select wells");
layout->addWidget(label);
m_wellSelectionTreeView = new caf::PdmUiTreeView(this);
layout->addWidget(m_wellSelectionTreeView);
m_wellPathImportObject = wellPathImport;
m_regionsWithVisibleWells = new caf::PdmObjectGroup;
//m_wellSelectionTreeView->setPdmObject(wellPathImport);
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void WellSelectionPage::initializePage()
{
RiuWellImportWizard* wiz = dynamic_cast<RiuWellImportWizard*>(wizard());
if (!wiz) return;
wiz->downloadWells();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void WellSelectionPage::expandAllTreeNodes()
{
m_regionsWithVisibleWells->objects.clear();
for (size_t rIdx = 0; rIdx < m_wellPathImportObject->regions.size(); rIdx++)
{
RimOilRegionEntry* oilRegion = m_wellPathImportObject->regions[rIdx];
if (oilRegion->selected)
{
m_regionsWithVisibleWells->objects.push_back(oilRegion);
}
}
m_wellSelectionTreeView->setPdmObject(m_regionsWithVisibleWells);
m_regionsWithVisibleWells->updateConnectedEditors();
//m_wellSelectionTreeView->treeView()->expandAll();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
WellSelectionPage::~WellSelectionPage()
{
delete m_regionsWithVisibleWells;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
WellSummaryPage::WellSummaryPage(RimWellPathImport* wellPathImport, QWidget* parent /*= 0*/)
{
m_wellPathImportObject = wellPathImport;
QVBoxLayout* layout = new QVBoxLayout;
setLayout(layout);
m_textEdit = new QTextEdit(this);
m_textEdit->setReadOnly(true);
layout->addWidget(m_textEdit);
QPushButton* button = new QPushButton("Details", this);
connect(button, SIGNAL(clicked()), this, SLOT(slotShowDetails()));
layout->addWidget(button);
m_listView = new caf::PdmUiListView(this);
layout->addWidget(m_listView);
m_listView->hide();
m_objectGroup = new caf::PdmObjectGroup;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void WellSummaryPage::initializePage()
{
RiuWellImportWizard* wiz = dynamic_cast<RiuWellImportWizard*>(wizard());
wiz->downloadWellPaths();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void WellSummaryPage::updateSummaryPage()
{
m_objectGroup->objects.clear();
m_textEdit->setText("Summary of imported wells\n\n");
size_t wellPathCount = 0;
QString errorString;
for (size_t rIdx = 0; rIdx < m_wellPathImportObject->regions.size(); rIdx++)
{
RimOilRegionEntry* oilRegion = m_wellPathImportObject->regions[rIdx];
if (oilRegion->selected)
{
for (size_t fIdx = 0; fIdx < oilRegion->fields.size(); fIdx++)
{
RimOilFieldEntry* oilField = oilRegion->fields[fIdx];
if (oilField->selected)
{
QString oilFieldText = QString("\nRegion : %1 - Field : %2").arg(oilRegion->name).arg(oilField->name);
m_textEdit->append(oilFieldText);
for (size_t wIdx = 0; wIdx < oilField->wells.size(); wIdx++)
{
RimWellPathEntry* wellPathEntry = oilField->wells[wIdx];
if (QFile::exists(oilField->wells[wIdx]->wellPathFilePath))
{
wellPathCount++;
}
else
{
errorString += QString("Failed to get file '%1' from well '%2'\n").arg(oilField->wells[wIdx]->wellPathFilePath).arg(oilField->wells[wIdx]->name);
}
m_objectGroup->objects.push_back(wellPathEntry);
}
}
}
}
}
m_textEdit->setText(QString("Downloaded successfully %1 well paths.\nPlease push 'Finish' button to import well paths into ResInsight.\n\n").arg(wellPathCount));
if (!errorString.isEmpty())
{
m_textEdit->append("Detected following errors during well path download. See details below.");
m_textEdit->append(errorString);
}
m_listView->setPdmObject(m_objectGroup);
m_objectGroup->updateConnectedEditors();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void WellSummaryPage::slotShowDetails()
{
m_listView->show();
}

View File

@ -0,0 +1,216 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2011-2012 Statoil ASA, Ceetron AS
//
// 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 <QString>
#include <QWizard>
#include <QNetworkAccessManager>
#include <QUrl>
#include <QItemSelection>
#include <QNetworkReply>
class QFile;
class QProgressDialog;
class QLabel;
class QTextEdit;
class RimWellPathImport;
class RimOilFieldEntry;
namespace caf
{
class UiTreeModelPdm;
class PdmUiTreeView;
class PdmUiListView;
class PdmObjectGroup;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
class AuthenticationPage : public QWizardPage
{
Q_OBJECT
public:
AuthenticationPage(const QString& webServiceAddress, QWidget *parent = 0);
virtual void initializePage();
};
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
class FieldSelectionPage : public QWizardPage
{
Q_OBJECT
public:
FieldSelectionPage(RimWellPathImport* wellPathImport, QWidget* parent = 0);
virtual void initializePage();
};
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
class WellSelectionPage : public QWizardPage
{
Q_OBJECT
public:
WellSelectionPage(RimWellPathImport* wellPathImport, QWidget* parent = 0);
~WellSelectionPage();
virtual void initializePage();
void expandAllTreeNodes();
private:
caf::PdmObjectGroup* m_regionsWithVisibleWells;
RimWellPathImport* m_wellPathImportObject;
caf::PdmUiTreeView* m_wellSelectionTreeView;
};
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
class WellSummaryPage : public QWizardPage
{
Q_OBJECT
public:
WellSummaryPage(RimWellPathImport* wellPathImport, QWidget* parent = 0);
virtual void initializePage();
void updateSummaryPage();
private slots:
void slotShowDetails();
private:
RimWellPathImport* m_wellPathImportObject;
QTextEdit* m_textEdit;
caf::PdmUiListView* m_listView;
caf::PdmObjectGroup*m_objectGroup;
};
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
class DownloadEntity
{
public:
QString requestUrl;
QString responseFilename;
};
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
class RiuWellImportWizard : public QWizard
{
Q_OBJECT
public:
enum DownloadState{ DOWNLOAD_FIELDS, DOWNLOAD_WELLS, DOWNLOAD_WELL_PATH, DOWNLOAD_UNDEFINED};
public:
RiuWellImportWizard(const QString& webServiceAddress, const QString& downloadFolder, RimWellPathImport* wellPathImportObject, QWidget *parent = 0);
void setCredentials(const QString& username, const QString& password);
QStringList absoluteFilePathsToWellPaths() const;
// Methods used from the wizard pages
caf::PdmObjectGroup* wellCollection();
void resetAuthenticationCount();
public slots:
void downloadWellPaths();
void downloadWells();
void downloadFields();
void checkDownloadQueueAndIssueRequests();
void issueHttpRequestToFile( QString completeUrlText, QString destinationFileName );
void cancelDownload();
void httpFinished();
void httpReadyRead();
void updateDataReadProgress(qint64 bytesRead, qint64 totalBytes);
void slotAuthenticationRequired(QNetworkReply* networkReply, QAuthenticator* authenticator);
#ifndef QT_NO_OPENSSL
void sslErrors(QNetworkReply*,const QList<QSslError> &errors);
#endif
private slots:
void slotCurrentIdChanged(int currentId);
private:
void startRequest(QUrl url);
void setUrl(const QString& httpAddress);
QString jsonFieldsFilePath();
QString jsonWellsFilePath();
void updateFieldsModel();
void parseWellsResponse(RimOilFieldEntry* oilFieldEntry);
QString getValue(const QString& key, const QString& stringContent);
private:
QString m_webServiceAddress;
QString m_destinationFolder;
RimWellPathImport* m_wellPathImportObject;
caf::PdmUiTreeView* m_pdmTreeView;
QProgressDialog* m_progressDialog;
QUrl m_url;
QNetworkAccessManager m_networkAccessManager;
QNetworkReply* m_reply;
QFile* m_file;
bool m_httpRequestAborted;
bool m_firstTimeRequestingAuthentication;
QList<DownloadEntity> m_wellRequestQueue;
DownloadState m_currentDownloadState;
int m_fieldSelectionPageId;
int m_wellSelectionPageId;
int m_wellSummaryPageId;
};

View File

@ -1,6 +1,6 @@
cmake_minimum_required (VERSION 2.8)
project ( ssihubTestApplication )
project ( WellPathImportSsihubTestApp )
set (QT_COMPONENTS_REQUIRED QtCore QtGui QtMain QtOpenGl QtNetwork QtScript QtScriptTools)
@ -11,10 +11,17 @@ include (${QT_USE_FILE})
find_package( OpenGL )
add_subdirectory(../ssihubInterface "${CMAKE_CURRENT_BINARY_DIR}/ssihubInterface")
add_subdirectory(../WellPathImportSsihub "${CMAKE_CURRENT_BINARY_DIR}/WellPathImportSsihub")
add_subdirectory(../../cafProjectDataModel "${CMAKE_CURRENT_BINARY_DIR}/cafProjectDataModel")
add_subdirectory(../../cafUserInterface "${CMAKE_CURRENT_BINARY_DIR}/cafUserInterface")
add_subdirectory(../../cafTests/cafTestApplication "${CMAKE_CURRENT_BINARY_DIR}/cafTestApplication")
include_directories(
${ssihubInterface_SOURCE_DIR}
${WellPathImportSsihub_SOURCE_DIR}
${CMAKE_CURRENT_SOURCE_DIR}/../../cafProjectDataModel
${CMAKE_CURRENT_SOURCE_DIR}/../../cafUserInterface
)
@ -39,12 +46,18 @@ qt4_add_resources( QRC_FILES_CPP
# add the executable
add_executable ( ${PROJECT_NAME}
main.cpp
TestTools.cpp
TestTools.h
${MOC_FILES_CPP}
${QRC_FILES_CPP}
)
target_link_libraries ( ${PROJECT_NAME}
ssihubInterface
cafProjectDataModel
cafUserInterface
WellPathImportSsihub
${QT_LIBRARIES}
)

View File

@ -0,0 +1,52 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2011-2012 Statoil ASA, Ceetron AS
//
// 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 "TestTools.h"
#include "RimWellPathImport.h"
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RimWellPathImport* TestTools::createMockObject()
{
RimWellPathImport* wellPathImport = new RimWellPathImport;
RimOilRegionEntry* regionA = new RimOilRegionEntry;
regionA->name = "Region A";
RimOilFieldEntry* fieldA = new RimOilFieldEntry;
fieldA->name = "test a";
fieldA->edmId = "edm1";
RimOilFieldEntry* fieldB = new RimOilFieldEntry;
fieldB->name = "test b";
fieldB->edmId = "edm b";
regionA->fields.push_back(fieldA);
wellPathImport->regions.push_back(regionA);
RimOilRegionEntry* regionB = new RimOilRegionEntry;
regionB->name = "Region B";
wellPathImport->regions.push_back(regionB);
wellPathImport->utmFilterMode = RimWellPathImport::UTM_FILTER_PROJECT;
return wellPathImport;
}

View File

@ -18,31 +18,11 @@
#pragma once
#include <QString>
#include <QStringList>
class RimWellPathImport;
namespace ssihub {
class Interface
class TestTools
{
public:
Interface();
void setWebServiceAddress(const QString wsAdress);
void setJsonDestinationFolder(const QString folder);
void setRegion(int north, int south, int east, int west);
QStringList jsonWellPaths();
private:
QString m_webServiceAddress;
QString m_jsonDestinationFolder;
int m_east;
int m_west;
int m_north;
int m_south;
static RimWellPathImport* createMockObject();
};
}

View File

@ -41,7 +41,13 @@
#include <QApplication>
#include <QDir>
#include "ssihubInterface.h"
#include "TestTools.h"
#include "RiuWellImportWizard.h"
#include "RimWellPathImport.h"
int main(int argc, char *argv[])
{
@ -51,23 +57,25 @@ int main(int argc, char *argv[])
QString destinationFolder("c:/tmp/resinsight_ws");
QString wsAddress("http://127.0.0.1:5000");
ssihub::Interface wsInterface;
wsInterface.setWebServiceAddress(wsAddress);
wsInterface.setJsonDestinationFolder(destinationFolder);
int north = 7500000;
int south = 7000000;
int east = 401000;
int west = 400000;
wsInterface.setRegion(north, south, east, west);
QStringList jsonWellPathFileNames = wsInterface.jsonWellPaths();
RimWellPathImport* wellPathImportObject = TestTools::createMockObject();
wellPathImportObject->north = north;
wellPathImportObject->south = south;
wellPathImportObject->east = east;
wellPathImportObject->west = west;
// void setWebServiceAddress(const QString wsAdress);
// void setJsonDestinationFolder(const QString folder);
// void setRegion(int east, int west, int north, int south);
//
// QStringList jsonWellPaths();
QString username("admin");
QString password("resinsight");
RiuWellImportWizard wizard(wsAddress, destinationFolder, wellPathImportObject);
wizard.setCredentials(username, password);
wizard.show();
return app.exec();

View File

@ -1,129 +0,0 @@
<ui version="4.0" >
<class>Dialog</class>
<widget class="QDialog" name="Dialog" >
<property name="geometry" >
<rect>
<x>0</x>
<y>0</y>
<width>389</width>
<height>243</height>
</rect>
</property>
<property name="windowTitle" >
<string>Http authentication required</string>
</property>
<layout class="QGridLayout" >
<item row="0" column="0" colspan="2" >
<widget class="QLabel" name="label" >
<property name="text" >
<string>You need to supply a Username and a Password to access this site</string>
</property>
<property name="wordWrap" >
<bool>false</bool>
</property>
</widget>
</item>
<item row="2" column="0" >
<widget class="QLabel" name="label_2" >
<property name="text" >
<string>Username:</string>
</property>
</widget>
</item>
<item row="2" column="1" >
<widget class="QLineEdit" name="userEdit" />
</item>
<item row="3" column="0" >
<widget class="QLabel" name="label_3" >
<property name="text" >
<string>Password:</string>
</property>
</widget>
</item>
<item row="3" column="1" >
<widget class="QLineEdit" name="passwordEdit" />
</item>
<item row="5" column="0" colspan="2" >
<widget class="QDialogButtonBox" name="buttonBox" >
<property name="orientation" >
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons" >
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
</property>
</widget>
</item>
<item row="1" column="0" >
<widget class="QLabel" name="label_4" >
<property name="text" >
<string>Site:</string>
</property>
</widget>
</item>
<item row="1" column="1" >
<widget class="QLabel" name="siteDescription" >
<property name="font" >
<font>
<weight>75</weight>
<bold>true</bold>
</font>
</property>
<property name="text" >
<string>%1 at %2</string>
</property>
<property name="wordWrap" >
<bool>true</bool>
</property>
</widget>
</item>
<item row="4" column="0" >
<spacer>
<property name="orientation" >
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" >
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
</layout>
</widget>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>Dialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel" >
<x>248</x>
<y>254</y>
</hint>
<hint type="destinationlabel" >
<x>157</x>
<y>274</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonBox</sender>
<signal>rejected()</signal>
<receiver>Dialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel" >
<x>316</x>
<y>260</y>
</hint>
<hint type="destinationlabel" >
<x>286</x>
<y>274</y>
</hint>
</hints>
</connection>
</connections>
</ui>

View File

@ -1,298 +0,0 @@
/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
** the names of its contributors may be used to endorse or promote
** products derived from this software without specific prior written
** permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtGui>
#include <QtNetwork>
#include "httpwindow.h"
#include "ui_authenticationdialog.h"
HttpWindow::HttpWindow(QWidget *parent)
#ifdef Q_WS_MAEMO_5
: QWidget(parent)
#else
: QDialog(parent)
#endif
{
#ifndef QT_NO_OPENSSL
urlLineEdit = new QLineEdit("https://qt.nokia.com/");
#else
urlLineEdit = new QLineEdit("http://qt.nokia.com/");
#endif
urlLabel = new QLabel(tr("&URL:"));
urlLabel->setBuddy(urlLineEdit);
statusLabel = new QLabel(tr("Please enter the URL of a file you want to "
"download."));
statusLabel->setWordWrap(true);
downloadButton = new QPushButton(tr("Download"));
downloadButton->setDefault(true);
quitButton = new QPushButton(tr("Quit"));
quitButton->setAutoDefault(false);
buttonBox = new QDialogButtonBox;
buttonBox->addButton(downloadButton, QDialogButtonBox::ActionRole);
buttonBox->addButton(quitButton, QDialogButtonBox::RejectRole);
#ifndef Q_WS_MAEMO_5
progressDialog = new QProgressDialog(this);
#endif
connect(urlLineEdit, SIGNAL(textChanged(QString)),
this, SLOT(enableDownloadButton()));
connect(&qnam, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)),
this, SLOT(slotAuthenticationRequired(QNetworkReply*,QAuthenticator*)));
#ifndef QT_NO_OPENSSL
connect(&qnam, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)),
this, SLOT(sslErrors(QNetworkReply*,QList<QSslError>)));
#endif
#ifndef Q_WS_MAEMO_5
connect(progressDialog, SIGNAL(canceled()), this, SLOT(cancelDownload()));
#endif
connect(downloadButton, SIGNAL(clicked()), this, SLOT(downloadFile()));
connect(quitButton, SIGNAL(clicked()), this, SLOT(close()));
QHBoxLayout *topLayout = new QHBoxLayout;
topLayout->addWidget(urlLabel);
topLayout->addWidget(urlLineEdit);
QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addLayout(topLayout);
mainLayout->addWidget(statusLabel);
mainLayout->addWidget(buttonBox);
setLayout(mainLayout);
setWindowTitle(tr("HTTP"));
urlLineEdit->setFocus();
}
void HttpWindow::startRequest(QUrl url)
{
reply = qnam.get(QNetworkRequest(url));
connect(reply, SIGNAL(finished()),
this, SLOT(httpFinished()));
connect(reply, SIGNAL(readyRead()),
this, SLOT(httpReadyRead()));
connect(reply, SIGNAL(downloadProgress(qint64,qint64)),
this, SLOT(updateDataReadProgress(qint64,qint64)));
}
void HttpWindow::downloadFile()
{
url = urlLineEdit->text();
QFileInfo fileInfo(url.path());
QString fileName = fileInfo.fileName();
if (fileName.isEmpty())
fileName = "index.html";
if (QFile::exists(fileName)) {
if (QMessageBox::question(this, tr("HTTP"),
tr("There already exists a file called %1 in "
"the current directory. Overwrite?").arg(fileName),
QMessageBox::Yes|QMessageBox::No, QMessageBox::No)
== QMessageBox::No)
return;
QFile::remove(fileName);
}
file = new QFile(fileName);
if (!file->open(QIODevice::WriteOnly)) {
QMessageBox::information(this, tr("HTTP"),
tr("Unable to save the file %1: %2.")
.arg(fileName).arg(file->errorString()));
delete file;
file = 0;
return;
}
#ifndef Q_WS_MAEMO_5
progressDialog->setWindowTitle(tr("HTTP"));
progressDialog->setLabelText(tr("Downloading %1.").arg(fileName));
#endif
downloadButton->setEnabled(false);
// schedule the request
httpRequestAborted = false;
startRequest(url);
}
void HttpWindow::cancelDownload()
{
statusLabel->setText(tr("Download canceled."));
httpRequestAborted = true;
reply->abort();
downloadButton->setEnabled(true);
}
void HttpWindow::httpFinished()
{
if (httpRequestAborted) {
if (file) {
file->close();
file->remove();
delete file;
file = 0;
}
reply->deleteLater();
#ifndef Q_WS_MAEMO_5
progressDialog->hide();
#endif
return;
}
#ifndef Q_WS_MAEMO_5
progressDialog->hide();
#endif
file->flush();
file->close();
QVariant redirectionTarget = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
if (reply->error()) {
file->remove();
QMessageBox::information(this, tr("HTTP"),
tr("Download failed: %1.")
.arg(reply->errorString()));
downloadButton->setEnabled(true);
} else if (!redirectionTarget.isNull()) {
QUrl newUrl = url.resolved(redirectionTarget.toUrl());
if (QMessageBox::question(this, tr("HTTP"),
tr("Redirect to %1 ?").arg(newUrl.toString()),
QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) {
url = newUrl;
reply->deleteLater();
file->open(QIODevice::WriteOnly);
file->resize(0);
startRequest(url);
return;
}
} else {
QString fileName = QFileInfo(QUrl(urlLineEdit->text()).path()).fileName();
statusLabel->setText(tr("Downloaded %1 to %2.").arg(fileName).arg(QDir::currentPath()));
downloadButton->setEnabled(true);
}
reply->deleteLater();
reply = 0;
delete file;
file = 0;
}
void HttpWindow::httpReadyRead()
{
// this slot gets called every time the QNetworkReply has new data.
// We read all of its new data and write it into the file.
// That way we use less RAM than when reading it at the finished()
// signal of the QNetworkReply
if (file)
file->write(reply->readAll());
}
void HttpWindow::updateDataReadProgress(qint64 bytesRead, qint64 totalBytes)
{
if (httpRequestAborted)
return;
#ifndef Q_WS_MAEMO_5
progressDialog->setMaximum(totalBytes);
progressDialog->setValue(bytesRead);
#else
Q_UNUSED(bytesRead);
Q_UNUSED(totalBytes);
#endif
}
void HttpWindow::enableDownloadButton()
{
downloadButton->setEnabled(!urlLineEdit->text().isEmpty());
}
void HttpWindow::slotAuthenticationRequired(QNetworkReply*,QAuthenticator *authenticator)
{
QDialog dlg;
Ui::Dialog ui;
ui.setupUi(&dlg);
dlg.adjustSize();
ui.siteDescription->setText(tr("%1 at %2").arg(authenticator->realm()).arg(url.host()));
// Did the URL have information? Fill the UI
// This is only relevant if the URL-supplied credentials were wrong
ui.userEdit->setText(url.userName());
ui.passwordEdit->setText(url.password());
if (dlg.exec() == QDialog::Accepted) {
authenticator->setUser(ui.userEdit->text());
authenticator->setPassword(ui.passwordEdit->text());
}
}
#ifndef QT_NO_OPENSSL
void HttpWindow::sslErrors(QNetworkReply*,const QList<QSslError> &errors)
{
QString errorString;
foreach (const QSslError &error, errors) {
if (!errorString.isEmpty())
errorString += ", ";
errorString += error.errorString();
}
if (QMessageBox::warning(this, tr("HTTP"),
tr("One or more SSL errors has occurred: %1").arg(errorString),
QMessageBox::Ignore | QMessageBox::Abort) == QMessageBox::Ignore) {
reply->ignoreSslErrors();
}
}
#endif
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void HttpWindow::setUrl(const QString& httpAddress)
{
urlLineEdit->setText(httpAddress);
}

View File

@ -1,112 +0,0 @@
/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
** the names of its contributors may be used to endorse or promote
** products derived from this software without specific prior written
** permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef HTTPWINDOW_H
#define HTTPWINDOW_H
#ifdef Q_WS_MAEMO_5
#include <QWidget>
#else
#include <QDialog>
#endif
#include <QNetworkAccessManager>
#include <QUrl>
QT_BEGIN_NAMESPACE
class QDialogButtonBox;
class QFile;
class QLabel;
class QLineEdit;
class QProgressDialog;
class QPushButton;
class QSslError;
class QAuthenticator;
class QNetworkReply;
QT_END_NAMESPACE
#ifdef Q_WS_MAEMO_5
class HttpWindow : public QWidget
#else
class HttpWindow : public QDialog
#endif
{
Q_OBJECT
public:
HttpWindow(QWidget *parent = 0);
void setUrl(const QString& httpAddress);
void startRequest(QUrl url);
private slots:
void downloadFile();
void cancelDownload();
void httpFinished();
void httpReadyRead();
void updateDataReadProgress(qint64 bytesRead, qint64 totalBytes);
void enableDownloadButton();
void slotAuthenticationRequired(QNetworkReply*,QAuthenticator *);
#ifndef QT_NO_OPENSSL
void sslErrors(QNetworkReply*,const QList<QSslError> &errors);
#endif
private:
QLabel *statusLabel;
QLabel *urlLabel;
QLineEdit *urlLineEdit;
#ifndef Q_WS_MAEMO_5
QProgressDialog *progressDialog;
#endif
QPushButton *downloadButton;
QPushButton *quitButton;
QDialogButtonBox *buttonBox;
QUrl url;
QNetworkAccessManager qnam;
QNetworkReply *reply;
QFile *file;
int httpGetId;
bool httpRequestAborted;
};
#endif

View File

@ -1,768 +0,0 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2011-2012 Statoil ASA, Ceetron AS
//
// 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 "ssihubDialog.h"
#include <QtGui>
#include <QtNetwork>
#include "httpwindow.h"
#include "ui_authenticationdialog.h"
#include "RifJsonEncodeDecode.h"
namespace ssihub {
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
FetchWellPathsDialog::FetchWellPathsDialog(QWidget *parent)
: QDialog(parent)
{
m_urlSsiHubLineEdit = new QLineEdit;
m_urlSsiHubLineEdit->setReadOnly(true);
m_urlSsiHubLabel = new QLabel(tr("SSIHUB address:"));
m_urlSsiHubLabel->setBuddy(m_urlSsiHubLineEdit);
m_urlLineEdit = new QLineEdit;
m_urlLineEdit->setReadOnly(true);
m_urlLabel = new QLabel(tr("SSIHUB complete request:"));
m_urlLabel->setBuddy(m_urlLineEdit);
m_statusLabel = new QLabel(tr("Status : idle"));
m_statusLabel->setWordWrap(true);
m_downloadFieldsButton = new QPushButton(tr("Get fields"));
connect(m_downloadFieldsButton, SIGNAL(clicked()), this, SLOT(downloadFields()));
// Fields data model and view
m_fieldListView = new QListView(this);
m_fieldModel = new QStringListModel;
m_fieldListView->setModel(m_fieldModel);
connect(m_fieldListView->selectionModel(), SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection& )), this, SLOT(slotSelectionChanged(const QItemSelection&, const QItemSelection& )));
// Well paths data model and view
m_wellPathsModel = new QStandardItemModel;
m_wellPathsModel->setColumnCount(2);
m_wellPathsView = new QListView(this);
m_wellPathsView->setModel(m_wellPathsModel);
// Filter by Utm coordinates
m_filterWellsByUtmArea = new QCheckBox("Filter by UTM area");
connect(m_filterWellsByUtmArea, SIGNAL(clicked()), this, SLOT(refreshButtonStatus()));
m_northLineEdit = new QLineEdit;
m_southLineEdit = new QLineEdit;
m_eastLineEdit = new QLineEdit;
m_westLineEdit = new QLineEdit;
QGroupBox* utmAreaGropBox = new QGroupBox("UTM filter by area");
QGridLayout *utmAreaLayout = new QGridLayout;
utmAreaLayout->addWidget(m_filterWellsByUtmArea, 0, 1);
utmAreaLayout->addWidget(new QLabel("North"), 1, 0);
utmAreaLayout->addWidget(m_northLineEdit, 1, 1);
utmAreaLayout->addWidget(new QLabel("South"), 1, 2);
utmAreaLayout->addWidget(m_southLineEdit, 1, 3);
utmAreaLayout->addWidget(new QLabel("East"), 2, 0);
utmAreaLayout->addWidget(m_eastLineEdit, 2, 1);
utmAreaLayout->addWidget(new QLabel("West"), 2, 2);
utmAreaLayout->addWidget(m_westLineEdit, 2, 3);
utmAreaGropBox->setLayout(utmAreaLayout);
// Well types
m_importSurveyCheckBox = new QCheckBox("Survey");
m_importSurveyCheckBox->setChecked(true);
m_importPlansCheckBox = new QCheckBox("Plans");
m_importPlansCheckBox->setChecked(true);
QGroupBox* wellTypeGropBox = new QGroupBox("Include well types");
QHBoxLayout* wellTypeLayout = new QHBoxLayout;
wellTypeLayout->addWidget(m_importSurveyCheckBox);
wellTypeLayout->addWidget(m_importPlansCheckBox);
wellTypeGropBox->setLayout(wellTypeLayout);
m_downloadWellPathsButton = new QPushButton(tr("Get well paths"));
m_downloadWellPathsButton->setDefault(true);
m_buttonBox = new QDialogButtonBox;
m_buttonBox->addButton(m_downloadFieldsButton, QDialogButtonBox::ActionRole);
m_buttonBox->addButton(m_downloadWellPathsButton, QDialogButtonBox::ActionRole);
QDialogButtonBox* buttonBox1 = new QDialogButtonBox;
buttonBox1->addButton(QDialogButtonBox::Cancel);
buttonBox1->addButton("Import well paths", QDialogButtonBox::AcceptRole);
connect(buttonBox1, SIGNAL(accepted()), this, SLOT(accept()));
connect(buttonBox1, SIGNAL(rejected()), this, SLOT(reject()));
m_progressDialog = new QProgressDialog(this);
connect(m_urlLineEdit, SIGNAL(textChanged(QString)),
this, SLOT(refreshButtonStatus()));
connect(&m_networkAccessManager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)),
this, SLOT(slotAuthenticationRequired(QNetworkReply*,QAuthenticator*)));
#ifndef QT_NO_OPENSSL
connect(&m_networkAccessManager, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)),
this, SLOT(sslErrors(QNetworkReply*,QList<QSslError>)));
#endif
connect(m_progressDialog, SIGNAL(canceled()), this, SLOT(cancelDownload()));
connect(m_downloadWellPathsButton, SIGNAL(clicked()), this, SLOT(downloadWellPaths()));
QVBoxLayout *topLayout1 = new QVBoxLayout;
QVBoxLayout *topLayout2 = new QVBoxLayout;
topLayout1->addWidget(m_urlSsiHubLabel);
topLayout1->addWidget(m_urlSsiHubLineEdit);
topLayout2->addWidget(m_urlLabel);
topLayout2->addWidget(m_urlLineEdit);
QHBoxLayout *topLayout = new QHBoxLayout;
topLayout->addLayout(topLayout1);
topLayout->addLayout(topLayout2);
QHBoxLayout *ssihubLayout = new QHBoxLayout;
ssihubLayout->addWidget(m_fieldListView);
QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addLayout(topLayout);
mainLayout->addLayout(ssihubLayout);
mainLayout->addWidget(m_statusLabel);
mainLayout->addWidget(utmAreaGropBox);
mainLayout->addWidget(wellTypeGropBox);
mainLayout->addWidget(m_buttonBox);
mainLayout->addWidget(m_wellPathsView);
mainLayout->addWidget(buttonBox1);
setLayout(mainLayout);
setWindowTitle(tr("Import Well Paths"));
m_urlLineEdit->setFocus();
refreshButtonStatus();
resize(600, 400);
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void FetchWellPathsDialog::startRequest(QUrl url)
{
m_reply = m_networkAccessManager.get(QNetworkRequest(url));
connect(m_reply, SIGNAL(finished()),
this, SLOT(httpFinished()));
connect(m_reply, SIGNAL(readyRead()),
this, SLOT(httpReadyRead()));
connect(m_reply, SIGNAL(downloadProgress(qint64,qint64)),
this, SLOT(updateDataReadProgress(qint64,qint64)));
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void FetchWellPathsDialog::cancelDownload()
{
m_statusLabel->setText(tr("Download canceled."));
m_httpRequestAborted = true;
m_reply->abort();
refreshButtonStatus();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void FetchWellPathsDialog::httpFinished()
{
if (m_httpRequestAborted) {
if (m_file) {
m_file->close();
m_file->remove();
delete m_file;
m_file = 0;
}
m_reply->deleteLater();
m_progressDialog->hide();
return;
}
if (m_wellPathRequestQueue.size() == 0)
{
m_progressDialog->hide();
}
m_file->flush();
m_file->close();
QVariant redirectionTarget = m_reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
if (m_reply->error()) {
m_file->remove();
QMessageBox::information(this, tr("HTTP"),
tr("Download failed: %1.")
.arg(m_reply->errorString()));
} else if (!redirectionTarget.isNull()) {
QUrl newUrl = m_url.resolved(redirectionTarget.toUrl());
if (QMessageBox::question(this, tr("HTTP"),
tr("Redirect to %1 ?").arg(newUrl.toString()),
QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) {
m_url = newUrl;
m_reply->deleteLater();
m_file->open(QIODevice::WriteOnly);
m_file->resize(0);
startRequest(m_url);
return;
}
} else {
m_statusLabel->setText(tr("Downloaded data to %1.").arg(m_destinationFolder));
}
if (m_currentDownloadState == DOWNLOAD_WELL_PATH)
{
QString singleWellPathFilePath = m_file->fileName();
QFile file(singleWellPathFilePath);
if (file.open(QFile::ReadOnly))
{
QString singleWellPathContent = file.readAll();
// Strip leading and trailing []
if (singleWellPathContent.indexOf('{') > 0)
{
singleWellPathContent = singleWellPathContent.right(singleWellPathContent.size() - singleWellPathContent.indexOf('{'));
}
if (singleWellPathContent[singleWellPathContent.size() - 1] == ']')
{
singleWellPathContent = singleWellPathContent.left(singleWellPathContent.size() - 1);
}
QString wellPathName = getValue("name", singleWellPathContent);
if (!singleWellPathContent.isEmpty() && !wellPathName.isEmpty())
{
int currentRowCount = m_wellPathsModel->rowCount();
m_wellPathsModel->setRowCount(m_wellPathsModel->rowCount() + 1);
QModelIndex miName = m_wellPathsModel->index(currentRowCount, 0);
m_wellPathsModel->setData(miName, wellPathName);
QModelIndex miFileName = m_wellPathsModel->index(currentRowCount, 1);
m_wellPathsModel->setData(miFileName, singleWellPathFilePath);
// Write out the content without leading/trailing []
file.close();
file.remove(singleWellPathFilePath);
if (file.open(QFile::WriteOnly))
{
QTextStream out(&file);
out << singleWellPathContent;
}
}
}
}
refreshButtonStatus();
m_reply->deleteLater();
m_reply = 0;
delete m_file;
m_file = 0;
if (m_currentDownloadState == DOWNLOAD_WELLS)
{
QStringList survey;
QStringList plans;
getWellPathLinks(&survey, &plans);
m_currentDownloadState = DOWNLOAD_UNDEFINED;
issueDownloadOfWellPaths(survey, plans);
}
else if (m_currentDownloadState == DOWNLOAD_FIELDS)
{
updateFieldsModel();
m_currentDownloadState = DOWNLOAD_UNDEFINED;
}
else
{
checkDownloadQueueAndIssueRequests();
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void FetchWellPathsDialog::httpReadyRead()
{
// this slot gets called every time the QNetworkReply has new data.
// We read all of its new data and write it into the file.
// That way we use less RAM than when reading it at the finished()
// signal of the QNetworkReply
if (m_file)
m_file->write(m_reply->readAll());
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void FetchWellPathsDialog::updateDataReadProgress(qint64 bytesRead, qint64 totalBytes)
{
if (m_httpRequestAborted)
return;
m_progressDialog->setMaximum(totalBytes);
m_progressDialog->setValue(bytesRead);
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void FetchWellPathsDialog::refreshButtonStatus()
{
if (m_fieldListView->selectionModel()->selectedIndexes().size() > 0)
{
m_downloadWellPathsButton->setEnabled(true);
}
else
{
m_downloadWellPathsButton->setEnabled(false);
}
m_downloadFieldsButton->setEnabled(!m_urlSsiHubLineEdit->text().isEmpty());
bool enableUtmEditors = m_filterWellsByUtmArea->isChecked();
m_northLineEdit->setEnabled(enableUtmEditors);
m_southLineEdit->setEnabled(enableUtmEditors);
m_eastLineEdit->setEnabled(enableUtmEditors);
m_westLineEdit->setEnabled(enableUtmEditors);
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void FetchWellPathsDialog::slotAuthenticationRequired(QNetworkReply*,QAuthenticator *authenticator)
{
QDialog dlg;
Ui::Dialog ui;
ui.setupUi(&dlg);
dlg.adjustSize();
ui.siteDescription->setText(tr("%1 at %2").arg(authenticator->realm()).arg(m_url.host()));
// Did the URL have information? Fill the UI
// This is only relevant if the URL-supplied credentials were wrong
ui.userEdit->setText(m_url.userName());
ui.passwordEdit->setText(m_url.password());
ui.passwordEdit->setEchoMode(QLineEdit::Password);
if (dlg.exec() == QDialog::Accepted) {
authenticator->setUser(ui.userEdit->text());
authenticator->setPassword(ui.passwordEdit->text());
}
}
#ifndef QT_NO_OPENSSL
void FetchWellPathsDialog::sslErrors(QNetworkReply*,const QList<QSslError> &errors)
{
QString errorString;
foreach (const QSslError &error, errors) {
if (!errorString.isEmpty())
errorString += ", ";
errorString += error.errorString();
}
if (QMessageBox::warning(this, tr("HTTP"),
tr("One or more SSL errors has occurred: %1").arg(errorString),
QMessageBox::Ignore | QMessageBox::Abort) == QMessageBox::Ignore) {
m_reply->ignoreSslErrors();
}
}
#endif
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void FetchWellPathsDialog::setUrl(const QString& httpAddress)
{
m_urlLineEdit->setText(httpAddress);
m_url = httpAddress;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void FetchWellPathsDialog::downloadWellPaths()
{
QString fileName = jsonWellsFilePath();
if (QFile::exists(fileName))
{
QFile::remove(fileName);
m_wellPathsModel->clear();
m_wellPathsModel->setColumnCount(2);
}
m_currentDownloadState = DOWNLOAD_WELLS;
QModelIndex mi = m_fieldListView->currentIndex();
QString fieldName = m_fieldModel->data(mi, Qt::DisplayRole).toString();
QString completeUrlText = m_urlSsiHubLineEdit->text() + "/resinsight/projects/" + fieldName;
if (m_filterWellsByUtmArea->isChecked())
{
completeUrlText += "/wellsInArea";
int north = m_northLineEdit->text().toInt();
int south = m_southLineEdit->text().toInt();
int east = m_eastLineEdit->text().toInt();
int west = m_westLineEdit->text().toInt();
completeUrlText += QString("?north=%1").arg(north);
completeUrlText += QString("&south=%1").arg(south);
completeUrlText += QString("&east=%1").arg(east);
completeUrlText += QString("&west=%1").arg(west);
completeUrlText += QString("&utmZone=32S&format=json");
}
else
{
completeUrlText += "/wells";
}
issueHttpRequestToFile(completeUrlText, fileName);
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void FetchWellPathsDialog::downloadFields()
{
QString wellFileName = jsonWellsFilePath();
if (QFile::exists(wellFileName))
{
QFile::remove(wellFileName);
m_wellPathsModel->clear();
m_wellPathsModel->setColumnCount(2);
}
QString completeUrlText = m_urlSsiHubLineEdit->text() + "/resinsight/projects";
QString destinationFileName = jsonFieldsFilePath();
m_currentDownloadState = DOWNLOAD_FIELDS;
issueHttpRequestToFile(completeUrlText, destinationFileName);
return;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void FetchWellPathsDialog::setDestinationFolder(const QString& folder)
{
m_destinationFolder = folder;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void FetchWellPathsDialog::setSsiHubUrl(const QString& httpAddress)
{
QString validAddress(httpAddress);
if (validAddress.endsWith('/'))
{
validAddress = validAddress.left(validAddress.size() - 1);
}
m_urlSsiHubLineEdit->setText(validAddress);
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void FetchWellPathsDialog::slotSelectionChanged(const QItemSelection & selected, const QItemSelection & deselected)
{
QModelIndexList idxList = selected.indexes();
if (idxList.size() == 1)
{
QString fieldName = m_fieldModel->data(idxList[0], Qt::DisplayRole).toString();
QString completeUrlText = m_urlSsiHubLineEdit->text() + "/resinsight/projects/" + fieldName;
setUrl(completeUrlText);
}
else
{
setUrl("");
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void FetchWellPathsDialog::updateFieldsModel()
{
QString fileName = jsonFieldsFilePath();
if (QFile::exists(fileName))
{
JsonReader jsonReader;
QMap<QString, QVariant> jsonMap = jsonReader.decodeFile(fileName);
QStringList fieldNames;
QMapIterator<QString, QVariant> it(jsonMap);
while (it.hasNext())
{
it.next();
QString key = it.key();
if (key[0].isDigit())
{
QMap<QString, QVariant> fieldMap = it.value().toMap();
fieldNames.push_back(fieldMap["name"].toString());
}
}
m_fieldModel->setStringList(fieldNames);
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString FetchWellPathsDialog::jsonFieldsFilePath()
{
return m_destinationFolder + "/fields.json";
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString FetchWellPathsDialog::jsonWellsFilePath()
{
return m_destinationFolder + "/wellpaths.json";
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString FetchWellPathsDialog::jsonWellsInArea()
{
return m_destinationFolder + "/wellsInArea.json";
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QStringList FetchWellPathsDialog::downloadedJsonWellPathFiles()
{
QStringList fileNames;
for (int i = 0; i < m_wellPathsModel->rowCount(); i++)
{
QModelIndex mi = m_wellPathsModel->index(i, 1);
fileNames.push_back(m_wellPathsModel->data(mi).toString());
}
return fileNames;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void FetchWellPathsDialog::showEvent(QShowEvent* event)
{
refreshButtonStatus();
QDialog::showEvent(event);
}
//--------------------------------------------------------------------------------------------------
/// Search for string, and find the associated value inside the next quoted string
// text content : "A" : "B"
// A search for key "A" returns B
//--------------------------------------------------------------------------------------------------
QString FetchWellPathsDialog::getValue(const QString& key, const QString& stringContent)
{
QString quotedKey = "\"" + key + "\"";
int pos = stringContent.indexOf(quotedKey);
if (pos >=0)
{
int valueStartPos = stringContent.indexOf("\"", pos + quotedKey.size());
int valueEndPos = stringContent.indexOf("\"", valueStartPos + 1);
if (valueStartPos >= 0 && valueEndPos > valueStartPos)
{
return stringContent.mid(valueStartPos + 1, valueEndPos - valueStartPos - 1);
}
}
return QString();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void FetchWellPathsDialog::setRegion(int north, int south, int east, int west)
{
m_northLineEdit->setText(QString::number(north));
m_southLineEdit->setText(QString::number(south));
m_eastLineEdit->setText(QString::number(east));
m_westLineEdit->setText(QString::number(west));
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void FetchWellPathsDialog::issueHttpRequestToFile(QString completeUrlText, QString destinationFileName)
{
setUrl(completeUrlText);
m_file = new QFile(destinationFileName);
if (!m_file->open(QIODevice::WriteOnly)) {
QMessageBox::information(this, tr("HTTP"),
tr("Unable to save the file %1: %2.")
.arg(destinationFileName).arg(m_file->errorString()));
delete m_file;
m_file = 0;
return;
}
m_progressDialog->setWindowTitle(tr("HTTP"));
m_progressDialog->setLabelText(tr("Downloading %1.").arg(destinationFileName));
// schedule the request
m_httpRequestAborted = false;
startRequest(m_url);
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void FetchWellPathsDialog::getWellPathLinks(QStringList* surveyLinks, QStringList* planLinks)
{
QStringList entities;
QString filename = jsonWellsFilePath();
if (QFile::exists(filename))
{
JsonReader jsonReader;
QMap<QString, QVariant> jsonMap = jsonReader.decodeFile(filename);
QMapIterator<QString, QVariant> it(jsonMap);
while (it.hasNext())
{
it.next();
QString key = it.key();
if (key[0].isDigit())
{
QMap<QString, QVariant> slotMap = it.value().toMap();
QMap<QString, QVariant> linkMap = slotMap["links"].toMap();
QString surveyLink = linkMap["survey"].toString();
surveyLinks->push_back(surveyLink);
QString planLink = linkMap["plans"].toString();
planLinks->push_back(planLink);
}
}
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void FetchWellPathsDialog::issueDownloadOfWellPaths(const QStringList& surveyLinks, const QStringList& planLinks)
{
m_wellPathRequestQueue.clear();
if (m_importSurveyCheckBox->isChecked())
{
m_wellPathRequestQueue += surveyLinks;
}
if (m_importPlansCheckBox->isChecked())
{
m_wellPathRequestQueue += planLinks;
}
checkDownloadQueueAndIssueRequests();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void FetchWellPathsDialog::checkDownloadQueueAndIssueRequests()
{
if (m_wellPathRequestQueue.size() > 0)
{
QString link = m_wellPathRequestQueue[0];
m_wellPathRequestQueue.pop_front();
QString completeUrlText = m_urlSsiHubLineEdit->text() + link;
QUuid guid = QUuid::createUuid();
QString singleWellPathFilePath = m_destinationFolder + QString("/wellpath_%1.json").arg(guid);
m_currentDownloadState = DOWNLOAD_WELL_PATH;
issueHttpRequestToFile(completeUrlText, singleWellPathFilePath);
}
}
} // namespace ssihub

View File

@ -1,147 +0,0 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2011-2012 Statoil ASA, Ceetron AS
//
// 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 <QDialog>
#include <QNetworkAccessManager>
#include <QUrl>
#include <QItemSelection>
QT_BEGIN_NAMESPACE
class QDialogButtonBox;
class QFile;
class QLabel;
class QLineEdit;
class QProgressDialog;
class QPushButton;
class QSslError;
class QAuthenticator;
class QNetworkReply;
class QStringListModel;
class QListView;
class QStandardItemModel;
class QCheckBox;
QT_END_NAMESPACE
namespace ssihub {
class FetchWellPathsDialog : public QDialog
{
Q_OBJECT
public:
enum DownloadState{ DOWNLOAD_FIELDS, DOWNLOAD_WELLS, DOWNLOAD_WELL_PATH, DOWNLOAD_UNDEFINED};
public:
FetchWellPathsDialog(QWidget *parent = 0);
void setSsiHubUrl(const QString& httpAddress);
void setDestinationFolder(const QString& folder);
void setRegion(int north, int south, int east, int west);
QStringList downloadedJsonWellPathFiles();
protected:
virtual void showEvent(QShowEvent* event);
private:
void startRequest(QUrl url);
void setUrl(const QString& httpAddress);
QString jsonFieldsFilePath();
QString jsonWellsFilePath();
QString jsonWellsInArea();
void updateFieldsModel();
QString getValue(const QString& key, const QString& stringContent);
void getWellPathLinks(QStringList* surveyLinks, QStringList* planLinks);
void issueDownloadOfWellPaths(const QStringList& surveyLinks, const QStringList& planLinks);
private slots:
void downloadWellPaths();
void downloadFields();
void checkDownloadQueueAndIssueRequests();
void issueHttpRequestToFile( QString completeUrlText, QString fieldsFileName );
void cancelDownload();
void httpFinished();
void httpReadyRead();
void updateDataReadProgress(qint64 bytesRead, qint64 totalBytes);
void refreshButtonStatus();
void slotAuthenticationRequired(QNetworkReply*,QAuthenticator *);
void slotSelectionChanged( const QItemSelection & selected, const QItemSelection & deselected );
#ifndef QT_NO_OPENSSL
void sslErrors(QNetworkReply*,const QList<QSslError> &errors);
#endif
private:
QLabel* m_statusLabel;
QLabel* m_urlLabel;
QLineEdit* m_urlLineEdit;
QLabel* m_urlSsiHubLabel;
QLineEdit* m_urlSsiHubLineEdit;
QPushButton* m_downloadFieldsButton;
QListView* m_fieldListView;
QListView* m_wellPathsView;
QStandardItemModel* m_wellPathsModel;
QCheckBox* m_filterWellsByUtmArea;
QLineEdit* m_northLineEdit;
QLineEdit* m_southLineEdit;
QLineEdit* m_eastLineEdit;
QLineEdit* m_westLineEdit;
QCheckBox* m_importSurveyCheckBox;
QCheckBox* m_importPlansCheckBox;
QProgressDialog* m_progressDialog;
QPushButton* m_downloadWellPathsButton;
QDialogButtonBox* m_buttonBox;
QUrl m_url;
QNetworkAccessManager m_networkAccessManager;
QNetworkReply* m_reply;
QFile* m_file;
bool m_httpRequestAborted;
QString m_destinationFolder;
QStringListModel* m_fieldModel;
QStringList m_wellPathRequestQueue;
DownloadState m_currentDownloadState;
};
} // namespace ssihub

View File

@ -1,128 +0,0 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2011-2012 Statoil ASA, Ceetron AS
//
// 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 "ssihubWebServiceInterface.h"
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QStringList>
#include "ssihubDialog.h"
//#include <QObject>
namespace ssihub {
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
WebServiceInterface::WebServiceInterface(QObject *parent /*= 0*/)
: QObject(parent)
{
m_networkManager = new QNetworkAccessManager(this);
//connect(m_openProjectAction, SIGNAL(triggered()), SLOT(slotOpenProject()));
connect(m_networkManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(onResult(QNetworkReply*)));
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
WebServiceInterface::~WebServiceInterface()
{
//if (m_networkManager) delete m_networkManager;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void WebServiceInterface::setUrl(const QString& url)
{
m_httpAddress = url;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QStringList WebServiceInterface::fetchData(const QString& method, const QMap<QString, QVariant>& arguments)
{
FetchWellPathsDialog httpWin;
httpWin.setSsiHubUrl(m_httpAddress);
httpWin.exec();
/*
QNetworkReply* reply = m_networkManager->get(QNetworkRequest(QUrl("http://qt.nokia.com")));
while (!reply->isFinished())
{
}
QString data = (QString) reply->readAll();
/*
QUrl url(m_httpAddress);
// url.setPath(QString("%1%2").arg(url.path()).arg(method));
//
// foreach(QString param, arguments.keys()) {
// url.addQueryItem(param, arguments[param].toString());
// }
QNetworkRequest request;
request.setUrl(url);
QNetworkReply* reply = m_networkManager->get(request);
QString data = (QString) reply->readAll();
QStringList fileContent;
fileContent.push_back(data);
return fileContent;
*/
QStringList strings;
return strings;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void WebServiceInterface::onResult(QNetworkReply* reply)
{
if (reply->error() != QNetworkReply::NoError)
return; // ...only in a blog post
QString data = (QString) reply->readAll();
}
}; // namespace ssihub

View File

@ -16,16 +16,22 @@ else()
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /MP")
endif()
option (RESINSIGHT_USE_OPENMP "Enable OpenMP parallellization in the code" ON)
IF(${CMAKE_SYSTEM_NAME} MATCHES "Linux")
# Linux specific code
set(CMAKE_CXX_FLAGS "-DCVF_LINUX -pipe -Wextra -Woverloaded-virtual -Wformat")
set(CMAKE_CXX_FLAGS_DEBUG "-ggdb -g3 -O0 -DDEBUG -D_DEBUG")
set(CMAKE_CXX_FLAGS_RELEASE "-O2 -DNO_DEBUG")
#set(CMAKE_EXE_LINKER_FLAGS "-Xlinker -rpath .")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fopenmp")
if(RESINSIGHT_USE_OPENMP)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fopenmp")
endif()
# set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -g1")
ELSE()
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /openmp")
if(RESINSIGHT_USE_OPENMP)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /openmp")
endif()
ENDIF()
@ -121,11 +127,11 @@ if (NOT "${RESINSIGHT_PLATFORM}" STREQUAL "")
endif()
# override system install prefix if private installation chosen
option (PRIVATE_INSTALL "Install in a private directory" ON)
if (PRIVATE_INSTALL)
option (RESINSIGHT_PRIVATE_INSTALL "Install as an independent bundle including the neccesary Qt libraries" ON)
if (RESINSIGHT_PRIVATE_INSTALL)
set (CMAKE_INSTALL_PREFIX ${CMAKE_BINARY_DIR}/Install/)
#set (CMAKE_INSTALL_PREFIX /usr/${RESINSIGHT_FINAL_NAME})
endif (PRIVATE_INSTALL)
endif (RESINSIGHT_PRIVATE_INSTALL)
################################################################################
# Application

View File

@ -10,15 +10,25 @@ set( QOBJECT_HEADERS
qt4_wrap_cpp( MOC_FILES_CPP ${QOBJECT_HEADERS} )
add_library( ${PROJECT_NAME}
cafEffectCache.cpp
cafEffectGenerator.cpp
cafLog.cpp
cafMessagePanel.cpp
cafMouseState.cpp
cafUtils.cpp
cvfStructGrid.cpp
cvfStructGridGeometryGenerator.cpp
cafEffectCache.cpp
cafEffectCache.h
cafEffectGenerator.cpp
cafEffectGenerator.h
cafLog.cpp
cafLog.h
cafMessagePanel.cpp
cafMessagePanel.h
cafMouseState.cpp
cafMouseState.h
cafUtils.cpp
cafUtils.h
cvfStructGrid.cpp
cvfStructGrid.h
cvfStructGridGeometryGenerator.cpp
cvfStructGridGeometryGenerator.h
cvfStructGridScalarDataAccess.h
${MOC_FILES_CPP}
)

View File

@ -483,7 +483,7 @@ ScalarMapperEffectGenerator::addAlphaAndUndefStripes(const cvf::TextureImage* te
CVF_ASSERT(texImg->height() == 1);
cvf::ref<cvf::TextureImage> modTexImg = new cvf::TextureImage;
modTexImg->allocate(texImg->width(), texImg->height() + 2);
modTexImg->allocate(texImg->width(), texImg->height() + 3); // Make the texture a power of two to avoid behind the scenes scaling and the following artefacts
modTexImg->fill(cvf::Color4ub(cvf::Color3ub(undefScalarColor), 255)); // Undefined color
for (cvf::uint i = 0 ; i < texImg->width(); ++i)
@ -492,6 +492,7 @@ ScalarMapperEffectGenerator::addAlphaAndUndefStripes(const cvf::TextureImage* te
modTexImg->setPixel(i, 0, legendColor);
legendColor.a() = static_cast<cvf::ubyte>(opacityLevel * 255);
modTexImg->setPixel(i, 1, legendColor);
modTexImg->setPixel(i, 2, legendColor);
}
return modTexImg;

View File

@ -19,6 +19,10 @@ set(CPP_SOURCES
riGetActiveCellCorners.cpp
riGetGridProperty.cpp
riSetGridProperty.cpp
riGetPropertyNames.cpp
riGetWellNames.cpp
riGetWellStatus.cpp
riGetWellCells.cpp
)
if (${CMAKE_SYSTEM_NAME} MATCHES "Linux")
@ -36,9 +40,9 @@ set(OCTAVE_BINARY_OCT_FILES)
# To be able to do so, we need to establish all Qt-related variables for a 32-bit configuration
# In addition, VS2010 32-bit compile environment must be launched
if (${CMAKE_SYSTEM_NAME} MATCHES "Windows" AND CMAKE_CL_64)
find_program(32BIT_QMAKE 32bitqmake)
if(32BIT_QMAKE)
get_filename_component(32BIT_QMAKE_PATH ${32BIT_QMAKE} PATH) # Get path to 32-bit Qt binary directory
find_program(RESINSIGHT_OCTAVE_PLUGIN_32BIT_QMAKE_EXE 32bitqmake)
if(RESINSIGHT_OCTAVE_PLUGIN_32BIT_QMAKE_EXE)
get_filename_component(32BIT_QMAKE_PATH ${RESINSIGHT_OCTAVE_PLUGIN_32BIT_QMAKE_EXE} PATH) # Get path to 32-bit Qt binary directory
STRING(REPLACE "/bin" "" OCTAVE_QT_ROOT ${32BIT_QMAKE_PATH})
SET(OCTAVE_QT_INCLUDE_DIR ${OCTAVE_QT_ROOT}/include)
@ -54,13 +58,13 @@ else()
endif()
find_program(MKOCTFILE_EXECUTABLE mkoctfile)
if(NOT MKOCTFILE_EXECUTABLE)
find_program(RESINSIGHT_OCTAVE_PLUGIN_MKOCTFILE_EXE mkoctfile)
if(NOT RESINSIGHT_OCTAVE_PLUGIN_MKOCTFILE_EXE)
message(WARNING "Failed to find mkoctfile")
else()
# Get path to Octave binary directory to be able to build .oct files if Octave is not in path
get_filename_component(OCTAVE_PATH ${MKOCTFILE_EXECUTABLE} PATH)
get_filename_component(OCTAVE_PATH ${RESINSIGHT_OCTAVE_PLUGIN_MKOCTFILE_EXE} PATH)
foreach(srcFileName IN LISTS CPP_SOURCES)
@ -79,16 +83,16 @@ else()
add_custom_command(
OUTPUT "${octFileName}"
COMMAND call "\"%VS100COMNTOOLS%../../VC/vcvarsall.bat\"" x86
COMMAND ${CMAKE_COMMAND} ARGS -E chdir ${OCTAVE_PATH} ${MKOCTFILE_EXECUTABLE} -I${OCTAVE_QT_QTNETWORK_INCLUDE_DIR}
COMMAND ${CMAKE_COMMAND} ARGS -E chdir ${OCTAVE_PATH} ${RESINSIGHT_OCTAVE_PLUGIN_MKOCTFILE_EXE} -I${OCTAVE_QT_QTNETWORK_INCLUDE_DIR}
-I${OCTAVE_QT_QTCORE_INCLUDE_DIR} -I${OCTAVE_QT_INCLUDE_DIR} ${RPATH_COMMAND}
-L${OCTAVE_QT_LIBRARY_DIR} -lQtCore${QT_LIBRARY_POSTFIX} -lQtNetwork${QT_LIBRARY_POSTFIX} -o "${octFileName}" "${srcFileName}"
DEPENDS "${srcFileName}"
COMMENT "Generating ${octFileName}"
COMMENT "===> Generating ${octFileName}"
)
else()
add_custom_command(
OUTPUT "${octFileName}"
COMMAND ${CMAKE_COMMAND} ARGS -E chdir ${OCTAVE_PATH} ${MKOCTFILE_EXECUTABLE} -I${OCTAVE_QT_QTNETWORK_INCLUDE_DIR}
COMMAND ${CMAKE_COMMAND} ARGS -E chdir ${OCTAVE_PATH} ${RESINSIGHT_OCTAVE_PLUGIN_MKOCTFILE_EXE} -I${OCTAVE_QT_QTNETWORK_INCLUDE_DIR}
-I${OCTAVE_QT_QTCORE_INCLUDE_DIR} -I${OCTAVE_QT_INCLUDE_DIR} ${RPATH_COMMAND}
-L${OCTAVE_QT_LIBRARY_DIR} -lQtCore${QT_LIBRARY_POSTFIX} -lQtNetwork${QT_LIBRARY_POSTFIX} -o "${octFileName}" "${srcFileName}"
DEPENDS "${srcFileName}"
@ -98,7 +102,7 @@ else()
else()
add_custom_command(
OUTPUT "${octFileName}"
COMMAND ${MKOCTFILE_EXECUTABLE} -I${QT_QTNETWORK_INCLUDE_DIR} -I${QT_QTCORE_INCLUDE_DIR} -I${QT_INCLUDE_DIR} ${RPATH_COMMAND} -L${QT_LIBRARY_DIR} -lQtCore${QT_LIBRARY_POSTFIX} -lQtNetwork${QT_LIBRARY_POSTFIX} -o "${octFileName}" "${srcFileName}"
COMMAND ${RESINSIGHT_OCTAVE_PLUGIN_MKOCTFILE_EXE} -I${QT_QTNETWORK_INCLUDE_DIR} -I${QT_QTCORE_INCLUDE_DIR} -I${QT_INCLUDE_DIR} ${RPATH_COMMAND} -L${QT_LIBRARY_DIR} -lQtCore${QT_LIBRARY_POSTFIX} -lQtNetwork${QT_LIBRARY_POSTFIX} -o "${octFileName}" "${srcFileName}"
DEPENDS "${srcFileName}"
COMMENT "Generating ${octFileName}"
)
@ -127,7 +131,10 @@ else()
"${CMAKE_CURRENT_BINARY_DIR}/riGetActiveCellCorners.oct"
"${CMAKE_CURRENT_BINARY_DIR}/riGetGridProperty.oct"
"${CMAKE_CURRENT_BINARY_DIR}/riSetGridProperty.oct"
"${CMAKE_CURRENT_BINARY_DIR}/riGetPropertyNames.oct"
"${CMAKE_CURRENT_BINARY_DIR}/riGetWellNames.oct"
"${CMAKE_CURRENT_BINARY_DIR}/riGetWellStatus.oct"
"${CMAKE_CURRENT_BINARY_DIR}/riGetWellCells.oct"
SOURCES ${CPP_SOURCES}
)
@ -151,9 +158,9 @@ else()
endif()
if (PRIVATE_INSTALL)
if (RESINSIGHT_PRIVATE_INSTALL)
install(FILES ${OCTAVE_BINARY_OCT_FILES} DESTINATION ${RESINSIGHT_FINAL_NAME})
else (PRIVATE_INSTALL)
else (RESINSIGHT_PRIVATE_INSTALL)
# probe for site location of .oct files
if (NOT OCTAVE_SITE_OCT_DIR)
find_program (OCTAVE_CONFIG_COMMAND
@ -170,6 +177,6 @@ else (PRIVATE_INSTALL)
install (FILES ${OCTAVE_BINARY_OCT_FILES}
DESTINATION ${OCTAVE_SITE_OCT_DIR}
)
endif (PRIVATE_INSTALL)
endif (RESINSIGHT_PRIVATE_INSTALL)

View File

@ -0,0 +1,172 @@
#include <QtNetwork>
#include <octave/oct.h>
#include <octave/oct-map.h>
#include "riSettings.h"
void getPropertyNames(std::vector<QString>& propNames, std::vector<QString>& propTypes, const QString &hostName, quint16 port,
const qint64& caseId, QString porosityModel)
{
QString serverName = hostName;
quint16 serverPort = port;
QTcpSocket socket;
socket.connectToHost(serverName, serverPort);
if (!socket.waitForConnected(riOctavePlugin::connectTimeOutMilliSecs))
{
error((("Connection: ") + socket.errorString()).toLatin1().data());
return;
}
// Create command and send it:
QString command;
command += QString("GetPropertyNames") + " " + QString::number(caseId) + " " + porosityModel;
QByteArray cmdBytes = command.toLatin1();
QDataStream socketStream(&socket);
socketStream.setVersion(riOctavePlugin::qtDataStreamVersion);
socketStream << (qint64)(cmdBytes.size());
socket.write(cmdBytes);
// Get response. First wait for the header
while (socket.bytesAvailable() < (int)(sizeof(quint64)))
{
if (!socket.waitForReadyRead(riOctavePlugin::shortTimeOutMilliSecs))
{
error((("Waiting for header: ") + socket.errorString()).toLatin1().data());
return;
}
}
quint64 byteCount;
socketStream >> byteCount;
QString byteCountString = QString::number(byteCount);
//error(byteCountString.toLatin1().data());
while (socket.bytesAvailable() < (int)(byteCount))
{
if (!socket.waitForReadyRead(riOctavePlugin::shortTimeOutMilliSecs))
{
error((("Waiting for data: ") + socket.errorString()).toLatin1().data());
return;
}
OCTAVE_QUIT;
}
quint64 propCount;
socketStream >> propCount;
QString propName;
QString propType;
for (size_t i = 0; i < propCount; i++)
{
socketStream >> propName;
socketStream >> propType;
propNames.push_back(propName);
propTypes.push_back(propType);
}
return;
}
DEFUN_DLD (riGetPropertyNames, args, nargout,
"Usage:\n"
"\n"
" riGetPropertyNames([CaseId]), [PorosityModel = \"Matrix\"|\"Fracture\"] \n"
"\n"
"This function returns the name and type of all the properties in the case as a Vector of Structures.\n"
"The Structure is defined as: \n"
"PropertyInfo {\n"
" PropName = string # Name of the property as received from the analysis tool \n"
" PropType = string # The type of the property: \"StaticNative\", \"DynamicNative\", \"Input\", \"Generated\" \n"
"} \n"
"If the CaseId is not defined, ResInsights Current Case is used.\n"
)
{
int nargin = args.length ();
if (nargin > 2)
{
error("riGetPropertyNames: Too many arguments, this function takes two optional arguments.\n");
print_usage();
}
else if (nargout != 1)
{
error("riGetPropertyNames: Wrong number of output arguments, this function requires one output argument.\n");
print_usage();
}
else
{
qint64 argCaseId = -1;
QString porosityModel = "Matrix";
if (nargin == 1)
{
if (args(0).is_string())
{
porosityModel = args(0).char_matrix_value().row_as_string(0).c_str();
}
else
{
argCaseId = args(0).uint_value();
}
}
else if (nargin == 2)
{
argCaseId = args(0).uint_value();
porosityModel = args(1).char_matrix_value().row_as_string(0).c_str();
}
if (porosityModel != "Matrix" && porosityModel != "Fracture")
{
error("riGetPropertyNames: The value for \"PorosityModel\" is unknown. Please use either \"Matrix\" or \"Fracture\"\n");
print_usage();
return octave_value_list ();
}
std::vector<QString> propertyNames;
std::vector<QString> propertyTypes;
getPropertyNames(propertyNames, propertyTypes, "127.0.0.1", 40001, argCaseId, porosityModel);
size_t caseCount = propertyNames.size();
if (propertyNames.size() != propertyTypes.size() )
{
error("riGetPropertyNames: Inconsistent data received from ResInsight.\n");
}
else
{
// Create cells with N items for each field in the data structure
Cell cellValuesB(caseCount, 1);
Cell cellValuesC(caseCount, 1);
for (size_t i = 0; i < caseCount; i++)
{
cellValuesB(i) = propertyNames[i].toLatin1().data();
cellValuesC(i) = propertyTypes[i].toLatin1().data();
}
// Build a map between the field name and field cell values
Octave_map m;
m.assign(riOctavePlugin::propertyInfo_PropName, cellValuesB);
m.assign(riOctavePlugin::propertyInfo_PropType, cellValuesC);
return octave_value(m);
}
}
return octave_value();
}

View File

@ -0,0 +1,264 @@
#include <QtNetwork>
#include <octave/oct.h>
#include <octave/oct-map.h>
#include "riSettings.h"
void getWellCells( std::vector<int>& cellIs,
std::vector<int>& cellJs,
std::vector<int>& cellKs,
std::vector<int>& gridIndices,
std::vector<int>& cellStatuses,
std::vector<int>& branchIds,
std::vector<int>& segmentIds,
const QString &hostName, quint16 port,
const qint64& caseId, const QString& wellName, int requestedTimeStep)
{
QString serverName = hostName;
quint16 serverPort = port;
QTcpSocket socket;
socket.connectToHost(serverName, serverPort);
if (!socket.waitForConnected(riOctavePlugin::connectTimeOutMilliSecs))
{
error((("Connection: ") + socket.errorString()).toLatin1().data());
return;
}
// Create command and send it:
QString command;
command += QString("GetWellCells") + " " + QString::number(caseId) + " " + wellName + " " + QString::number(requestedTimeStep) ;
QByteArray cmdBytes = command.toLatin1();
QDataStream socketStream(&socket);
socketStream.setVersion(riOctavePlugin::qtDataStreamVersion);
socketStream << (qint64)(cmdBytes.size());
socket.write(cmdBytes);
// Get response. First wait for the header
while (socket.bytesAvailable() < (int)(sizeof(quint64)))
{
if (!socket.waitForReadyRead(riOctavePlugin::shortTimeOutMilliSecs))
{
error((("Waiting for header: ") + socket.errorString()).toLatin1().data());
return;
}
}
quint64 byteCount;
socketStream >> byteCount;
if (byteCount == 0)
{
return;
}
while (socket.bytesAvailable() < (int)(byteCount))
{
if (!socket.waitForReadyRead(riOctavePlugin::shortTimeOutMilliSecs))
{
error((("Waiting for data: ") + socket.errorString()).toLatin1().data());
return;
}
OCTAVE_QUIT;
}
quint64 cellCount;
socketStream >> cellCount;
octave_stdout << "riGetWellCells2: Num cells = " << cellCount << std::endl;
cellIs .reserve(cellCount);
cellJs .reserve(cellCount);
cellKs .reserve(cellCount);
gridIndices .reserve(cellCount);
cellStatuses .reserve(cellCount);
branchIds .reserve(cellCount);
segmentIds .reserve(cellCount);
qint32 i, j, k, gIdx, cStat, bId, sId;
for (size_t cIdx = 0; cIdx < cellCount; cIdx++)
{
socketStream >> i;
socketStream >> j;
socketStream >> k;
socketStream >> gIdx;
socketStream >> cStat;
socketStream >> bId;
socketStream >> sId;
cellIs.push_back (i);
cellJs.push_back (j);
cellKs.push_back (k);
gridIndices.push_back (gIdx);
cellStatuses.push_back(cStat);
branchIds.push_back (bId);
segmentIds.push_back (sId);
}
return;
}
DEFUN_DLD (riGetWellCells, args, nargout,
"Usage:\n"
"\n"
" riGetWellCells ([CaseId], WellName, TimeStep) \n"
"\n"
"This function returns the cells defined in the specified well for the time step requested \n"
"as a vector of Structures. \n"
"The Structure is defined as:\n"
"WellCellInfo { \n"
" I, J, K = int # Index to the cell in the grid\n"
" GridIndex = int # the index of the grid. Main grid has index 0.\n"
" CellStatus = int # is either 0 or 1, meaning the cell is closed or open respectively.\n"
"}\n"
"If the CaseId is not defined, ResInsights Current Case is used.\n"
)
{
if (nargout != 1)
{
error("riGetWellCells: Wrong number of output arguments, this function requires one output argument.\n");
print_usage();
return octave_value();
}
int nargin = args.length ();
if (nargin < 2)
{
error("riGetWellCells: Too few arguments, this function needs at least the well name and a timestep as input.\n");
print_usage();
return octave_value();
}
if (nargin > 3)
{
error("riGetWellCells: Too many arguments, this function takes at most three arguments.\n");
print_usage();
return octave_value();
}
std::vector<int> argIndices;
argIndices.push_back(0); // caseId
argIndices.push_back(1); // WellName
argIndices.push_back(2); // TimeStep
// Check if we do not have a CaseId:
if (args(argIndices[0]).is_string()) // Check if first argument is a text. If it is, the caseId is missing
{
argIndices[0] = -1;
for (size_t aIdx = 1; aIdx < argIndices.size(); ++aIdx)
--argIndices[aIdx];
}
if (!args(argIndices[1]).is_string()) // Check if the WellName argument is actually a string
{
error("riGetWellCells: Missing Well Name. this function needs at least the well name and a timestep as input.\n");
print_usage();
return octave_value();
}
if (!args(argIndices[2]).is_numeric_type()) // Check if the TimeStep argument is actually a number
{
error("riGetWellCells: The last argument must be a timestep index.\n");
print_usage();
return octave_value();
}
// Setup the argument list
int caseId = -1;
std::string wellName = "UNDEFINED";
int requestedTimeStep = -1;
if (argIndices[0] >= 0) caseId = args(argIndices[0]).int_value();
if (argIndices[1] >= 0) wellName = args(argIndices[1]).char_matrix_value().row_as_string(0);
if (argIndices[2] >= 0) requestedTimeStep = args(argIndices[2]).int_value();
if (wellName == "UNDEFINED")
{
error("riGetWellCells: The argument must be a text containing the well name.\n");
print_usage();
return octave_value();
}
if (requestedTimeStep == -1)
{
error("riGetWellCells: The last argument must be a timestep index (1 - timestepCount).\n");
print_usage();
return octave_value();
}
std::vector<int> cellIs, cellJs, cellKs;
std::vector<int> gridIndices;
std::vector<int> cellStatuses;
std::vector<int> branchIds;
std::vector<int> segmentIds;
getWellCells( cellIs, cellJs, cellKs,
gridIndices,
cellStatuses,
branchIds,
segmentIds,
"127.0.0.1", 40001,
caseId, QString::fromStdString(wellName), requestedTimeStep);
size_t cellCount = cellIs.size();
if (cellJs.size() != cellCount
|| cellKs.size() != cellCount
|| gridIndices.size() != cellCount
|| cellStatuses.size() != cellCount
|| branchIds.size() != cellCount
|| segmentIds.size() != cellCount )
{
error("riGetWellCells: Inconsistent data received from ResInsight.\n");
return octave_value();
}
// Create cells with N items for each field in the data structure
Cell cellIscv (cellCount, 1);
Cell cellJscv (cellCount, 1);
Cell cellKscv (cellCount, 1);
Cell gridIndicescv (cellCount, 1);
Cell cellStatusescv (cellCount, 1);
Cell branchIdscv (cellCount, 1);
Cell segmentIdscv (cellCount, 1);
for (size_t i = 0; i < cellCount; i++)
{
cellIscv (i) = cellIs [i];
cellJscv (i) = cellJs [i];
cellKscv (i) = cellKs [i];
gridIndicescv (i) = gridIndices [i];
cellStatusescv (i) = cellStatuses[i];
branchIdscv (i) = branchIds [i];
segmentIdscv (i) = segmentIds [i];
}
// Build a map between the field name and field cell values
Octave_map m;
m.assign(riOctavePlugin::wellCellInfo_I, cellIscv );
m.assign(riOctavePlugin::wellCellInfo_J, cellJscv );
m.assign(riOctavePlugin::wellCellInfo_K, cellKscv );
m.assign(riOctavePlugin::wellCellInfo_GridIndex , gridIndicescv );
m.assign(riOctavePlugin::wellCellInfo_CellStatus, cellStatusescv);
m.assign(riOctavePlugin::wellCellInfo_BranchId, branchIdscv );
m.assign(riOctavePlugin::wellCellInfo_SegmentId, segmentIdscv );
return octave_value(m);
}

View File

@ -0,0 +1,129 @@
#include <QtNetwork>
#include <octave/oct.h>
#include <octave/oct-map.h>
#include "riSettings.h"
void getWellNames(std::vector<QString>& wellNames, const QString &hostName, quint16 port,
const qint64& caseId)
{
QString serverName = hostName;
quint16 serverPort = port;
QTcpSocket socket;
socket.connectToHost(serverName, serverPort);
if (!socket.waitForConnected(riOctavePlugin::connectTimeOutMilliSecs))
{
error((("Connection: ") + socket.errorString()).toLatin1().data());
return;
}
// Create command and send it:
QString command;
command += QString("GetWellNames") + " " + QString::number(caseId);
QByteArray cmdBytes = command.toLatin1();
QDataStream socketStream(&socket);
socketStream.setVersion(riOctavePlugin::qtDataStreamVersion);
socketStream << (qint64)(cmdBytes.size());
socket.write(cmdBytes);
// Get response. First wait for the header
while (socket.bytesAvailable() < (int)(sizeof(quint64)))
{
if (!socket.waitForReadyRead(riOctavePlugin::shortTimeOutMilliSecs))
{
error((("Waiting for header: ") + socket.errorString()).toLatin1().data());
return;
}
}
quint64 byteCount;
socketStream >> byteCount;
// QString byteCountString = QString::number(byteCount);
//error(byteCountString.toLatin1().data());
while (socket.bytesAvailable() < (int)(byteCount))
{
if (!socket.waitForReadyRead(riOctavePlugin::shortTimeOutMilliSecs))
{
error((("Waiting for data: ") + socket.errorString()).toLatin1().data());
return;
}
OCTAVE_QUIT;
}
quint64 wellCount;
socketStream >> wellCount;
QString wellName;
for (size_t i = 0; i < wellCount; i++)
{
socketStream >> wellName;
wellNames.push_back(wellName);
}
return;
}
DEFUN_DLD (riGetWellNames, args, nargout,
"Usage:\n"
"\n"
" riGetWellNames([CaseId]) \n"
"\n"
"This function returns the names of all the wells in the case as a Vector of strings.\n"
"If the CaseId is not defined, ResInsights Current Case is used.\n"
)
{
int nargin = args.length ();
if (nargin > 1)
{
error("riGetWellNames: Too many arguments, this function takes one optional arguments.\n");
print_usage();
}
else if (nargout != 1)
{
error("riGetWellNames: Wrong number of output arguments, this function requires one output argument.\n");
print_usage();
}
else
{
qint64 argCaseId = -1;
if (nargin == 1)
{
argCaseId = args(0).uint_value();
}
std::vector<QString> wellNames;
getWellNames(wellNames, "127.0.0.1", 40001, argCaseId);
size_t caseCount = wellNames.size();
// Create cells with N items for each field in the data structure
//charMatrix octaveWellNames;
string_vector octaveWellNames;
for (size_t i = 0; i < caseCount; i++)
{
octaveWellNames.append(wellNames[i].toStdString());
}
// Build a map between the field name and field cell values
return octave_value(octaveWellNames);
}
return octave_value();
}

View File

@ -0,0 +1,206 @@
#include <QtNetwork>
#include <octave/oct.h>
#include <octave/oct-map.h>
#include "riSettings.h"
void getWellStatus(std::vector<QString>& wellTypes, std::vector<int>& wellStatuses, const QString &hostName, quint16 port,
const qint64& caseId, const QString& wellName, const int32NDArray& requestedTimeSteps)
{
QString serverName = hostName;
quint16 serverPort = port;
QTcpSocket socket;
socket.connectToHost(serverName, serverPort);
if (!socket.waitForConnected(riOctavePlugin::connectTimeOutMilliSecs))
{
error((("Connection: ") + socket.errorString()).toLatin1().data());
return;
}
// Create command and send it:
QString command;
command += QString("GetWellStatus") + " " + QString::number(caseId) + " " + wellName;
for (int i = 0; i < requestedTimeSteps.length(); ++i)
{
if (i == 0) command += " ";
command += QString::number(static_cast<int>(requestedTimeSteps.elem(i)) - 1); // To make the index 0-based
if (i != requestedTimeSteps.length() -1) command += " ";
}
QByteArray cmdBytes = command.toLatin1();
QDataStream socketStream(&socket);
socketStream.setVersion(riOctavePlugin::qtDataStreamVersion);
socketStream << (qint64)(cmdBytes.size());
socket.write(cmdBytes);
// Get response. First wait for the header
while (socket.bytesAvailable() < (int)(sizeof(quint64)))
{
if (!socket.waitForReadyRead(riOctavePlugin::shortTimeOutMilliSecs))
{
error((("Waiting for header: ") + socket.errorString()).toLatin1().data());
return;
}
}
quint64 byteCount;
socketStream >> byteCount;
while (socket.bytesAvailable() < (int)(byteCount))
{
if (!socket.waitForReadyRead(riOctavePlugin::shortTimeOutMilliSecs))
{
error((("Waiting for data: ") + socket.errorString()).toLatin1().data());
return;
}
OCTAVE_QUIT;
}
quint64 timeStepCount;
socketStream >> timeStepCount;
QString wellType;
qint32 wellStatus;
for (size_t i = 0; i < timeStepCount; i++)
{
socketStream >> wellType;
socketStream >> wellStatus;
wellTypes.push_back(wellType);
wellStatuses.push_back(wellStatus);
}
return;
}
DEFUN_DLD (riGetWellStatus, args, nargout,
"Usage:\n"
"\n"
" riGetWellStatus ([CaseId], WellName, [RequestedTimeSteps]) \n"
"\n"
"This function returns the status information for a specified well for each\n"
"requested time step as a vector of Structures. \n"
"The Structure is defined as:\n"
"WellStatus { \n"
" WellType = string # \"Producer\", \"OilInjector\", \"WaterInjector\", \"GasInjector\", \"NotDefined\" \n"
" WellStatus = int # is either 0 or 1, meaning the well is shut or open respectively.\n"
"}\n"
"If the CaseId is not defined, ResInsights Current Case is used.\n"
)
{
if (nargout != 1)
{
error("riGetWellStatus: Wrong number of output arguments, this function requires one output argument.\n");
print_usage();
return octave_value();
}
int nargin = args.length ();
if (nargin < 1)
{
error("riGetWellStatus: Too few arguments, this function needs at least the well name as input.\n");
print_usage();
return octave_value();
}
if (nargin > 3)
{
error("riGetWellStatus: Too many arguments, this function takes at most three arguments.\n");
print_usage();
return octave_value();
}
std::vector<int> argIndices;
argIndices.push_back(0); // caseId
argIndices.push_back(1); // WellName
argIndices.push_back(2); // TimeSteps
// Check if we do not have a CaseId:
if (args(argIndices[0]).is_string()) // Check if first argument is a text. If it is, the caseId is missing
{
argIndices[0] = -1;
for (size_t aIdx = 1; aIdx < argIndices.size(); ++aIdx)
--argIndices[aIdx];
}
// Check if we have a Requested TimeSteps
int lastArgumentIndex = argIndices[2] ;
if (!(nargin > argIndices[2] && args(argIndices[2]).is_matrix_type()))
{
argIndices[2] = -1;
}
// Check if we have more arguments than we should
if (nargin > lastArgumentIndex + 1)
{
error("riGetWellStatus: Unexpected argument at the end.\n");
print_usage();
return octave_value_list ();
}
// Setup the argument list
NDArray propertyFrames;
int caseId = -1;
std::string wellName = "UNDEFINED";
int32NDArray requestedTimeSteps;
if (argIndices[0] >= 0) caseId = args(argIndices[0]).int_value();
if (argIndices[1] >= 0) wellName = args(argIndices[1]).char_matrix_value().row_as_string(0);
if (argIndices[2] >= 0) requestedTimeSteps = args(argIndices[2]).int32_array_value();
if (wellName == "UNDEFINED")
{
error("riGetWellStatus: The argument must be a text containing the well name.\n");
print_usage();
return octave_value();
}
std::vector<QString> wellType;
std::vector<int> wellStatus;
getWellStatus(wellType, wellStatus, "127.0.0.1", 40001, caseId, QString::fromStdString(wellName), requestedTimeSteps);
size_t caseCount = wellType.size();
if (wellType.size() != wellStatus.size() )
{
error("riGetWellStatus: Inconsistent data received from ResInsight.\n");
return octave_value();
}
else
{
// Create cells with N items for each field in the data structure
Cell cellValuesB(caseCount, 1);
Cell cellValuesC(caseCount, 1);
for (size_t i = 0; i < caseCount; i++)
{
cellValuesB(i) = wellType[i].toLatin1().data();
cellValuesC(i) = wellStatus[i];
}
// Build a map between the field name and field cell values
Octave_map m;
m.assign(riOctavePlugin::wellStatus_WellType, cellValuesB);
m.assign(riOctavePlugin::wellStatus_WellStatus, cellValuesC);
return octave_value(m);
}
}

View File

@ -30,10 +30,27 @@ namespace riOctavePlugin
char caseInfo_CaseType[] = "CaseType";
char caseInfo_CaseGroupId[] = "CaseGroupId";
// Octave data structure: PropertyInfo
char propertyInfo_PropName[] = "PropName";
char propertyInfo_PropType[] = "PropType";
// Octave data structure: WellStatus
char wellStatus_WellType[] = "WellType";
char wellStatus_WellStatus[] = "WellStatus";
// Octave data structure : CaseGroupInfo
char caseGroupInfo_CaseGroupId[] = "CaseGroupId";
char caseGroupInfo_CaseGroupName[] = "CaseName";
// Octave data structure : WellCellInfo
char wellCellInfo_I[] = "I";
char wellCellInfo_J[] = "J";
char wellCellInfo_K[] = "K";
char wellCellInfo_GridIndex [] = "GridIndex";
char wellCellInfo_CellStatus[] = "CellStatus";
char wellCellInfo_BranchId[] = "BranchId";
char wellCellInfo_SegmentId[] = "SegmentId";
// Octave data structure : TimeStepDate
char timeStepDate_Year[] = "Year";
char timeStepDate_Month[] = "Month";

View File

@ -1,7 +1,7 @@
set(CMAKE_MAJOR_VERSION 0)
set(CMAKE_MINOR_VERSION 9)
set(CMAKE_PATCH_VERSION 24)
set(CMAKE_PATCH_VERSION 26)
set(PRODUCTVER ${CMAKE_MAJOR_VERSION},${CMAKE_MINOR_VERSION},0,${CMAKE_PATCH_VERSION})
set(STRPRODUCTVER ${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}.${CMAKE_PATCH_VERSION})

View File

@ -74,13 +74,16 @@ if (HAVE_SETENV)
add_definitions( -DPOSIX_SETENV )
endif()
check_function_exists( opendir HAVE_OPENDIR )
if (HAVE_OPENDIR)
add_definitions( -DHAVE_OPENDIR )
endif()
check_function_exists( getpwuid HAVE_GETPWUID )
if (HAVE_GETPWUID)
add_definitions( -DHAVE_GETPWUID )
endif()
# The usleep() check uses the symbol HAVE__USLEEP with double
# underscore to avoid conflict with plplot which defines the
# HAVE_USLEEP symbol.

View File

@ -1,9 +1,14 @@
include(cmake/ert_module.cmake)
add_subdirectory( script )
add_subdirectory( src )
add_subdirectory( modules )
#if (BUILD_APPLICATONS)
# add_subdirectory( applications )
#endif()
#if (BUILD_TESTS)
# add_subdirectory( tests )
#endif()
if (BUILD_APPLICATIONS)
add_subdirectory( applications )
endif()
if (BUILD_TESTS)
add_subdirectory( tests )
endif()

View File

@ -0,0 +1,8 @@
add_executable( ert_module_test ert_module_test.c )
target_link_libraries( ert_module_test analysis ert_util )
if (USE_RUNPATH)
add_runpath( ert_module_test )
endif()
install(TARGETS ert_module_test DESTINATION ${CMAKE_INSTALL_PREFIX}/bin)

View File

@ -15,20 +15,22 @@
See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
for more details.
*/
#include <dlfcn.h>
#include <analysis_module.h>
#include <stdlib.h>
#include <stdbool.h>
#include <rng.h>
#include <dlfcn.h>
#include <ert/util/rng.h>
#include <ert/analysis/analysis_module.h>
void check_module( rng_type * rng , const char * lib_name ) {
int check_module( rng_type * rng , const char * lib_name ) {
analysis_module_load_status_enum load_status;
analysis_module_type * module = analysis_module_alloc_external__( rng , "MODULE" , lib_name , false , &load_status);
if (module != NULL) {
printf("Module loaded successfully\n");
analysis_module_free( module );
return 0;
} else {
if (load_status == DLOPEN_FAILURE) {
printf("\ndlerror(): %s\n\n",dlerror());
@ -46,13 +48,11 @@ void check_module( rng_type * rng , const char * lib_name ) {
printf("See documentation of \'symbol_table\' in modules.txt.\n\n");
}
}
return 1;
}
int main( int argc , char ** argv) {
int iarg;
for (iarg = 1; iarg < argc; iarg++) {
check_module( NULL , argv[iarg] );
}
exit( check_module( NULL , argv[1] ) );
}

View File

@ -0,0 +1,21 @@
function( ert_module module args source_files )
set( build_file ${CMAKE_CURRENT_BINARY_DIR}/${module}.so )
set( depends analysis )
set( arg_string "${module} ${args}")
separate_arguments( arg_list UNIX_COMMAND "${arg_string}")
foreach (src_file ${source_files} )
list(APPEND arg_list ${CMAKE_CURRENT_SOURCE_DIR}/${src_file} )
list(APPEND depends ${CMAKE_CURRENT_SOURCE_DIR}/${src_file} )
endforeach()
add_custom_command(
OUTPUT ${build_file}
COMMAND ${PROJECT_SOURCE_DIR}/libanalysis/script/ert_module
ARGS ${arg_list}
DEPENDS ${depends})
install(FILES ${build_file} DESTINATION ${CMAKE_INSTALL_LIBDIR})
add_custom_target( ${module} ALL DEPENDS ${build_file} )
endfunction()

View File

@ -42,7 +42,7 @@ extern "C" {
#define ANALYSIS_USE_A 4 // The module will read the content of A - but not modify it.
#define ANALYSIS_UPDATE_A 8 // The update will be based on modifying A directly, and not on an X matrix.
#define ANALYSIS_SCALE_DATA 16
#define ANALYSIS_ITERABLE 32 // The module can bu uused as an iterative smoother.
#define EXTERNAL_MODULE_NAME "analysis_table"
#define EXTERNAL_MODULE_SYMBOL analysis_table

View File

@ -0,0 +1,7 @@
set( args "--silent --exclude-ert -I${PROJECT_SOURCE_DIR}/libanalysis/include -I${PROJECT_SOURCE_DIR}/libert_util/include -I${CMAKE_CURRENT_SOURCE_DIR} -I${PROJECT_BINARY_DIR}/libert_util/include")
set( RML_SOURCE_FILES
rml_enkf.c
rml_enkf_common.c )
ert_module( rml_enkf ${args} "${RML_SOURCE_FILES}")

View File

@ -13,11 +13,11 @@
FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
for more details.
for more details.
*/
#include <stdlib.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <math.h>
@ -30,9 +30,10 @@
#include <ert/analysis/analysis_module.h>
#include <ert/analysis/analysis_table.h>
#include <ert/analysis/enkf_linalg.h>
#include <ert/analysis/rml_enkf_common.h>
#include <ert/analysis/std_enkf.h>
#include <rml_enkf_common.h>
/*
A random 'magic' integer id which is used for run-time type checking
of the input data.
@ -128,6 +129,9 @@ void rml_enkf_set_subspace_dimension( rml_enkf_data_type * data , int subspace_d
data->truncation = INVALID_TRUNCATION;
}
void rml_enkf_set_iteration_number( rml_enkf_data_type *data , int iteration_number ) {
data->iteration_nr = iteration_number;
}
void * rml_enkf_data_alloc( rng_type * rng) {
@ -136,7 +140,7 @@ void * rml_enkf_data_alloc( rng_type * rng) {
rml_enkf_set_truncation( data , DEFAULT_ENKF_TRUNCATION_ );
rml_enkf_set_subspace_dimension( data , DEFAULT_SUBSPACE_DIMENSION );
data->option_flags = ANALYSIS_NEED_ED + ANALYSIS_UPDATE_A;
data->option_flags = ANALYSIS_NEED_ED + ANALYSIS_UPDATE_A + ANALYSIS_ITERABLE;
data->iteration_nr = 0;
data->Std = 0;
data->Cd = NULL;
@ -296,6 +300,8 @@ bool rml_enkf_set_int( void * arg , const char * var_name , int value) {
if (strcmp( var_name , ENKF_NCOMP_KEY_) == 0)
rml_enkf_set_subspace_dimension( module_data , value );
else if(strcmp( var_name , "NUM_ITER") == 0)
rml_enkf_set_iteration_number( module_data , value );
else
name_recognized = false;

View File

@ -31,10 +31,8 @@
#include <ert/analysis/analysis_module.h>
#include <ert/analysis/analysis_table.h>
#include <ert/analysis/enkf_linalg.h>
#include <ert/analysis/rml_enkf_common.h>
#include <rml_enkf_common.h>
/* This program contains common functions to both rml_enkf & rml_enkf_imodel*/

View File

@ -0,0 +1 @@
install(PROGRAMS ert_module DESTINATION ${CMAKE_INSTALL_PREFIX}/bin)

View File

@ -0,0 +1,246 @@
#!/usr/bin/env python
import sys
import os
import os.path
from optparse import OptionParser
ert_root = os.path.realpath( os.path.join(os.path.dirname( os.path.abspath( __file__)) , "../") )
#-----------------------------------------------------------------
default_lib_list = ["analysis" , "ert_util"]
default_define_list = ["HAVE_PTHREAD"]
CFLAGS = "-std=gnu99 -O2 -Wall -fpic -g"
LDFLAGS_list = ["-shared"]
CC = "gcc"
LD = CC
#-----------------------------------------------------------------
c_file = 0
header_file = 1
object_file = 2
other = 3
file_types = {".o" : object_file ,
".h" : header_file ,
".c" : c_file }
def base_name(file):
(name,ext) = os.path.split( file )
return name
def file_type( file ):
name,ext = os.path.splitext( file )
return file_types.get( ext , other )
def object_file_name( file ):
(name,ext) = os.path.splitext( file )
return "%s.o" % name
def make_LDFLAGS( use_rpath , lib_path_list):
if use_rpath:
LDFLAGS_list.append("-Wl,--enable-new-dtags")
for path in lib_path_list:
LDFLAGS_list.append("-Wl,-rpath,%s" % path)
LDFLAGS_list.append("-Wl,-soname,")
return " ".join(LDFLAGS_list)
def make_XFLAG( X , def_list ):
FLAG = ""
for d in def_list:
FLAG += "-%s%s " % (X , d)
return FLAG
def compile_file( file , IFLAG , DFLAG , verbose):
target = object_file_name( file )
if os.path.exists( target ):
os.unlink( target )
cmd = "%s %s %s %s -c %s -o %s" % (CC , CFLAGS , IFLAG , DFLAG , file , target)
if verbose:
print "Compiling: %s" % cmd
os.system( cmd )
if os.path.exists( target ):
return target
else:
sys.exit("Compile cmd:%s failed" % cmd)
def link( soname , filename , object_list , LDFLAGS , LFLAG , lFLAG , verbose):
object_string = ""
for obj in object_list:
object_string += "%s " % obj
cmd = "%s %s%s -o %s %s %s %s" % ( LD , LDFLAGS , soname , filename , object_string , LFLAG , lFLAG)
if verbose:
print "Linking : %s" % cmd
if os.path.exists( filename ):
os.unlink( filename )
os.system(cmd)
if os.path.exists( filename ):
return True
else:
return False
usage = """
The ert_module script is a small convenience script to
compile C source code into an analysis module which can
be loaded by ert. The script is controlled by commandline
arguments:
1. The first argument should be the name of the module
you are creating, an extension .so will be appended.
2. List the source files you want to include, the
files should have extension .c. In addition you can
include object files which have been compiled by
other means, the object files should have
extension .o
3. Optionally you can pass -I and -D options which are
passed to the compiler; and -l and -L options which
are passed to the linker.
Example:
ert_module my_module my_src1.c my_src2.c f90_object1.o f90_object2.o -I/path -DFAST=Yes -L/path/to/lib -lfm -lz
Will create a module 'my_module' based on the src files my_src1.c
and my_src2.c; in addition the object files f90_object1.o and
f90_object2.o will be included in the final module.
-----------------------------------------------------------------
To compile the module code you will typically need the include files
and libraries from an existing ert installation. By default the
ert_module script will locate the ert installation based on the
location of the script, but you can pass the option:
--ert-root=/path/where/ert/is/installed
The --ert-root option should point to a directory containing the
lib64/ and include/ directories of a binary etr distribution. In
addition to --ert-root you can use the normal -L/path/to/lib option to
send in additional link path arguments.
By default the path to shared libraries will not be embedded in the
resulting module, but by passing the option --use-rpath you can tell
the script to embed these paths in the final shared object.
-----------------------------------------------------------------
Options summary:
-L/path/to/lib: Include the path /path/to/lib in the linker path
-llib1 : Link with the library lib1
-I/include : Include the path /include in the compiler include path.
--ert-root=/path/to/ert : Use this is as root for ert headers
and libraries. [Default: inferred from location of script]
--use-rpath : Embed library paths in shared objects. Default off.
--exclude-ert: Do not use any ert default libraries or headers
Default flags:
Compile: %s %s %s
Link: %s %s %s
""" % (CC,
make_XFLAG( "I" , ["./" , "%s/include" % ert_root]) ,
make_XFLAG( "D" , default_define_list) ,
LD ,
make_XFLAG("L" , ["%s/lib64" % ert_root]) ,
make_XFLAG("l" , default_lib_list))
parser = OptionParser( usage )
parser.add_option("--ert-root" , dest="ert_root" , action="store")
parser.add_option("-I" , dest = "include_path_list", action = "append")
parser.add_option("-D" , dest = "define_list" , action = "append")
parser.add_option("-L" , dest = "lib_path_list" , action = "append")
parser.add_option("-l" , dest = "lib_list" , action = "append")
parser.add_option("--exclude-ert" , dest = "exclude_ert" , action="store_true" , default = False)
parser.add_option("--use-rpath" , dest="use_rpath" , action="store_true" , default = False)
parser.add_option("--silent" , dest="silent" , action="store_true" , default = False)
(options , args) = parser.parse_args()
if len(args) == 0:
sys.exit( usage )
if options.ert_root:
ert_root = options.ert_root
if options.exclude_ert:
include_path_list = ["./"]
lib_path_list = []
define_list = []
lib_list = []
else:
include_path_list = ["./" , "%s/include" % ert_root]
lib_path_list = ["%s/lib64" % ert_root]
define_list = default_define_list
lib_list = default_lib_list
if options.include_path_list:
include_path_list += options.include_path_list
if options.define_list:
define_list += options.define_list
if options.lib_list:
lib_list += options.lib_list
if options.lib_path_list:
lib_path_list += options.lib_path_list
verbose = not options.silent
LDFLAGS = make_LDFLAGS( options.use_rpath , lib_path_list)
input_name = args[0]
(path , tmp ) = os.path.split( input_name )
(module , ext) = os.path.splitext( tmp )
soname = "%s.so" % module
if path:
filename = "%s/%s.so" % (path , module)
if not os.path.exists( path ):
os.makedirs( path )
else:
filename = "%s.so" % module
#-----------------------------------------------------------------
IFLAG = make_XFLAG( "I" , include_path_list )
DFLAG = make_XFLAG( "D" , define_list )
LFLAG = make_XFLAG( "L" , lib_path_list )
lFLAG = make_XFLAG( "l" , lib_list )
object_list = []
for arg in args[1:]:
if file_type( arg ) == c_file:
object_list.append( compile_file( arg , IFLAG , DFLAG , verbose) )
elif file_type( arg ) == object_file:
object_list.append( arg )
else:
print "** Warning: ignoring file:%s" % arg
if link( soname , filename , object_list , LDFLAGS , LFLAG , lFLAG , verbose):
sys.exit()
else:
sys.exit("Creating library failed")

View File

@ -1,6 +1,6 @@
# Common libanalysis library
set( source_files analysis_module.c enkf_linalg.c std_enkf.c sqrt_enkf.c cv_enkf.c bootstrap_enkf.c null_enkf.c fwd_step_enkf.c )
set( header_files analysis_module.h enkf_linalg.h analysis_table.h)
set( header_files analysis_module.h enkf_linalg.h analysis_table.h std_enkf.h)
add_library( analysis SHARED ${source_files} )
set_target_properties( analysis PROPERTIES COMPILE_DEFINITIONS INTERNAL_LINK)
set_target_properties( analysis PROPERTIES VERSION 1.0 SOVERSION 1.0 )
@ -14,17 +14,22 @@ if (USE_RUNPATH)
add_runpath( analysis )
endif()
# List of modules
set( CMAKE_SHARED_MODULE_PREFIX "" )
add_library( std_enkf MODULE std_enkf.c )
add_library( sqrt_enkf MODULE sqrt_enkf.c )
add_library( rml_enkf MODULE rml_enkf.c rml_enkf_common.c )
## List of modules
#set( CMAKE_SHARED_MODULE_PREFIX "" )
##add_library( std_enkf MODULE std_enkf.c )
#add_library( sqrt_enkf MODULE sqrt_enkf.c )
#add_library( rml_enkf MODULE rml_enkf.c rml_enkf_common.c )
#
#ert_module( std_enkf std_enkf.c )
#-----------------------------------------------------------------
if (INSTALL_ERT)
install(TARGETS analysis DESTINATION ${CMAKE_INSTALL_LIBDIR})
install(TARGETS rml_enkf DESTINATION ${CMAKE_INSTALL_LIBDIR})
#install(TARGETS rml_enkf DESTINATION ${CMAKE_INSTALL_LIBDIR})
foreach(header ${header_files})
install(FILES ../include/ert/analysis/${header} DESTINATION ${CMAKE_INSTALL_PREFIX}/include/ert/analysis)
endforeach()

View File

@ -1,167 +0,0 @@
#!/usr/bin/env python
import sys
import os
from optparse import OptionParser
#-----------------------------------------------------------------
lib_list = ["analysis" , "ert_util"]
lib_path_list = ["./" , "../../libutil/slib"]
include_path_list = ["../include" , "../../libutil/src"]
define_list = ["HAVE_PTHREAD"]
CFLAGS = "-std=gnu99 -O2 -Wall -fpic -g"
LDFLAGS = "-shared -Wl,-soname,"
CC = "gcc"
LD = CC
#-----------------------------------------------------------------
c_file = 0
header_file = 1
object_file = 2
other = 3
file_types = {".o" : object_file ,
".h" : header_file ,
".c" : c_file }
def base_name(file):
(name,ext) = os.path.split( file )
return name
def file_type( file ):
name,ext = os.path.splitext( file )
return file_types.get( ext , other )
def object_file_name( file ):
(name,ext) = os.path.splitext( file )
return "%s.o" % name
def make_XFLAG( X , def_list ):
FLAG = ""
for d in def_list:
FLAG += "-%s%s " % (X , d)
return FLAG
def compile_file( file , IFLAG , DFLAG ):
target = object_file_name( file )
if os.path.exists( target ):
os.unlink( target )
cmd = "%s %s %s %s -c %s -o %s" % (CC , CFLAGS , IFLAG , DFLAG , file , target)
print "Compiling: %s" % cmd
os.system( cmd )
if os.path.exists( target ):
return target
else:
sys.exit("Compile cmd:%s failed" % cmd)
def link( libname , object_list , LFLAG , lFLAG):
(tmp,ext) = os.path.splitext( libname )
if not ext:
libname += ".so"
object_string = ""
for obj in object_list:
object_string += "%s " % obj
soname = libname
cmd = "%s %s%s -o %s %s %s %s" % ( LD , LDFLAGS , soname , libname , object_string , LFLAG , lFLAG)
print "Linking : %s" % cmd
if os.path.exists( libname ):
os.unlink( libname )
os.system(cmd)
if os.path.exists( libname ):
return True
else:
return False
usage = """
The ert_module script is a small convenience script to
compile C source code into an analysis module which can
be loaded by ert. The script is controlled by commandline
arguments:
1. The first argument should be the name of the module
you are creating, an extension .so will be appended.
2. List the source files you want to include, the
files should have extension .c. In addition you can
include object files which have been compiled by
other means, the object files should have
extension .o
3. Optionally you can pass -I and -D options which are
passed to the compiler; and -l and -L options which
are passed to the linker.
Example:
ert_module my_module my_src1.c my_src2.c f90_object1.o f90_object2.o -I/path -DFAST=Yes -L/path/to/lib -lfm -lz
Will create a module 'my_module' based on the src files my_src1.c
and my_src2.c; in addition the object files f90_object1.o and
f90_object2.o will be included in the final module.
By default the ert_module script will include some libraries from the
core ert distribution; if you are not interested in referencing these
you can issue the option --exclude-ert. Default flags:
Compile: %s %s
Link: %s %s
""" % (make_XFLAG( "I" , include_path_list) , make_XFLAG( "D" , define_list) , make_XFLAG("L" , lib_path_list) , make_XFLAG("l" , lib_list))
parser = OptionParser( usage )
parser.add_option("-I" , dest = "include_path_list", action = "append")
parser.add_option("-D" , dest = "define_list" , action = "append")
parser.add_option("-L" , dest = "lib_path_list" , action = "append")
parser.add_option("-l" , dest = "lib_list" , action = "append")
parser.add_option("--exclude-ert" , dest = "exclude_ert" , action="store_true" , default = False)
(options , args) = parser.parse_args()
if len(args) == 0:
sys.exit( usage )
if options.exclude_ert:
include_path_list = []
define_list = []
lib_list = []
lib_path_list = []
if options.include_path_list:
include_path_list += options.include_path_list
if options.define_list:
define_list += options.define_list
if options.lib_list:
lib_list += options.lib_list
if options.lib_path_list:
lib_path_list += options.lib_path_list
IFLAG = make_XFLAG( "I" , include_path_list )
DFLAG = make_XFLAG( "D" , define_list )
LFLAG = make_XFLAG( "L" , lib_path_list )
lFLAG = make_XFLAG( "l" , lib_list )
object_list = []
for arg in args[1:]:
if file_type( arg ) == c_file:
object_list.append( compile_file( arg ,IFLAG , DFLAG) )
elif file_type( arg ) == object_file:
object_list.append( arg )
else:
print "** Warning: ignoring file:%s" % arg
link( args[0] , object_list , LFLAG , lFLAG)

View File

@ -0,0 +1 @@
add_test( analysis_rml_enkf_module ${EXECUTABLE_OUTPUT_PATH}/ert_module_test ${PROJECT_BINARY_DIR}/libanalysis/modules/rml_enkf.so )

View File

@ -33,7 +33,7 @@ extern "C" {
nnc_vector_type * nnc_vector_alloc(int lgr_nr);
void nnc_vector_free( nnc_vector_type * nnc_vector );
void nnc_vector_add_nnc(nnc_vector_type * nnc_vector, int global_cell_number);
const int_vector_type * nnc_vector_get_index_list(const nnc_vector_type * nnc_vector);
const int_vector_type * nnc_vector_get_index_list(nnc_vector_type * nnc_vector);
int nnc_vector_get_lgr_nr(const nnc_vector_type * nnc_vector );
void nnc_vector_free__(void * arg);

View File

@ -2133,7 +2133,7 @@ static void ecl_grid_init_nnc_cells( ecl_grid_type * grid1, ecl_grid_type * grid
ecl_cell_type * grid1_cell = ecl_grid_get_cell(grid1, grid1_cell_index);
ecl_cell_type * grid2_cell = ecl_grid_get_cell(grid2, grid2_cell_index);
//Add the non-neighbour connection in both directions
//Add the non-neighbour connection in both directions
nnc_info_add_nnc(grid1_cell->nnc_info, grid2->lgr_nr, grid2_cell_index);
nnc_info_add_nnc(grid2_cell->nnc_info, grid1->lgr_nr, grid1_cell_index);
@ -2149,28 +2149,35 @@ static void ecl_grid_init_nnc_cells( ecl_grid_type * grid1, ecl_grid_type * grid
*/
static void ecl_grid_init_nnc(ecl_grid_type * main_grid, ecl_file_type * ecl_file) {
int num_nnchead_kw = ecl_file_get_num_named_kw( ecl_file , NNCHEAD_KW );
int num_nncg_kw = ecl_file_get_num_named_kw( ecl_file , NNCG_KW );
int i;
for (i = 0; i < num_nnchead_kw; i++) {
ecl_kw_type * nnchead_kw = ecl_file_iget_named_kw( ecl_file , NNCHEAD_KW , i);
int lgr_nr = ecl_kw_iget_int(nnchead_kw, NNCHEAD_LGR_INDEX);
ecl_kw_type * keyword1 = NULL;
ecl_kw_type * keyword2 = NULL;
if (ECL_GRID_MAINGRID_LGR_NR == lgr_nr) {
keyword1 = ecl_file_iget_named_kw( ecl_file , NNC1_KW , i);
keyword2 = ecl_file_iget_named_kw( ecl_file , NNC2_KW , i);
} else {
int nnc_lgr_index = (num_nnchead_kw == num_nncg_kw) ? i : i-1; //Subtract 1 if no nnc data for main grid
keyword1 = ecl_file_iget_named_kw( ecl_file , NNCL_KW , nnc_lgr_index);
keyword2 = ecl_file_iget_named_kw( ecl_file , NNCG_KW , nnc_lgr_index);
}
ecl_file_push_block(ecl_file); /* <---------------------------------------------------------------- */
ecl_file_select_block(ecl_file , NNCHEAD_KW , i);
{
ecl_grid_type * grid = (lgr_nr > 0) ? ecl_grid_get_lgr_from_lgr_nr(main_grid, lgr_nr) : main_grid;
ecl_grid_init_nnc_cells(grid, main_grid, keyword1, keyword2);
ecl_kw_type * nnchead_kw = ecl_file_iget_named_kw(ecl_file, NNCHEAD_KW, 0);
int lgr_nr = ecl_kw_iget_int(nnchead_kw, NNCHEAD_LGR_INDEX);
if (ecl_file_has_kw(ecl_file , NNC1_KW)) {
const ecl_kw_type * nnc1 = ecl_file_iget_named_kw(ecl_file, NNC1_KW, 0);
const ecl_kw_type * nnc2 = ecl_file_iget_named_kw(ecl_file, NNC2_KW, 0);
{
ecl_grid_type * grid = (lgr_nr > 0) ? ecl_grid_get_lgr_from_lgr_nr(main_grid, lgr_nr) : main_grid;
ecl_grid_init_nnc_cells(grid, grid, nnc1, nnc2);
}
}
if (ecl_file_has_kw(ecl_file , NNCL_KW)) {
const ecl_kw_type * nncl = ecl_file_iget_named_kw(ecl_file, NNCL_KW, 0);
const ecl_kw_type * nncg = ecl_file_iget_named_kw(ecl_file, NNCG_KW, 0);
{
ecl_grid_type * grid = (lgr_nr > 0) ? ecl_grid_get_lgr_from_lgr_nr(main_grid, lgr_nr) : main_grid;
ecl_grid_init_nnc_cells(grid, main_grid, nncl, nncg);
}
}
}
ecl_file_pop_block( ecl_file ); /* <------------------------------------------------------------------ */
}
}

View File

@ -422,7 +422,6 @@ void fortio_fclose(fortio_type *fortio) {
bool fortio_is_fortio_file(fortio_type * fortio) {
FILE * stream = fortio->stream;
offset_type init_pos = fortio_ftell(fortio);
int elm_read;
bool is_fortio_file = false;

View File

@ -24,6 +24,7 @@
#include <ert/util/type_macros.h>
#include <ert/ecl/nnc_vector.h>
#include <ert/ecl/nnc_index_list.h>
#define NNC_VECTOR_TYPE_ID 875615078
@ -31,8 +32,8 @@
struct nnc_vector_struct {
UTIL_TYPE_ID_DECLARATION;
int_vector_type *nnc_index_list;
int lgr_nr;
nnc_index_list_type * index_list;
int lgr_nr;
};
@ -44,13 +45,13 @@ static UTIL_SAFE_CAST_FUNCTION(nnc_vector , NNC_VECTOR_TYPE_ID)
nnc_vector_type * nnc_vector_alloc(int lgr_nr) {
nnc_vector_type * nnc_vector = util_malloc( sizeof * nnc_vector );
UTIL_TYPE_ID_INIT(nnc_vector , NNC_VECTOR_TYPE_ID);
nnc_vector->nnc_index_list = int_vector_alloc(0, 0);
nnc_vector->index_list = nnc_index_list_alloc();
nnc_vector->lgr_nr = lgr_nr;
return nnc_vector;
}
void nnc_vector_free( nnc_vector_type * nnc_vector ) {
int_vector_free( nnc_vector->nnc_index_list );
nnc_index_list_free( nnc_vector->index_list );
free( nnc_vector );
}
@ -62,12 +63,12 @@ void nnc_vector_free__(void * arg) {
void nnc_vector_add_nnc(nnc_vector_type * nnc_vector, int global_cell_number) {
int_vector_append( nnc_vector->nnc_index_list , global_cell_number );
nnc_index_list_add_index( nnc_vector->index_list , global_cell_number );
}
const int_vector_type * nnc_vector_get_index_list(const nnc_vector_type * nnc_vector) {
return nnc_vector->nnc_index_list;
const int_vector_type * nnc_vector_get_index_list(nnc_vector_type * nnc_vector) {
return nnc_index_list_get_list(nnc_vector->index_list);
}

View File

@ -0,0 +1,34 @@
/*
Copyright (C) 2013 Statoil ASA, Norway.
The file 'ecl_nnc_index_list_grid.c' is part of ERT - Ensemble based Reservoir Tool.
ERT 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.
ERT 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 <stdlib.h>
#include <stdbool.h>
#include <ert/util/test_util.h>
#include <ert/util/util.h>
#include <ert/util/int_vector.h>
#include <ert/ecl/nnc_index_list.h>
#include <ert/ecl/ecl_grid.h>
#include <ert/ecl/ecl_file.h>
int main( int argc , char ** argv) {
ecl_grid_type * ecl_grid = ecl_grid_alloc( argv[1] );
exit(0);
}

View File

@ -65,11 +65,13 @@ void test_nnc_lgr( const char * grid_filename ) {
const int_vector_type * nnc_cell_number_vec = nnc_info_get_index_list(nnc_info, 0);
test_assert_not_NULL(nnc_cell_number_vec);
int_vector_fprintf(nnc_cell_number_vec , stdout , "nnc_cell_number" , "%6d");
test_assert_int_equal(int_vector_size(nnc_cell_number_vec), 1);
test_assert_int_equal(int_vector_iget(nnc_cell_number_vec, 0), 151053);
//LGR
const int data[] = {126394, 126305};
const int data[] = {126305, 126394};
ecl_grid_type * lgr_grid = ecl_grid_iget_lgr(ecl_grid, 0);
test_assert_not_NULL( lgr_grid );
@ -85,7 +87,7 @@ void test_nnc_lgr( const char * grid_filename ) {
int i;
for (i = 0; i < int_vector_size(lgr_nnc_cell_number_vec); i++)
test_assert_int_equal(int_vector_iget(lgr_nnc_cell_number_vec, i), data[i]);
test_assert_int_equal(data[i], int_vector_iget(lgr_nnc_cell_number_vec, i));
ecl_grid_free(ecl_grid);
}
@ -98,7 +100,7 @@ void test_nnc_multiple_lgr( const char * grid_filename) {
{
//Global grid, check NNC for cell with global index 736
int data[] = {11957, 20336, 3528, 6321, 9114, 11907, 20286};
int data[] = {3528, 6321, 9114, 11907, 11957, 20286 , 20336};
const nnc_info_type * nnc_info = ecl_grid_get_cell_nnc_info1(ecl_grid, 736);
test_assert_not_NULL(nnc_info);
@ -120,7 +122,7 @@ void test_nnc_multiple_lgr( const char * grid_filename) {
{
//Global grid, check NNC for cell with global index 138291
int data[] = {141035, 143828, 141085, 143878};
int data[] = {141035, 141085, 143828, 143878};
const nnc_info_type * nnc_info = ecl_grid_get_cell_nnc_info1(ecl_grid, 138291);
test_assert_not_NULL(nnc_info);
@ -138,7 +140,7 @@ void test_nnc_multiple_lgr( const char * grid_filename) {
{
//LGR nr 1, cell global index 0: check NNCs to main grid
int data[] = {29012, 26220};
int data[] = {26220 , 29012};
ecl_grid_type * lgr_grid = ecl_grid_iget_lgr(ecl_grid, 0);
test_assert_not_NULL(lgr_grid);
@ -211,7 +213,7 @@ void test_nnc_multiple_lgr( const char * grid_filename) {
{
//LGR nr 99, check NNC for cell with global index 736
int data[] = {126671, 79142};
int data[] = {79142 ,126671};
ecl_grid_type * lgr_grid = ecl_grid_iget_lgr(ecl_grid, 98-1); //Subtract 1: LGR nr 98 is not present in the test file. LGRs are numbered 1-97 and 99-110 in test file.
test_assert_not_NULL(lgr_grid);
@ -333,7 +335,7 @@ int main(int argc , char ** argv) {
test_nnc_global_grid( EGRID_file1 );
test_nnc_lgr( EGRID_file2 );
test_nnc_multiple_lgr( EGRID_file3 );
test_nnc_multiple_lgr( EGRID_file3 );
test_nnc_amalgamated_lgrs(EGRID_file3);
test_nnc_dual_poro( EGRID_file4 );

View File

@ -35,6 +35,11 @@ int main(int argc , char ** argv) {
nnc_vector_add_nnc( vector , 200 );
nnc_vector_add_nnc( vector , 300 );
nnc_vector_add_nnc( vector , 100 );
nnc_vector_add_nnc( vector , 200 );
nnc_vector_add_nnc( vector , 300 );
{
const int_vector_type * index_list = nnc_vector_get_index_list( vector );

View File

@ -2,6 +2,9 @@ add_executable( ecl_coarse_test ecl_coarse_test.c )
target_link_libraries( ecl_coarse_test ecl test_util )
add_test( ecl_coarse_test ${EXECUTABLE_OUTPUT_PATH}/ecl_coarse_test ${PROJECT_SOURCE_DIR}/test-data/Statoil/ECLIPSE/LGCcase/LGC_TESTCASE2 )
add_executable( ecl_nnc_amalgamated ecl_nnc_amalgamated.c )
target_link_libraries( ecl_nnc_amalgamated ecl test_util )
add_test( ecl_nnc_amalgamated ${EXECUTABLE_OUTPUT_PATH}/ecl_nnc_amalgamated ${PROJECT_SOURCE_DIR}/test-data/Statoil/ECLIPSE/nestedLGRcase/TESTCASE_NESTEDLGR.EGRID )
add_executable( ecl_restart_test ecl_restart_test.c )
target_link_libraries( ecl_restart_test ecl test_util )
@ -61,6 +64,14 @@ target_link_libraries( ecl_nnc_info_test ecl test_util )
add_test (ecl_nnc_info_test ${EXECUTABLE_OUTPUT_PATH}/ecl_nnc_info_test )
add_executable( ecl_nnc_vector ecl_nnc_vector.c )
target_link_libraries( ecl_nnc_vector ecl test_util )
add_test(ecl_nnc_vector ${EXECUTABLE_OUTPUT_PATH}/ecl_nnc_vector )
add_executable( ecl_nnc_index_list ecl_nnc_index_list.c )
target_link_libraries( ecl_nnc_index_list ecl test_util )
add_test (ecl_nnc_index_list ${EXECUTABLE_OUTPUT_PATH}/ecl_nnc_index_list )
add_executable( ecl_kw_grdecl ecl_kw_grdecl.c )
target_link_libraries( ecl_kw_grdecl ecl test_util )
add_test( ecl_kw_grdecl ${EXECUTABLE_OUTPUT_PATH}/ecl_kw_grdecl )
@ -173,3 +184,4 @@ set_property( TEST ecl_region2region PROPERTY LABELS StatoilData)
set_property( TEST ecl_grid_case PROPERTY LABELS StatoilData)
set_property( TEST ecl_rft_rft PROPERTY LABELS StatoilData)
set_property( TEST ecl_rft_plt PROPERTY LABELS StatoilData)
set_property( TEST ecl_nnc_amalgamated PROPERTY LABELS StatoilData)

View File

@ -24,6 +24,7 @@
#include <time.h>
#include <ert/util/double_vector.h>
#include <ert/util/int_vector.h>
#include <ert/util/util.h>
#include <ert/util/menu.h>
#include <ert/util/arg_pack.h>
@ -31,6 +32,7 @@
#include <ert/util/bool_vector.h>
#include <ert/util/msg.h>
#include <ert/util/vector.h>
#include <ert/util/type_vector_functions.h>
#include <ert/plot/plot.h>
#include <ert/plot/plot_dataset.h>
@ -62,12 +64,18 @@ void enkf_tui_QC_plot_get_PC( enkf_main_type * enkf_main , int step1 , int step2
double truncation , int ncomp ,
matrix_type * PC , matrix_type * PC_obs) {
int ens_size = enkf_main_get_ensemble_size( enkf_main );
bool_vector_type * ens_mask = bool_vector_alloc(0 , false);
obs_data_type * obs_data = obs_data_alloc();
meas_data_type * meas_data = meas_data_alloc( ens_size );
analysis_config_type * analysis_config = enkf_main_get_analysis_config( enkf_main );
int_vector_type * step_list = int_vector_alloc(0,0);
enkf_fs_type * source_fs = enkf_main_get_fs( enkf_main);
state_map_type * state_map = enkf_fs_get_state_map(source_fs);
int_vector_type * ens_active_list;
meas_data_type * meas_data;
state_map_select_matching(state_map , ens_mask , STATE_HAS_DATA);
ens_active_list = bool_vector_alloc_active_list(ens_mask);
meas_data = meas_data_alloc(ens_active_list);
{
for (int step =step1; step <= step2; step++)
int_vector_append( step_list , step );
@ -81,10 +89,10 @@ void enkf_tui_QC_plot_get_PC( enkf_main_type * enkf_main , int step1 , int step2
double alpha = analysis_config_get_alpha( analysis_config );
enkf_obs_get_obs_and_measure(enkf_main_get_obs( enkf_main ),
enkf_main_get_fs( enkf_main ),
source_fs ,
step_list ,
state,
ens_size,
ens_active_list ,
(const enkf_state_type **) enkf_main_get_ensemble( enkf_main ),
meas_data ,
obs_data ,
@ -105,6 +113,7 @@ void enkf_tui_QC_plot_get_PC( enkf_main_type * enkf_main , int step1 , int step2
matrix_free( dObs );
}
bool_vector_free(ens_mask);
int_vector_free( step_list );
obs_data_free( obs_data );
meas_data_free( meas_data );

View File

@ -35,8 +35,6 @@
#include <ert/enkf/ensemble_config.h>
#include <ert/enkf/enkf_analysis.h>
#include <ert/enkf/ecl_config.h>
#include <ert/enkf/analysis_config.h>
#include <ert/enkf/analysis_iter_config.h>
#include <enkf_tui_util.h>
#include <enkf_tui_fs.h>
@ -116,76 +114,29 @@ void enkf_tui_run_smoother(void * arg) {
void enkf_tui_run_iterated_ES(void * enkf_main) {
const int ens_size = enkf_main_get_ensemble_size( enkf_main );
void enkf_tui_run_iterated_ES(void * arg) {
enkf_main_type * enkf_main = enkf_main_safe_cast( arg );
const ecl_config_type * ecl_config = enkf_main_get_ecl_config( enkf_main );
const int last_report = enkf_main_get_history_length( enkf_main );
{
model_config_type * model_config = enkf_main_get_model_config( enkf_main );
const ecl_config_type * ecl_config = enkf_main_get_ecl_config( enkf_main );
const analysis_config_type * analysis_config = enkf_main_get_analysis_config( enkf_main );
analysis_iter_config_type * iter_config = analysis_config_get_iter_config( analysis_config );
int step1 = 0;
int step2 ;
int_vector_type * step_list = int_vector_alloc(0,0);
bool_vector_type * iactive = bool_vector_alloc(0 , true);
int iter = 0;
int num_iter = analysis_iter_config_get_num_iterations( iter_config );
stringlist_type * node_list = ensemble_config_alloc_keylist_from_var_type( enkf_main_get_ensemble_config(enkf_main) , PARAMETER );
if (ecl_config_has_schedule( ecl_config ))
step2 = util_scanf_int_with_limits("Last report",PROMPT_LEN , 0 , last_report);
else
step2 = last_report;
{
for (int step=step1; step <= step2; step++)
int_vector_append( step_list , step );
}
bool_vector_iset( iactive , ens_size - 1 , true );
while (true) {
{
const char * runpath_fmt = analysis_iter_config_iget_runpath_fmt( iter_config , iter);
if (runpath_fmt != NULL) {
char * runpath_key = util_alloc_sprintf( "runpath-%d" , iter);
model_config_add_runpath( model_config , runpath_key , runpath_fmt);
model_config_select_runpath( model_config , runpath_key );
free( runpath_key );
}
}
enkf_main_run_exp(enkf_main , iactive , true , step1 , step1 , FORECAST);
{
const char * target_fs_name = analysis_iter_config_iget_case( iter_config , iter );
enkf_fs_type * target_fs = enkf_main_get_alt_fs(enkf_main , target_fs_name , false , true );
enkf_main_smoother_update(enkf_main , step_list , target_fs);
enkf_main_copy_ensemble( enkf_main ,
enkf_main_get_current_fs( enkf_main ),
0 , // Smoother update will write on step 0
ANALYZED ,
target_fs_name ,
step1 ,
FORECAST ,
iactive ,
NULL ,
node_list );
enkf_main_set_fs(enkf_main , target_fs , enkf_fs_get_case_name( target_fs ));
}
//iter = analysis_module_get_int(module, "ITER");
iter++;
if (iter == num_iter)
break;
}
int_vector_free( step_list );
bool_vector_free( iactive );
}
int step2;
if (ecl_config_has_schedule( ecl_config ))
step2 = util_scanf_int_with_limits("Last report",PROMPT_LEN , 0 , last_report);
else
step2 = last_report;
enkf_main_run_iterated_ES(enkf_main, step2);
}
void enkf_tui_run_one_more_iteration(void * arg){
enkf_main_type * enkf_main = enkf_main_safe_cast( arg );
const ecl_config_type * ecl_config = enkf_main_get_ecl_config( enkf_main );
const int last_report = enkf_main_get_history_length( enkf_main );
int step2;
if (ecl_config_has_schedule( ecl_config ))
step2 = util_scanf_int_with_limits("Last report",PROMPT_LEN , 0 , last_report);
else
step2 = last_report;
enkf_main_run_one_more_iteration(enkf_main, step2);
}
@ -221,7 +172,7 @@ void enkf_tui_run_exp(void * enkf_main) {
free( prompt );
}
if (bool_vector_count_equal(iactive , true))
enkf_main_run_exp(enkf_main , iactive , true , init_step_parameters , start_report , init_state);
enkf_main_run_exp(enkf_main , iactive , true , init_step_parameters , start_report , init_state, true);
bool_vector_free(iactive);
}
@ -247,7 +198,7 @@ void enkf_tui_run_create_runpath__(void * __enkf_main) {
util_safe_free( select_string );
free( prompt );
}
enkf_main_run_exp(enkf_main , iactive , false , init_step_parameters , start_report , init_state);
enkf_main_run_exp(enkf_main , iactive , false , init_step_parameters , start_report , init_state, true);
bool_vector_free(iactive);
}
@ -372,11 +323,15 @@ void enkf_tui_run_menu(void * arg) {
menu_item_type * restart_enkf_item = menu_add_item(menu , "Restart EnKF run from arbitrary state" , "rR" , enkf_tui_run_restart__ , enkf_main , NULL);
menu_item_type * ES_item = menu_add_item(menu , "Integrated smoother update" , "iI" , enkf_tui_run_smoother , enkf_main , NULL);
menu_item_type * it_ES_item = menu_add_item(menu , "Iterated smoother [RML-EnKF]" , "tT" , enkf_tui_run_iterated_ES , enkf_main , NULL);
menu_item_type * one_more_item = menu_add_item(menu , "One more iteration" , "mM" , enkf_tui_run_one_more_iteration , enkf_main , NULL);
if (!ecl_config_has_schedule( ecl_config )) {
menu_item_disable( enkf_item );
menu_item_disable( restart_enkf_item );
}
if (!ecl_config_has_init_section( ecl_config ))
menu_item_disable( enkf_item );
if (!model_config_has_history( model_config )) {
menu_item_disable( it_ES_item );

View File

@ -49,7 +49,7 @@ void analysis_config_reload_module( analysis_config_type * con
stringlist_type * analysis_config_alloc_module_names( analysis_config_type * config );
const char * analysis_config_get_log_path( const analysis_config_type * config );
void analysis_config_init( analysis_config_type * analysis , const config_type * config);
analysis_config_type * analysis_config_alloc_default( rng_type * rng );
analysis_config_type * analysis_config_alloc( rng_type * rng );
void analysis_config_free( analysis_config_type * );
bool analysis_config_get_merge_observations(const analysis_config_type * );
double analysis_config_get_alpha(const analysis_config_type * config);
@ -96,6 +96,12 @@ void analysis_config_set_PC_filename( analysis_config_type * c
const char * analysis_config_get_PC_filename( const analysis_config_type * config );
void analysis_config_set_PC_path( analysis_config_type * config , const char * path );
const char * analysis_config_get_PC_path( const analysis_config_type * config );
void analysis_config_set_min_realisations( analysis_config_type * config , int min_realisations);
int analysis_config_get_min_realisations( const analysis_config_type * config );
bool analysis_config_have_enough_realisations( const analysis_config_type * config , int realisations);
UTIL_IS_INSTANCE_HEADER( analysis_config );
#ifdef __cplusplus
}

View File

@ -28,6 +28,8 @@ typedef struct analysis_iter_config_struct analysis_iter_config_type;
void analysis_iter_config_set_num_iterations( analysis_iter_config_type * config , int num_iterations);
int analysis_iter_config_get_num_iterations( const analysis_iter_config_type * config );
void analysis_iter_config_set_case_fmt( analysis_iter_config_type * config, const char * case_fmt);
char * analysis_iter_config_get_case_fmt( analysis_iter_config_type * config);
analysis_iter_config_type * analysis_iter_config_alloc();
void analysis_iter_config_free( analysis_iter_config_type * config );
const char * analysis_iter_config_iget_case( analysis_iter_config_type * config , int iter);

View File

@ -0,0 +1,39 @@
/*
Copyright (C) 2013 Statoil ASA, Norway.
The file 'cases_config.h' is part of ERT - Ensemble based Reservoir Tool.
ERT 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.
ERT 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.
*/
#ifndef __CASES_CONFIG_H__
#define __CASES_CONFIG_H__
#ifdef __cplusplus
extern "C" {
#endif
typedef struct cases_config_struct cases_config_type;
bool cases_config_set_int( cases_config_type * config , const char * var_name, int num_iterations);
int cases_config_get_iteration_number( const cases_config_type * config );
void cases_config_fwrite( cases_config_type * config , const char * filename );
void cases_config_fread( cases_config_type * config , const char * filename);
cases_config_type * cases_config_alloc();
void cases_config_free( cases_config_type * config );
#ifdef __cplusplus
}
#endif
#endif

View File

@ -112,6 +112,7 @@ extern "C" {
#define MAX_RUNNING_RSH_KEY "MAX_RUNNING_RSH"
#define MAX_SUBMIT_KEY "MAX_SUBMIT"
#define NUM_REALIZATIONS_KEY "NUM_REALIZATIONS"
#define MIN_REALIZATIONS_KEY "MIN_REALIZATIONS"
#define OBS_CONFIG_KEY "OBS_CONFIG"
#define OBS_CONFIG_KEY "OBS_CONFIG"
#define PLOT_DRIVER_KEY "PLOT_DRIVER"

View File

@ -83,6 +83,7 @@ extern "C" {
void ecl_config_fprintf_config( const ecl_config_type * ecl_config , FILE * stream );
ecl_config_type * ecl_config_alloc_empty( );
void ecl_config_add_config_items( config_type * config );
bool ecl_config_has_init_section( const ecl_config_type * ecl_config );
#ifdef __cplusplus
}

View File

@ -116,7 +116,10 @@
#define DEFAULT_UPDATE_RESULTS false
#define DEFAULT_SINGLE_NODE_UPDATE true
#define DEFAULT_ANALYSIS_MODULE "STD_ENKF"
#define DEFAULT_ANALYSIS_NUM_ITERATIONS 1
#define DEFAULT_ANALYSIS_NUM_ITERATIONS 4
#define DEFAULT_ANALYSIS_ITER_CASE "ITERATED_ENSEMBLE_SMOOTHER%d"
#define DEFAULT_ANALYSIS_ITER_RUNPATH "Simulations/Real%d"
#define DEFAULT_ANALYSIS_MIN_REALISATIONS 0 // 0: No lower limit
/* Default directories. */
#define DEFAULT_QC_PATH "QC"

View File

@ -34,6 +34,8 @@ extern "C" {
#include <ert/enkf/fs_types.h>
#include <ert/enkf/enkf_fs_type.h>
#include <ert/enkf/time_map.h>
#include <ert/enkf/cases_config.h>
#include <ert/enkf/state_map.h>
#include <ert/enkf/misfit_ensemble_typedef.h>
const char * enkf_fs_get_mount_point( const enkf_fs_type * fs );
@ -92,8 +94,10 @@ extern "C" {
FILE * enkf_fs_open_excase_file( const enkf_fs_type * fs , const char * input_name);
FILE * enkf_fs_open_excase_tstep_file( const enkf_fs_type * fs , const char * input_name , int tstep );
FILE * enkf_fs_open_excase_member_file( const enkf_fs_type * fs , const char * input_name , int iens );
state_map_type * enkf_fs_get_state_map( const enkf_fs_type * fs );
time_map_type * enkf_fs_get_time_map( const enkf_fs_type * fs );
cases_config_type * enkf_fs_get_cases_config( const enkf_fs_type * fs);
misfit_ensemble_type * enkf_fs_get_misfit_ensemble( const enkf_fs_type * fs );
UTIL_SAFE_CAST_HEADER( enkf_fs );

View File

@ -110,24 +110,26 @@ extern "C" {
void enkf_main_iload_ecl_mt(enkf_main_type *enkf_main , int );
void enkf_main_assimilation_update(enkf_main_type * enkf_main , const int_vector_type * step_list);
void enkf_main_smoother_update(enkf_main_type * enkf_main , const int_vector_type * step_list , enkf_fs_type * target_fs);
bool enkf_main_smoother_update(enkf_main_type * enkf_main , const int_vector_type * step_list , enkf_fs_type * target_fs);
void enkf_main_run_exp(enkf_main_type * enkf_main ,
const bool_vector_type * iactive ,
bool_vector_type * iactive ,
bool simulate ,
int init_step_parameters ,
int start_report ,
state_enum start_state);
state_enum start_state ,
bool initialize);
void enkf_main_run_assimilation(enkf_main_type * enkf_main ,
const bool_vector_type * iactive ,
bool_vector_type * iactive ,
int init_step_parameters ,
int start_report ,
state_enum start_state);
void enkf_main_run_smoother(enkf_main_type * enkf_main , const char * target_fs_name , bool rerun);
void enkf_main_run_smoother(enkf_main_type * enkf_main , const char * target_fs_name , bool rerun);
void enkf_main_run_iterated_ES(enkf_main_type * enkf_main, int last_report);
void enkf_main_run_one_more_iteration(enkf_main_type * enkf_main, int step2);
void enkf_main_set_data_kw(enkf_main_type * , const char * , const char *);
void enkf_main_set_state_run_path(const enkf_main_type * , int );
void enkf_main_set_state_eclbase(const enkf_main_type * , int );

View File

@ -25,6 +25,7 @@ extern "C" {
#include <ert/util/hash.h>
#include <ert/util/stringlist.h>
#include <ert/util/int_vector.h>
#include <ert/sched/history.h>
@ -63,7 +64,7 @@ extern "C" {
enkf_fs_type * fs,
const int_vector_type * step_list ,
state_enum state,
int ens_size,
const int_vector_type * ens_active_list,
const enkf_state_type ** ensemble ,
meas_data_type * meas_data,
obs_data_type * obs_data,

View File

@ -80,15 +80,15 @@ typedef struct enkf_state_struct enkf_state_type;
void * enkf_state_run_eclipse__(void * );
void * enkf_state_start_forward_model__(void * );
void enkf_state_load_from_forward_model(enkf_state_type * enkf_state ,
void enkf_state_load_from_forward_model(enkf_state_type * enkf_state ,
enkf_fs_type * fs ,
bool * loadOK ,
int * result ,
bool interactive ,
stringlist_type * msg_list);
void enkf_state_forward_init(enkf_state_type * enkf_state ,
enkf_fs_type * fs ,
bool * loadOK );
int * result );
enkf_state_type * enkf_state_alloc(int ,
rng_type * main_rng ,
@ -125,7 +125,7 @@ typedef struct enkf_state_struct enkf_state_type;
rng_type * enkf_state_get_rng( const enkf_state_type * enkf_state );
unsigned int enkf_state_get_random( enkf_state_type * enkf_state );
/*****************************************************************/
void enkf_state_set_inactive(enkf_state_type * state);

View File

@ -21,7 +21,7 @@
#ifdef __cplusplus
extern "C" {
#endif
#include <ert/util/arg_pack.h>
@ -125,6 +125,13 @@ typedef enum {UNDEFINED = 0 ,
{.value = 6 , .name = "BOTH"}
#define ENKF_STATE_ENUM_SIZE 4
typedef enum { REPORT_STEP_INCOMPATIBLE = 1,
LOAD_FAILURE = 2 } enkf_fw_load_result_enum;
@ -228,6 +235,15 @@ typedef enum {
/*****************************************************************/
/* Possible transitions: */
typedef enum {
STATE_UNDEFINED = 1,
STATE_INITIALIZED = 2,
STATE_HAS_DATA = 4,
STATE_LOAD_FAILURE = 8,
STATE_PARENT_FAILURE = 16
} realisation_state_enum;
typedef struct enkf_obs_struct enkf_obs_type;

View File

@ -27,10 +27,14 @@ extern "C" {
#include <ert/util/matrix.h>
#include <ert/util/hash.h>
#include <ert/util/int_vector.h>
#include <ert/util/type_macros.h>
typedef struct meas_data_struct meas_data_type;
typedef struct meas_block_struct meas_block_type;
UTIL_IS_INSTANCE_HEADER( meas_data );
void meas_block_iset( meas_block_type * meas_block , int iens , int iobs , double value);
double meas_block_iget_ens_mean( const meas_block_type * meas_block , int iobs );
double meas_block_iget_ens_std( const meas_block_type * meas_block , int iobs);
@ -38,8 +42,8 @@ void meas_block_deactivate( meas_block_type * meas_block , int iob
void meas_data_fprintf( const meas_data_type * matrix , FILE * stream);
void meas_data_reset(meas_data_type * );
meas_data_type * meas_data_alloc( int );
void meas_data_reset(meas_data_type * );
meas_data_type * meas_data_alloc( const int_vector_type * ens_active_list );
void meas_data_free(meas_data_type * );
void meas_data_add(meas_data_type * , int , double );
matrix_type * meas_data_allocS(const meas_data_type * matrix , int active_size);
@ -56,7 +60,6 @@ void meas_block_calculate_ens_stats( meas_block_type * meas_block
int meas_block_get_total_size( const meas_block_type * meas_block );
bool meas_block_iget_active( const meas_block_type * meas_block , int iobs);
void meas_data_assign_vector(meas_data_type * target_matrix, const meas_data_type * src_matrix , int target_index , int src_index);
meas_data_type * meas_data_alloc_copy( const meas_data_type * src );
#ifdef __cplusplus
}

View File

@ -26,6 +26,7 @@ extern "C" {
#include <time.h>
#include <ert/util/path_fmt.h>
#include <ert/util/type_macros.h>
#include <ert/config/config.h>
@ -55,6 +56,7 @@ extern "C" {
const char * model_config_get_enspath( const model_config_type * model_config);
const char * model_config_get_rftpath( const model_config_type * model_config);
fs_driver_impl model_config_get_dbase_type(const model_config_type * model_config );
const ecl_sum_type * model_config_get_refcase( const model_config_type * model_config );
void model_config_init_internalization( model_config_type * );
void model_config_set_internalize_state( model_config_type * , int );
void model_config_set_load_state( model_config_type * , int );
@ -82,8 +84,11 @@ extern "C" {
history_source_type model_config_get_history_source( const model_config_type * model_config );
void model_config_set_refcase( model_config_type * model_config , const ecl_sum_type * refcase );
void model_config_fprintf_config( const model_config_type * model_config , int ens_size ,FILE * stream );
model_config_type * model_config_alloc_empty();
model_config_type * model_config_alloc();
bool model_config_select_history( model_config_type * model_config , history_source_type source_type, const sched_file_type * sched_file , const ecl_sum_type * refcase);
void model_config_set_runpath(model_config_type * model_config , const char * fmt);
UTIL_IS_INSTANCE_HEADER( model_config);
#ifdef __cplusplus
}

Some files were not shown because too many files have changed in this diff Show More