#4683 clang-format on all files in ApplicationCode

This commit is contained in:
Magne Sjaastad
2019-09-06 10:40:57 +02:00
parent 3a317504bb
commit fe9e567825
2092 changed files with 117952 additions and 111846 deletions

View File

@@ -48,91 +48,105 @@
#include <QString>
#include <QStringList>
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool RiaArgumentParser::parseArguments(cvf::ProgramOptions* progOpt)
bool RiaArgumentParser::parseArguments( cvf::ProgramOptions* progOpt )
{
CVF_ASSERT(progOpt);
progOpt->registerOption("help", "", "Displays help text and exits.");
progOpt->registerOption("?", "", "Displays help text and exits.");
CVF_ASSERT( progOpt );
progOpt->registerOption( "help", "", "Displays help text and exits." );
progOpt->registerOption( "?", "", "Displays help text and exits." );
progOpt->registerOption("project", "<filename>", "Open project file <filename>.", cvf::ProgramOptions::SINGLE_VALUE);
progOpt->registerOption("last", "", "Open last used project.");
progOpt->registerOption("case",
"<casename|filename> [<casename|filename> ...]",
"Imports the Eclipse cases specified by case name with or without extension."
"If <casename>, import the corresponding grid file and summary file"
"If <filename> has extension .GRRID/.EGRID, import the grid file and corresponding summary file"
"If <filename> has extension .SMSPEC, import the summary file (does not open the corresponding grid file)",
cvf::ProgramOptions::MULTI_VALUE);
progOpt->registerOption("size", "<width> <height>", "Set size of the main application window.", cvf::ProgramOptions::MULTI_VALUE);
progOpt->registerOption("console", "", "Launch as a console application without graphics");
progOpt->registerOption("server", "[<portnumber>]", "Launch as a GRPC server. Default port is 50051", cvf::ProgramOptions::SINGLE_VALUE);
progOpt->registerOption("startdir", "<folder>", "Set startup directory.\n", cvf::ProgramOptions::SINGLE_VALUE);
progOpt->registerOption( "project", "<filename>", "Open project file <filename>.", cvf::ProgramOptions::SINGLE_VALUE );
progOpt->registerOption( "last", "", "Open last used project." );
progOpt->registerOption( "case",
"<casename|filename> [<casename|filename> ...]",
"Imports the Eclipse cases specified by case name with or without extension."
"If <casename>, import the corresponding grid file and summary file"
"If <filename> has extension .GRRID/.EGRID, import the grid file and corresponding "
"summary file"
"If <filename> has extension .SMSPEC, import the summary file (does not open the "
"corresponding grid file)",
cvf::ProgramOptions::MULTI_VALUE );
progOpt->registerOption( "size",
"<width> <height>",
"Set size of the main application window.",
cvf::ProgramOptions::MULTI_VALUE );
progOpt->registerOption( "console", "", "Launch as a console application without graphics" );
progOpt->registerOption( "server",
"[<portnumber>]",
"Launch as a GRPC server. Default port is 50051",
cvf::ProgramOptions::SINGLE_VALUE );
progOpt->registerOption( "startdir", "<folder>", "Set startup directory.\n", cvf::ProgramOptions::SINGLE_VALUE );
progOpt->registerOption("summaryplot",
"[<plotOptions>] <eclipsesummaryvectors> [<eclipsedatafiles>]",
"Creates a summary plot using all the <eclipsedatafiles>,"
"and all the summary vectors defined in <eclipsesummaryvectors>."
"Use --summaryplot -help to show a more detailed help text.\n",
cvf::ProgramOptions::OPTIONAL_MULTI_VALUE);
progOpt->registerOption( "summaryplot",
"[<plotOptions>] <eclipsesummaryvectors> [<eclipsedatafiles>]",
"Creates a summary plot using all the <eclipsedatafiles>,"
"and all the summary vectors defined in <eclipsesummaryvectors>."
"Use --summaryplot -help to show a more detailed help text.\n",
cvf::ProgramOptions::OPTIONAL_MULTI_VALUE );
progOpt->registerOption("commandFile", "<commandfile>", "Execute the command file.", cvf::ProgramOptions::SINGLE_VALUE);
progOpt->registerOption("commandFileReplaceCases",
"[<caseId>] <caseListFile>",
"Supply list of cases to replace in project, performing command file for each case.",
cvf::ProgramOptions::SINGLE_VALUE);
progOpt->registerOption("commandFileProject",
"<filename>",
"Project to use if performing case looping for command file. Used in conjunction with 'commandFileReplaceCases'.\n",
cvf::ProgramOptions::SINGLE_VALUE);
progOpt->registerOption( "commandFile",
"<commandfile>",
"Execute the command file.",
cvf::ProgramOptions::SINGLE_VALUE );
progOpt->registerOption( "commandFileReplaceCases",
"[<caseId>] <caseListFile>",
"Supply list of cases to replace in project, performing command file for each case.",
cvf::ProgramOptions::SINGLE_VALUE );
progOpt->registerOption( "commandFileProject",
"<filename>",
"Project to use if performing case looping for command file. Used in conjunction with "
"'commandFileReplaceCases'.\n",
cvf::ProgramOptions::SINGLE_VALUE );
progOpt->registerOption("savesnapshots",
"all|views|plots",
"Save snapshot of all views or plots to project file location sub folder 'snapshots'. Option 'all' "
"will include both views and plots. Application closes after snapshots have been written.",
cvf::ProgramOptions::OPTIONAL_MULTI_VALUE);
progOpt->registerOption("multiCaseSnapshots",
"<gridListFile>",
"For each grid file listed in the <gridListFile> file, replace the first case in the project and save "
"snapshots of all views.\n",
cvf::ProgramOptions::SINGLE_VALUE);
progOpt->registerOption( "savesnapshots",
"all|views|plots",
"Save snapshot of all views or plots to project file location sub folder 'snapshots'. "
"Option 'all' "
"will include both views and plots. Application closes after snapshots have been written.",
cvf::ProgramOptions::OPTIONAL_MULTI_VALUE );
progOpt->registerOption( "multiCaseSnapshots",
"<gridListFile>",
"For each grid file listed in the <gridListFile> file, replace the first case in the "
"project and save "
"snapshots of all views.\n",
cvf::ProgramOptions::SINGLE_VALUE );
progOpt->registerOption("replaceCase",
"[<caseId>] <newGridFile>",
"Replace grid in <caseId> or first case with <newgridFile>. Repeat parameter for multiple replace operations.",
cvf::ProgramOptions::MULTI_VALUE,
cvf::ProgramOptions::COMBINE_REPEATED);
progOpt->registerOption("replaceSourceCases",
"[<caseGroupId>] <gridListFile>",
"Replace source cases in <caseGroupId> or first grid case group with the grid files listed in the "
"<gridListFile> file. Repeat parameter for multiple replace operations.",
cvf::ProgramOptions::MULTI_VALUE,
cvf::ProgramOptions::COMBINE_REPEATED);
progOpt->registerOption("replacePropertiesFolder",
"[<caseId>] <newPropertiesFolder>",
"Replace the folder containing property files for an eclipse input case.\n",
cvf::ProgramOptions::MULTI_VALUE);
progOpt->registerOption( "replaceCase",
"[<caseId>] <newGridFile>",
"Replace grid in <caseId> or first case with <newgridFile>. Repeat parameter for multiple "
"replace operations.",
cvf::ProgramOptions::MULTI_VALUE,
cvf::ProgramOptions::COMBINE_REPEATED );
progOpt->registerOption( "replaceSourceCases",
"[<caseGroupId>] <gridListFile>",
"Replace source cases in <caseGroupId> or first grid case group with the grid files "
"listed in the "
"<gridListFile> file. Repeat parameter for multiple replace operations.",
cvf::ProgramOptions::MULTI_VALUE,
cvf::ProgramOptions::COMBINE_REPEATED );
progOpt->registerOption( "replacePropertiesFolder",
"[<caseId>] <newPropertiesFolder>",
"Replace the folder containing property files for an eclipse input case.\n",
cvf::ProgramOptions::MULTI_VALUE );
progOpt->registerOption("updateregressiontestbase", "<folder>", "System command", cvf::ProgramOptions::SINGLE_VALUE);
progOpt->registerOption("regressiontest", "<folder>", "System command", cvf::ProgramOptions::SINGLE_VALUE);
progOpt->registerOption( "updateregressiontestbase", "<folder>", "System command", cvf::ProgramOptions::SINGLE_VALUE );
progOpt->registerOption( "regressiontest", "<folder>", "System command", cvf::ProgramOptions::SINGLE_VALUE );
#ifdef USE_UNIT_TESTS
progOpt->registerOption("unittest", "", "System command");
progOpt->registerOption( "unittest", "", "System command" );
#endif
progOpt->registerOption("ignoreArgs", "", "System command. Ignore all arguments. Mostly for testing purposes");
progOpt->registerOption( "ignoreArgs", "", "System command. Ignore all arguments. Mostly for testing purposes" );
progOpt->setOptionPrefix(cvf::ProgramOptions::DOUBLE_DASH);
progOpt->setOptionPrefix( cvf::ProgramOptions::DOUBLE_DASH );
QStringList arguments = QCoreApplication::arguments();
bool parseOk = progOpt->parse(cvfqt::Utils::toStringVector(arguments));
// If positional parameter functionality is to be supported, the test for existence of positionalParameters must be removed
// This is based on a pull request by @andlaus https://github.com/OPM/ResInsight/pull/162
if (!parseOk || !progOpt->positionalParameters().empty())
bool parseOk = progOpt->parse( cvfqt::Utils::toStringVector( arguments ) );
// If positional parameter functionality is to be supported, the test for existence of positionalParameters must be
// removed This is based on a pull request by @andlaus https://github.com/OPM/ResInsight/pull/162
if ( !parseOk || !progOpt->positionalParameters().empty() )
{
return false;
}

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017 Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE.
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -26,12 +26,11 @@ class ProgramOptions;
}
//==================================================================================================
//
//
//
//
//==================================================================================================
class RiaArgumentParser
{
public:
static bool parseArguments(cvf::ProgramOptions* progOpt);
static bool parseArguments( cvf::ProgramOptions* progOpt );
};

View File

@@ -3,17 +3,17 @@
// Copyright (C) 2011- Statoil ASA
// Copyright (C) 2013- Ceetron Solutions AS
// Copyright (C) 2011-2012 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>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -23,12 +23,12 @@
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
cvf::BoundingBox RiaBoundingBoxTools::inflate(const cvf::BoundingBox& boundingBox, double factor)
cvf::BoundingBox RiaBoundingBoxTools::inflate( const cvf::BoundingBox& boundingBox, double factor )
{
cvf::Vec3d center = boundingBox.center();
cvf::Vec3d sizes = boundingBox.extent() * factor;
cvf::Vec3d sizes = boundingBox.extent() * factor;
cvf::Vec3d newMin(center.x() - sizes.x() / 2.0, center.y() - sizes.y() / 2.0, center.z() - sizes.z() / 2.0);
cvf::Vec3d newMax(center.x() + sizes.x() / 2.0, center.y() + sizes.y() / 2.0, center.z() + sizes.z() / 2.0);
return cvf::BoundingBox(newMin, newMax);
cvf::Vec3d newMin( center.x() - sizes.x() / 2.0, center.y() - sizes.y() / 2.0, center.z() - sizes.z() / 2.0 );
cvf::Vec3d newMax( center.x() + sizes.x() / 2.0, center.y() + sizes.y() / 2.0, center.z() + sizes.z() / 2.0 );
return cvf::BoundingBox( newMin, newMax );
}

View File

@@ -3,17 +3,17 @@
// Copyright (C) 2011- Statoil ASA
// Copyright (C) 2013- Ceetron Solutions AS
// Copyright (C) 2011-2012 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>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -25,11 +25,11 @@
//==================================================================================================
//
//
//
//
//==================================================================================================
class RiaBoundingBoxTools
{
public:
static cvf::BoundingBox inflate(const cvf::BoundingBox& boundingBox, double factor);
static cvf::BoundingBox inflate( const cvf::BoundingBox& boundingBox, double factor );
};

View File

@@ -30,7 +30,7 @@
//--------------------------------------------------------------------------------------------------
/// Splits a line in a number of equal parts
//--------------------------------------------------------------------------------------------------
std::vector<cvf::Vec3d> splitLine(cvf::Vec3d ptStart, cvf::Vec3d ptEnd, size_t partCount);
std::vector<cvf::Vec3d> splitLine( cvf::Vec3d ptStart, cvf::Vec3d ptEnd, size_t partCount );
//--------------------------------------------------------------------------------------------------
/// Calculates all points on a face described by edge points from all four edges.
@@ -45,71 +45,74 @@ std::vector<cvf::Vec3d> splitLine(cvf::Vec3d ptStart, cvf::Vec3d ptEnd, size_t p
/// edgeXPtsLow
///
//--------------------------------------------------------------------------------------------------
std::vector<std::vector<cvf::Vec3d>> calcFacePoints(const std::vector<cvf::Vec3d> edgeXPtsLow,
const std::vector<cvf::Vec3d> edgeXPtsHigh,
const std::vector<cvf::Vec3d> edgeYPtsLow,
const std::vector<cvf::Vec3d> edgeYPtsHigh);
std::vector<std::vector<cvf::Vec3d>> calcFacePoints( const std::vector<cvf::Vec3d> edgeXPtsLow,
const std::vector<cvf::Vec3d> edgeXPtsHigh,
const std::vector<cvf::Vec3d> edgeYPtsLow,
const std::vector<cvf::Vec3d> edgeYPtsHigh );
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
std::vector<cvf::Vec3d>
RiaCellDividingTools::createHexCornerCoords(std::array<cvf::Vec3d, 8> mainCellCorners, size_t nx, size_t ny, size_t nz)
std::vector<cvf::Vec3d> RiaCellDividingTools::createHexCornerCoords( std::array<cvf::Vec3d, 8> mainCellCorners,
size_t nx,
size_t ny,
size_t nz )
{
std::array<std::pair<size_t, size_t>, 12> edgeCorners = {
std::make_pair(0, 1),
std::make_pair(3, 2),
std::make_pair(4, 5),
std::make_pair(7, 6), // X
std::make_pair(0, 3),
std::make_pair(4, 7),
std::make_pair(1, 2),
std::make_pair(5, 6), // Y
std::make_pair(0, 4),
std::make_pair(1, 5),
std::make_pair(3, 7),
std::make_pair(2, 6), // Z
std::make_pair( 0, 1 ),
std::make_pair( 3, 2 ),
std::make_pair( 4, 5 ),
std::make_pair( 7, 6 ), // X
std::make_pair( 0, 3 ),
std::make_pair( 4, 7 ),
std::make_pair( 1, 2 ),
std::make_pair( 5, 6 ), // Y
std::make_pair( 0, 4 ),
std::make_pair( 1, 5 ),
std::make_pair( 3, 7 ),
std::make_pair( 2, 6 ), // Z
};
std::array<size_t, 3> nxyz = {nx, ny, nz};
std::array<std::vector<cvf::Vec3d>, 12> edgePoints;
for (int i = 0; i < 12; i++)
for ( int i = 0; i < 12; i++ )
{
int partCountsIndex = i / 4;
edgePoints[i] =
splitLine(mainCellCorners[edgeCorners[i].first], mainCellCorners[edgeCorners[i].second], nxyz[partCountsIndex]);
edgePoints[i] = splitLine( mainCellCorners[edgeCorners[i].first],
mainCellCorners[edgeCorners[i].second],
nxyz[partCountsIndex] );
}
// lowIJ, highIJ, lowJK, highKJ,
std::vector<std::vector<std::vector<cvf::Vec3d>>> nodes;
nodes.reserve((nx + 1) * (ny + 1) * (nz + 1));
nodes.reserve( ( nx + 1 ) * ( ny + 1 ) * ( nz + 1 ) );
auto xyFacePtsLow = calcFacePoints(edgePoints[0], edgePoints[1], edgePoints[4], edgePoints[6]);
auto xyFacePtsHigh = calcFacePoints(edgePoints[2], edgePoints[3], edgePoints[5], edgePoints[7]);
auto yzFacePtsLow = calcFacePoints(edgePoints[4], edgePoints[5], edgePoints[8], edgePoints[10]);
auto yzFacePtsHigh = calcFacePoints(edgePoints[6], edgePoints[7], edgePoints[9], edgePoints[11]);
auto xzFacePtsLow = calcFacePoints(edgePoints[0], edgePoints[2], edgePoints[8], edgePoints[9]);
auto xzFacePtsHigh = calcFacePoints(edgePoints[1], edgePoints[3], edgePoints[10], edgePoints[11]);
auto xyFacePtsLow = calcFacePoints( edgePoints[0], edgePoints[1], edgePoints[4], edgePoints[6] );
auto xyFacePtsHigh = calcFacePoints( edgePoints[2], edgePoints[3], edgePoints[5], edgePoints[7] );
auto yzFacePtsLow = calcFacePoints( edgePoints[4], edgePoints[5], edgePoints[8], edgePoints[10] );
auto yzFacePtsHigh = calcFacePoints( edgePoints[6], edgePoints[7], edgePoints[9], edgePoints[11] );
auto xzFacePtsLow = calcFacePoints( edgePoints[0], edgePoints[2], edgePoints[8], edgePoints[9] );
auto xzFacePtsHigh = calcFacePoints( edgePoints[1], edgePoints[3], edgePoints[10], edgePoints[11] );
nodes.push_back(xyFacePtsLow);
nodes.push_back( xyFacePtsLow );
for (size_t z = 1; z < nz; z++)
for ( size_t z = 1; z < nz; z++ )
{
auto xyFacePoints = calcFacePoints(xzFacePtsLow[z], xzFacePtsHigh[z], yzFacePtsLow[z], yzFacePtsHigh[z]);
nodes.push_back(xyFacePoints);
auto xyFacePoints = calcFacePoints( xzFacePtsLow[z], xzFacePtsHigh[z], yzFacePtsLow[z], yzFacePtsHigh[z] );
nodes.push_back( xyFacePoints );
}
nodes.push_back(xyFacePtsHigh);
nodes.push_back( xyFacePtsHigh );
std::vector<cvf::Vec3d> coords;
coords.reserve(nx * ny * nz * 8);
coords.reserve( nx * ny * nz * 8 );
for (size_t z = 1; z < nz + 1; z++)
for ( size_t z = 1; z < nz + 1; z++ )
{
for (size_t y = 1; y < ny + 1; y++)
for ( size_t y = 1; y < ny + 1; y++ )
{
for (size_t x = 1; x < nx + 1; x++)
for ( size_t x = 1; x < nx + 1; x++ )
{
std::array<cvf::Vec3d, 8> cs;
@@ -123,7 +126,7 @@ RiaCellDividingTools::createHexCornerCoords(std::array<cvf::Vec3d, 8> mainCellCo
cs[6] = nodes[z][y][x];
cs[7] = nodes[z][y][x - 1];
coords.insert(coords.end(), cs.begin(), cs.end());
coords.insert( coords.end(), cs.begin(), cs.end() );
}
}
}
@@ -133,15 +136,15 @@ RiaCellDividingTools::createHexCornerCoords(std::array<cvf::Vec3d, 8> mainCellCo
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
double RiaCellDividingTools::computeFlowDistance(const std::array<cvf::Vec3d, 8>& cellVertices,
const cvf::Vec3d& areaCenter)
double RiaCellDividingTools::computeFlowDistance( const std::array<cvf::Vec3d, 8>& cellVertices,
const cvf::Vec3d& areaCenter )
{
auto subCellCorners = createHexCornerCoords(cellVertices, 2, 2, 2);
auto subCellCorners = createHexCornerCoords( cellVertices, 2, 2, 2 );
double weightedDistanceTotal = 0.0;
double weightTotal = 0.0;
double weightTotal = 0.0;
for (size_t c = 0; c < 8; c++)
for ( size_t c = 0; c < 8; c++ )
{
double weight = 1.0;
weightTotal += weight;
@@ -149,12 +152,13 @@ double RiaCellDividingTools::computeFlowDistance(const std::array<cvf::Vec3d, 8>
cvf::Vec3d centerOfSubCell = cvf::Vec3d::ZERO;
{
cvf::Vec3d vertexSum = cvf::Vec3d::ZERO;
for (size_t v = 0; v < 8; v++) vertexSum += subCellCorners[c * 8 + v];
for ( size_t v = 0; v < 8; v++ )
vertexSum += subCellCorners[c * 8 + v];
centerOfSubCell = vertexSum / 8;
}
auto dist = (centerOfSubCell - areaCenter).length();
weightedDistanceTotal += (dist * weight);
auto dist = ( centerOfSubCell - areaCenter ).length();
weightedDistanceTotal += ( dist * weight );
}
return weightedDistanceTotal / weightTotal;
@@ -163,29 +167,29 @@ double RiaCellDividingTools::computeFlowDistance(const std::array<cvf::Vec3d, 8>
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
std::vector<cvf::Vec3d> splitLine(cvf::Vec3d ptStart, cvf::Vec3d ptEnd, size_t partCount)
std::vector<cvf::Vec3d> splitLine( cvf::Vec3d ptStart, cvf::Vec3d ptEnd, size_t partCount )
{
std::vector<cvf::Vec3d> pts = {ptStart};
for (size_t i = 1; i < partCount; i++)
for ( size_t i = 1; i < partCount; i++ )
{
pts.push_back(cvf::Vec3d(ptStart.x() + (ptEnd.x() - ptStart.x()) * i / partCount,
ptStart.y() + (ptEnd.y() - ptStart.y()) * i / partCount,
ptStart.z() + (ptEnd.z() - ptStart.z()) * i / partCount));
pts.push_back( cvf::Vec3d( ptStart.x() + ( ptEnd.x() - ptStart.x() ) * i / partCount,
ptStart.y() + ( ptEnd.y() - ptStart.y() ) * i / partCount,
ptStart.z() + ( ptEnd.z() - ptStart.z() ) * i / partCount ) );
}
pts.push_back(ptEnd);
pts.push_back( ptEnd );
return pts;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
std::vector<std::vector<cvf::Vec3d>> calcFacePoints(const std::vector<cvf::Vec3d> edgeXPtsLow,
const std::vector<cvf::Vec3d> edgeXPtsHigh,
const std::vector<cvf::Vec3d> edgeYPtsLow,
const std::vector<cvf::Vec3d> edgeYPtsHigh)
std::vector<std::vector<cvf::Vec3d>> calcFacePoints( const std::vector<cvf::Vec3d> edgeXPtsLow,
const std::vector<cvf::Vec3d> edgeXPtsHigh,
const std::vector<cvf::Vec3d> edgeYPtsLow,
const std::vector<cvf::Vec3d> edgeYPtsHigh )
{
CVF_ASSERT(edgeXPtsLow.size() == edgeXPtsHigh.size() && edgeYPtsLow.size() == edgeYPtsHigh.size());
CVF_ASSERT( edgeXPtsLow.size() == edgeXPtsHigh.size() && edgeYPtsLow.size() == edgeYPtsHigh.size() );
size_t xSize = edgeXPtsLow.size();
size_t ySize = edgeYPtsLow.size();
@@ -193,16 +197,16 @@ std::vector<std::vector<cvf::Vec3d>> calcFacePoints(const std::vector<cvf::Vec3d
std::vector<std::vector<cvf::Vec3d>> pts;
// Add low edge points
pts.push_back(edgeXPtsLow);
pts.push_back( edgeXPtsLow );
// Interior points
for (size_t y = 1; y < ySize - 1; y++)
for ( size_t y = 1; y < ySize - 1; y++ )
{
auto interiorPts = splitLine(edgeYPtsLow[y], edgeYPtsHigh[y], xSize - 1);
pts.push_back(interiorPts);
auto interiorPts = splitLine( edgeYPtsLow[y], edgeYPtsHigh[y], xSize - 1 );
pts.push_back( interiorPts );
}
// Add low edge points
pts.push_back(edgeXPtsHigh);
pts.push_back( edgeXPtsHigh );
return pts;
}

View File

@@ -21,8 +21,8 @@
#include <cvfBase.h>
#include <cvfVector3.h>
#include <vector>
#include <array>
#include <vector>
//--------------------------------------------------------------------------------------------------
///
@@ -31,7 +31,7 @@ class RiaCellDividingTools
{
public:
static std::vector<cvf::Vec3d>
createHexCornerCoords(std::array<cvf::Vec3d, 8> mainCellCorners, size_t nx, size_t ny, size_t nz);
createHexCornerCoords( std::array<cvf::Vec3d, 8> mainCellCorners, size_t nx, size_t ny, size_t nz );
static double computeFlowDistance(const std::array<cvf::Vec3d, 8>& cellVertices, const cvf::Vec3d& areaCenter);
static double computeFlowDistance( const std::array<cvf::Vec3d, 8>& cellVertices, const cvf::Vec3d& areaCenter );
};

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017 Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE.
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -23,145 +23,120 @@
#include <QColor>
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::normalPaletteColors()
{
static std::vector<cvf::Color3ub> colors {
cvf::Color3ub( 0, 0, 255),
cvf::Color3ub( 0, 127, 255),
cvf::Color3ub( 0, 255, 255),
cvf::Color3ub( 0, 255, 0),
cvf::Color3ub(255, 255, 0),
cvf::Color3ub(255, 127, 0),
cvf::Color3ub(255, 0, 0)
};
static std::vector<cvf::Color3ub> colors{cvf::Color3ub( 0, 0, 255 ),
cvf::Color3ub( 0, 127, 255 ),
cvf::Color3ub( 0, 255, 255 ),
cvf::Color3ub( 0, 255, 0 ),
cvf::Color3ub( 255, 255, 0 ),
cvf::Color3ub( 255, 127, 0 ),
cvf::Color3ub( 255, 0, 0 )};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::normalPaletteOppositeOrderingColors()
{
static std::vector<cvf::Color3ub> colors{
cvf::Color3ub(255, 0, 0),
cvf::Color3ub(255, 127, 0),
cvf::Color3ub(255, 255, 0),
cvf::Color3ub( 0, 255, 0),
cvf::Color3ub( 0, 255, 255),
cvf::Color3ub( 0, 127, 255),
cvf::Color3ub( 0, 0, 255)
};
static std::vector<cvf::Color3ub> colors{cvf::Color3ub( 255, 0, 0 ),
cvf::Color3ub( 255, 127, 0 ),
cvf::Color3ub( 255, 255, 0 ),
cvf::Color3ub( 0, 255, 0 ),
cvf::Color3ub( 0, 255, 255 ),
cvf::Color3ub( 0, 127, 255 ),
cvf::Color3ub( 0, 0, 255 )};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::blackWhitePaletteColors()
{
static std::vector<cvf::Color3ub> colors{
cvf::Color3ub::BLACK,
cvf::Color3ub::WHITE
};
static std::vector<cvf::Color3ub> colors{cvf::Color3ub::BLACK, cvf::Color3ub::WHITE};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::whiteBlackPaletteColors()
{
static std::vector<cvf::Color3ub> colors{
cvf::Color3ub::WHITE,
cvf::Color3ub::BLACK
};
static std::vector<cvf::Color3ub> colors{cvf::Color3ub::WHITE, cvf::Color3ub::BLACK};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::pinkWhitePaletteColors()
{
static std::vector<cvf::Color3ub> colors{
cvf::Color3ub::DEEP_PINK,
cvf::Color3ub::WHITE
};
static std::vector<cvf::Color3ub> colors{cvf::Color3ub::DEEP_PINK, cvf::Color3ub::WHITE};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::whitePinkPaletteColors()
{
static std::vector<cvf::Color3ub> colors{
cvf::Color3ub::WHITE,
cvf::Color3ub::DEEP_PINK
};
static std::vector<cvf::Color3ub> colors{cvf::Color3ub::WHITE, cvf::Color3ub::DEEP_PINK};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::blueWhiteRedPaletteColors()
{
static std::vector<cvf::Color3ub> colors{
cvf::Color3ub::BLUE,
cvf::Color3ub::WHITE,
cvf::Color3ub::RED
};
static std::vector<cvf::Color3ub> colors{cvf::Color3ub::BLUE, cvf::Color3ub::WHITE, cvf::Color3ub::RED};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::redWhiteBluePaletteColors()
{
static std::vector<cvf::Color3ub> colors{
cvf::Color3ub::RED,
cvf::Color3ub::WHITE,
cvf::Color3ub::BLUE
};
static std::vector<cvf::Color3ub> colors{cvf::Color3ub::RED, cvf::Color3ub::WHITE, cvf::Color3ub::BLUE};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::categoryPaletteColors()
{
static caf::ColorTable colorTable = caf::ColorTable(categoryColors());
static caf::ColorTable colorTable = caf::ColorTable( categoryColors() );
return colorTable;
}
@@ -171,13 +146,13 @@ const caf::ColorTable& RiaColorTables::categoryPaletteColors()
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::contrastCategoryPaletteColors()
{
static caf::ColorTable colorTable = caf::ColorTable(contrastCategoryColors());
static caf::ColorTable colorTable = caf::ColorTable( contrastCategoryColors() );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::tensorWhiteGrayBlackPaletteColors()
{
@@ -187,109 +162,107 @@ const caf::ColorTable& RiaColorTables::tensorWhiteGrayBlackPaletteColors()
cvf::Color3ub::BLACK,
};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::tensorOrangeBlueWhitePaletteColors()
{
static std::vector<cvf::Color3ub> colors{
cvf::Color3ub(236, 118, 0), // Orange
cvf::Color3ub(56, 56, 255), // Vivid Blue
cvf::Color3ub(210, 248, 250), // White Turquoiseish
cvf::Color3ub( 236, 118, 0 ), // Orange
cvf::Color3ub( 56, 56, 255 ), // Vivid Blue
cvf::Color3ub( 210, 248, 250 ), // White Turquoiseish
};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::tensorsMagentaBrownGrayPaletteColors()
{
static std::vector<cvf::Color3ub> colors{
cvf::Color3ub(248, 0, 170), // Magenta
cvf::Color3ub( 248, 0, 170 ), // Magenta
cvf::Color3ub::BROWN,
cvf::Color3ub::LIGHT_GRAY,
};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::angularPaletteColors()
{
static std::vector<cvf::Color3ub> colors{
cvf::Color3ub(255, 0, 255),
cvf::Color3ub(0, 0, 255),
cvf::Color3ub(0, 127, 255),
cvf::Color3ub(0, 255, 255),
cvf::Color3ub(0, 255, 0),
cvf::Color3ub(255, 255, 0),
cvf::Color3ub(255, 127, 0),
cvf::Color3ub(255, 0, 0),
cvf::Color3ub(255, 0, 255)
};
static std::vector<cvf::Color3ub> colors{cvf::Color3ub( 255, 0, 255 ),
cvf::Color3ub( 0, 0, 255 ),
cvf::Color3ub( 0, 127, 255 ),
cvf::Color3ub( 0, 255, 255 ),
cvf::Color3ub( 0, 255, 0 ),
cvf::Color3ub( 255, 255, 0 ),
cvf::Color3ub( 255, 127, 0 ),
cvf::Color3ub( 255, 0, 0 ),
cvf::Color3ub( 255, 0, 255 )};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::stimPlanPaletteColors()
{
static std::vector<cvf::Color3ub> colors{
cvf::Color3ub(220, 220, 220), //Grey
cvf::Color3ub(0, 0, 255), //Blue
cvf::Color3ub(0, 128, 255), //Lighter blue
cvf::Color3ub(80, 240, 60), //Darker green
cvf::Color3ub(0, 255, 0), //Green
cvf::Color3ub(255, 255, 0), //Yellow
cvf::Color3ub(255, 192, 0), //Light orange
cvf::Color3ub(255, 128, 0), //Orange
cvf::Color3ub(255, 64, 0), //Red-orange
cvf::Color3ub(255, 0, 255) //Magenta
cvf::Color3ub( 220, 220, 220 ), // Grey
cvf::Color3ub( 0, 0, 255 ), // Blue
cvf::Color3ub( 0, 128, 255 ), // Lighter blue
cvf::Color3ub( 80, 240, 60 ), // Darker green
cvf::Color3ub( 0, 255, 0 ), // Green
cvf::Color3ub( 255, 255, 0 ), // Yellow
cvf::Color3ub( 255, 192, 0 ), // Light orange
cvf::Color3ub( 255, 128, 0 ), // Orange
cvf::Color3ub( 255, 64, 0 ), // Red-orange
cvf::Color3ub( 255, 0, 255 ) // Magenta
};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::faultsPaletteColors()
{
static std::vector<cvf::Color3ub> colors{
cvf::Color3ub(101, 132, 96), // Dark green
cvf::Color3ub(255, 131, 140), // Old pink
cvf::Color3ub(210, 176, 112), // Light Brown
cvf::Color3ub(140, 171, 238), // Light gray blue
cvf::Color3ub(255, 205, 131), // Peach
cvf::Color3ub(220, 212, 166), // Dark off white
cvf::Color3ub(130, 255, 120), // Light green
cvf::Color3ub(166, 220, 215), // Light gray torquise
cvf::Color3ub(168, 220, 166), // Light gray green
cvf::Color3ub(255, 64, 236) // Magneta
cvf::Color3ub( 101, 132, 96 ), // Dark green
cvf::Color3ub( 255, 131, 140 ), // Old pink
cvf::Color3ub( 210, 176, 112 ), // Light Brown
cvf::Color3ub( 140, 171, 238 ), // Light gray blue
cvf::Color3ub( 255, 205, 131 ), // Peach
cvf::Color3ub( 220, 212, 166 ), // Dark off white
cvf::Color3ub( 130, 255, 120 ), // Light green
cvf::Color3ub( 166, 220, 215 ), // Light gray torquise
cvf::Color3ub( 168, 220, 166 ), // Light gray green
cvf::Color3ub( 255, 64, 236 ) // Magneta
};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::wellsPaletteColors()
{
@@ -297,226 +270,222 @@ const caf::ColorTable& RiaColorTables::wellsPaletteColors()
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::summaryCurveDefaultPaletteColors()
{
static std::vector<cvf::Color3ub> colors{
cvf::Color3ub( 0, 112, 136), // Dark Green-Blue
cvf::Color3ub(202, 0, 0), // Red
cvf::Color3ub( 78, 204, 0), // Clear Green
cvf::Color3ub(236, 118, 0), // Orange
cvf::Color3ub( 0, 0, 0), // Black
cvf::Color3ub( 56, 56, 255), // Vivid Blue
cvf::Color3ub(248, 0, 170), // Magenta
cvf::Color3ub(169, 2, 240), // Purple
cvf::Color3ub( 0, 221, 221), // Turquoise
cvf::Color3ub(201, 168, 206), // Light Violet
cvf::Color3ub( 0, 205, 68), // Bluish Green
cvf::Color3ub(236, 188, 0), // Mid Yellow
cvf::Color3ub( 51, 204, 255), // Bluer Turquoise
cvf::Color3ub(164, 193, 0), // Mid Yellowish Green
cvf::Color3ub( 0, 143, 239) // Dark Light Blue
cvf::Color3ub( 0, 112, 136 ), // Dark Green-Blue
cvf::Color3ub( 202, 0, 0 ), // Red
cvf::Color3ub( 78, 204, 0 ), // Clear Green
cvf::Color3ub( 236, 118, 0 ), // Orange
cvf::Color3ub( 0, 0, 0 ), // Black
cvf::Color3ub( 56, 56, 255 ), // Vivid Blue
cvf::Color3ub( 248, 0, 170 ), // Magenta
cvf::Color3ub( 169, 2, 240 ), // Purple
cvf::Color3ub( 0, 221, 221 ), // Turquoise
cvf::Color3ub( 201, 168, 206 ), // Light Violet
cvf::Color3ub( 0, 205, 68 ), // Bluish Green
cvf::Color3ub( 236, 188, 0 ), // Mid Yellow
cvf::Color3ub( 51, 204, 255 ), // Bluer Turquoise
cvf::Color3ub( 164, 193, 0 ), // Mid Yellowish Green
cvf::Color3ub( 0, 143, 239 ) // Dark Light Blue
};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::summaryCurveRedPaletteColors()
{
static std::vector<cvf::Color3ub> colors{
cvf::Color3ub(202, 0, 0), // Off Red
cvf::Color3ub(255, 51, 51), // Bright Red
cvf::Color3ub(255, 102, 102) // Light Red
cvf::Color3ub( 202, 0, 0 ), // Off Red
cvf::Color3ub( 255, 51, 51 ), // Bright Red
cvf::Color3ub( 255, 102, 102 ) // Light Red
};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::summaryCurveGreenPaletteColors()
{
static std::vector<cvf::Color3ub> colors{
cvf::Color3ub( 78, 204, 0), // Clear Green
cvf::Color3ub(164, 193, 0), // Mid Yellowish Green
cvf::Color3ub( 0, 205, 68) // Bluish Green
cvf::Color3ub( 78, 204, 0 ), // Clear Green
cvf::Color3ub( 164, 193, 0 ), // Mid Yellowish Green
cvf::Color3ub( 0, 205, 68 ) // Bluish Green
};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::summaryCurveBluePaletteColors()
{
static std::vector<cvf::Color3ub> colors{
cvf::Color3ub( 56, 56, 255), // Vivid Blue
cvf::Color3ub( 0, 143, 239), // Dark Light Blue
cvf::Color3ub(153, 153, 255) // Off Light Blue
cvf::Color3ub( 56, 56, 255 ), // Vivid Blue
cvf::Color3ub( 0, 143, 239 ), // Dark Light Blue
cvf::Color3ub( 153, 153, 255 ) // Off Light Blue
};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::summaryCurveBrownPaletteColors()
{
static std::vector<cvf::Color3ub> colors{
cvf::Color3ub(186, 101, 44),
cvf::Color3ub( 99, 53, 23), // Highway Brown
cvf::Color3ub(103, 56, 24), // Dark Brown
cvf::Color3ub( 186, 101, 44 ),
cvf::Color3ub( 99, 53, 23 ), // Highway Brown
cvf::Color3ub( 103, 56, 24 ), // Dark Brown
};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::summaryCurveNoneRedGreenBlueBrownPaletteColors()
{
static std::vector<cvf::Color3ub> colors{
cvf::Color3ub(236, 118, 0), // Orange
cvf::Color3ub( 0, 0, 0), // Black
cvf::Color3ub(248, 0, 170), // Magenta
cvf::Color3ub(236, 188, 0), // Mid Yellow
cvf::Color3ub(169, 2, 240), // Purple
cvf::Color3ub( 0, 221, 221), // Turquoise
cvf::Color3ub(201, 168, 206) // Light Violet
cvf::Color3ub( 236, 118, 0 ), // Orange
cvf::Color3ub( 0, 0, 0 ), // Black
cvf::Color3ub( 248, 0, 170 ), // Magenta
cvf::Color3ub( 236, 188, 0 ), // Mid Yellow
cvf::Color3ub( 169, 2, 240 ), // Purple
cvf::Color3ub( 0, 221, 221 ), // Turquoise
cvf::Color3ub( 201, 168, 206 ) // Light Violet
};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::wellLogPlotPaletteColors()
{
static std::vector<cvf::Color3ub> colors{
caf::ColorTable::fromQColor(Qt::GlobalColor(Qt::darkBlue)),
caf::ColorTable::fromQColor(Qt::GlobalColor(Qt::darkRed)),
caf::ColorTable::fromQColor(Qt::GlobalColor(Qt::darkGreen)),
caf::ColorTable::fromQColor(Qt::GlobalColor(Qt::darkYellow)),
caf::ColorTable::fromQColor(Qt::GlobalColor(Qt::darkMagenta)),
caf::ColorTable::fromQColor(Qt::GlobalColor(Qt::darkCyan)),
caf::ColorTable::fromQColor(Qt::GlobalColor(Qt::darkGray)),
caf::ColorTable::fromQColor(Qt::GlobalColor(Qt::blue)),
caf::ColorTable::fromQColor(Qt::GlobalColor(Qt::red)),
caf::ColorTable::fromQColor(Qt::GlobalColor(Qt::green)),
caf::ColorTable::fromQColor(Qt::GlobalColor(Qt::yellow)),
caf::ColorTable::fromQColor(Qt::GlobalColor(Qt::magenta)),
caf::ColorTable::fromQColor(Qt::GlobalColor(Qt::cyan)),
caf::ColorTable::fromQColor(Qt::GlobalColor(Qt::gray)),
caf::ColorTable::fromQColor(Qt::GlobalColor(Qt::black))
};
static std::vector<cvf::Color3ub> colors{caf::ColorTable::fromQColor( Qt::GlobalColor( Qt::darkBlue ) ),
caf::ColorTable::fromQColor( Qt::GlobalColor( Qt::darkRed ) ),
caf::ColorTable::fromQColor( Qt::GlobalColor( Qt::darkGreen ) ),
caf::ColorTable::fromQColor( Qt::GlobalColor( Qt::darkYellow ) ),
caf::ColorTable::fromQColor( Qt::GlobalColor( Qt::darkMagenta ) ),
caf::ColorTable::fromQColor( Qt::GlobalColor( Qt::darkCyan ) ),
caf::ColorTable::fromQColor( Qt::GlobalColor( Qt::darkGray ) ),
caf::ColorTable::fromQColor( Qt::GlobalColor( Qt::blue ) ),
caf::ColorTable::fromQColor( Qt::GlobalColor( Qt::red ) ),
caf::ColorTable::fromQColor( Qt::GlobalColor( Qt::green ) ),
caf::ColorTable::fromQColor( Qt::GlobalColor( Qt::yellow ) ),
caf::ColorTable::fromQColor( Qt::GlobalColor( Qt::magenta ) ),
caf::ColorTable::fromQColor( Qt::GlobalColor( Qt::cyan ) ),
caf::ColorTable::fromQColor( Qt::GlobalColor( Qt::gray ) ),
caf::ColorTable::fromQColor( Qt::GlobalColor( Qt::black ) )};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::selectionPaletteColors()
{
static std::vector<cvf::Color3ub> colors{
caf::ColorTable::fromQColor(Qt::GlobalColor(Qt::magenta)),
caf::ColorTable::fromQColor(Qt::GlobalColor(Qt::cyan)),
caf::ColorTable::fromQColor(Qt::GlobalColor(Qt::blue)),
caf::ColorTable::fromQColor(Qt::GlobalColor(Qt::red)),
caf::ColorTable::fromQColor(Qt::GlobalColor(Qt::green)),
caf::ColorTable::fromQColor(Qt::GlobalColor(Qt::yellow)),
caf::ColorTable::fromQColor(Qt::GlobalColor(Qt::gray))
};
static std::vector<cvf::Color3ub> colors{caf::ColorTable::fromQColor( Qt::GlobalColor( Qt::magenta ) ),
caf::ColorTable::fromQColor( Qt::GlobalColor( Qt::cyan ) ),
caf::ColorTable::fromQColor( Qt::GlobalColor( Qt::blue ) ),
caf::ColorTable::fromQColor( Qt::GlobalColor( Qt::red ) ),
caf::ColorTable::fromQColor( Qt::GlobalColor( Qt::green ) ),
caf::ColorTable::fromQColor( Qt::GlobalColor( Qt::yellow ) ),
caf::ColorTable::fromQColor( Qt::GlobalColor( Qt::gray ) )};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::timestepsPaletteColors()
{
static std::vector<cvf::Color3ub> colors{
cvf::Color3ub( 56, 56, 255), // Vivid Blue
cvf::Color3ub( 0, 143, 239), // Dark Light Blue
cvf::Color3ub( 0, 112, 136), // Dark Green-Blue
cvf::Color3ub( 51, 204, 255), // Bluer Turquoise
cvf::Color3ub( 0, 221, 221), // Turquoise
cvf::Color3ub( 0, 205, 68), // Bluish Green
cvf::Color3ub( 78, 204, 0), // Clear Green
cvf::Color3ub(164, 193, 0), // Mid Yellowish Green
cvf::Color3ub(236, 188, 0), // Mid Yellow
cvf::Color3ub(236, 118, 0), // Orange
cvf::Color3ub(202, 0, 0), // Red
cvf::Color3ub(248, 0, 170), // Magenta
cvf::Color3ub(201, 168, 206), // Light Violet
cvf::Color3ub(169, 2, 240), // Purple
cvf::Color3ub( 56, 56, 255 ), // Vivid Blue
cvf::Color3ub( 0, 143, 239 ), // Dark Light Blue
cvf::Color3ub( 0, 112, 136 ), // Dark Green-Blue
cvf::Color3ub( 51, 204, 255 ), // Bluer Turquoise
cvf::Color3ub( 0, 221, 221 ), // Turquoise
cvf::Color3ub( 0, 205, 68 ), // Bluish Green
cvf::Color3ub( 78, 204, 0 ), // Clear Green
cvf::Color3ub( 164, 193, 0 ), // Mid Yellowish Green
cvf::Color3ub( 236, 188, 0 ), // Mid Yellow
cvf::Color3ub( 236, 118, 0 ), // Orange
cvf::Color3ub( 202, 0, 0 ), // Red
cvf::Color3ub( 248, 0, 170 ), // Magenta
cvf::Color3ub( 201, 168, 206 ), // Light Violet
cvf::Color3ub( 169, 2, 240 ), // Purple
};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::editableWellPathsPaletteColors()
{
static std::vector<cvf::Color3ub> colors{
cvf::Color3ub( 204, 0, 204), // Dark magenta
cvf::Color3ub( 173, 23, 212), // Strong Purple
cvf::Color3ub( 143, 46, 219), //Purple
cvf::Color3ub( 102, 76, 230), // Gray Blue
cvf::Color3ub( 71, 99, 237), // Lighter Gray Blue
cvf::Color3ub( 31, 130, 247), // Strong Blue
cvf::Color3ub( 0, 153, 255), // Dark Turquise
cvf::Color3ub( 204, 0, 204 ), // Dark magenta
cvf::Color3ub( 173, 23, 212 ), // Strong Purple
cvf::Color3ub( 143, 46, 219 ), // Purple
cvf::Color3ub( 102, 76, 230 ), // Gray Blue
cvf::Color3ub( 71, 99, 237 ), // Lighter Gray Blue
cvf::Color3ub( 31, 130, 247 ), // Strong Blue
cvf::Color3ub( 0, 153, 255 ), // Dark Turquise
};
static caf::ColorTable colorTable = caf::ColorTable(colors);
static caf::ColorTable colorTable = caf::ColorTable( colors );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const caf::ColorTable& RiaColorTables::wellPathsPaletteColors()
{
// Use inverted category colors to avoid identical colors if we have few sim wells and few well paths
static caf::ColorTable colorTable = caf::ColorTable(invertedCategoryColors());
static caf::ColorTable colorTable = caf::ColorTable( invertedCategoryColors() );
return colorTable;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
cvf::Color3f RiaColorTables::undefinedCellColor()
{
@@ -546,16 +515,15 @@ RiaColorTables::WellPathComponentColors RiaColorTables::wellPathComponentColors(
//--------------------------------------------------------------------------------------------------
cvf::Color3f RiaColorTables::defaultGridLineColor()
{
return cvf::Color3f(0.92f, 0.92f, 0.92f);
return cvf::Color3f( 0.92f, 0.92f, 0.92f );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
cvf::Color3f RiaColorTables::defaultFaultLineColor()
{
return cvf::Color3f(0.08f, 0.08f, 0.08f);
return cvf::Color3f( 0.08f, 0.08f, 0.08f );
}
//--------------------------------------------------------------------------------------------------
@@ -563,7 +531,7 @@ cvf::Color3f RiaColorTables::defaultFaultLineColor()
//--------------------------------------------------------------------------------------------------
cvf::Color3f RiaColorTables::defaultWellLabelColor()
{
return cvf::Color3f(0.92f, 0.92f, 0.92f);
return cvf::Color3f( 0.92f, 0.92f, 0.92f );
}
//--------------------------------------------------------------------------------------------------
@@ -571,37 +539,38 @@ cvf::Color3f RiaColorTables::defaultWellLabelColor()
//--------------------------------------------------------------------------------------------------
cvf::Color3f RiaColorTables::defaultViewerBackgroundColor()
{
return cvf::Color3f(0.69f, 0.77f, 0.87f);
return cvf::Color3f( 0.69f, 0.77f, 0.87f );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
caf::ColorTable RiaColorTables::createBrightnessBasedColorTable(cvf::Color3ub baseColor, int brightnessLevelCount)
caf::ColorTable RiaColorTables::createBrightnessBasedColorTable( cvf::Color3ub baseColor, int brightnessLevelCount )
{
CVF_ASSERT(brightnessLevelCount >= 1);
QColor baseRGB(baseColor.r(), baseColor.g(), baseColor.b());
float hueF = baseRGB.hslHueF();
float satF = baseRGB.hslSaturationF();
CVF_ASSERT( brightnessLevelCount >= 1 );
QColor baseRGB( baseColor.r(), baseColor.g(), baseColor.b() );
float hueF = baseRGB.hslHueF();
float satF = baseRGB.hslSaturationF();
std::vector<cvf::Color3ub> colors;
if (brightnessLevelCount == 1)
if ( brightnessLevelCount == 1 )
{
colors.push_back(cvf::Color3ub(RiaColorTools::fromQColorTo3f(QColor::fromHslF(hueF, satF, 0.5))));
colors.push_back( cvf::Color3ub( RiaColorTools::fromQColorTo3f( QColor::fromHslF( hueF, satF, 0.5 ) ) ) );
}
else
{
for (int i = 0; i < brightnessLevelCount; ++i)
for ( int i = 0; i < brightnessLevelCount; ++i )
{
float brightness = static_cast<float>(i) / static_cast<float>(brightnessLevelCount - 1);
colors.push_back(cvf::Color3ub(RiaColorTools::fromQColorTo3f(QColor::fromHslF(hueF, satF, brightness))));
float brightness = static_cast<float>( i ) / static_cast<float>( brightnessLevelCount - 1 );
colors.push_back(
cvf::Color3ub( RiaColorTools::fromQColorTo3f( QColor::fromHslF( hueF, satF, brightness ) ) ) );
}
}
return caf::ColorTable(colors);
return caf::ColorTable( colors );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
std::vector<cvf::Color3ub> RiaColorTables::categoryColors()
{
@@ -610,26 +579,26 @@ std::vector<cvf::Color3ub> RiaColorTables::categoryColors()
// See also http://www.w3schools.com/colors/ for palettes etc.
static std::vector<cvf::Color3ub> colors{
cvf::Color3ub(128, 62, 117), // hwb(310, 24%, 50%) strong_purple
cvf::Color3ub(212, 28, 132), // hwb(326, 11%, 17%) strong_purplish_red
cvf::Color3ub(246, 118, 142), // hwb(349, 46%, 4%) strong_purplish_pink
cvf::Color3ub(193, 0, 32), // hwb(350, 0%, 24%) vivid_red
cvf::Color3ub(127, 24, 13), // hwb( 6, 5%, 50%) strong_reddish_brown
cvf::Color3ub(241, 58, 19), // hwb( 11, 7%, 5%) vivid_reddish_orange
cvf::Color3ub(255, 122, 92), // hwb( 11, 36%, 0%) strong_yellowish_pink
cvf::Color3ub(129, 112, 102), // hwb( 22, 40%, 49%) medium_gray
cvf::Color3ub(255, 104, 0), // hwb( 24, 0%, 0%) vivid_orange
cvf::Color3ub( 89, 51, 21), // hwb( 26, 8%, 65%) deep_yellowish_brown
cvf::Color3ub(255, 142, 0), // hwb( 33, 0%, 0%) vivid_orange_yellow
cvf::Color3ub(206, 162, 98), // hwb( 36, 38%, 19%) grayish_yellow
cvf::Color3ub(244, 200, 0), // hwb( 49, 0%, 4%) vivid_greenish_yellow
cvf::Color3ub(147, 170, 0), // hwb( 68, 0%, 33%) vivid_yellowish_green
cvf::Color3ub( 59, 84, 23), // hwb( 85, 9%, 67%) dark_olive_green
cvf::Color3ub( 0, 125, 52), // hwb(145, 0%, 51%) vivid_green
cvf::Color3ub( 54, 125, 123), // hwb(178, 21%, 51%) vivid_blueish_green
cvf::Color3ub( 0, 83, 138), // hwb(204, 0%, 46%) strong_blue
cvf::Color3ub(166, 189, 215), // hwb(212, 65%, 16%) very_light_blue
cvf::Color3ub( 46, 76, 224) // hwb(230, 18%, 12%) medium_blue
cvf::Color3ub( 128, 62, 117 ), // hwb(310, 24%, 50%) strong_purple
cvf::Color3ub( 212, 28, 132 ), // hwb(326, 11%, 17%) strong_purplish_red
cvf::Color3ub( 246, 118, 142 ), // hwb(349, 46%, 4%) strong_purplish_pink
cvf::Color3ub( 193, 0, 32 ), // hwb(350, 0%, 24%) vivid_red
cvf::Color3ub( 127, 24, 13 ), // hwb( 6, 5%, 50%) strong_reddish_brown
cvf::Color3ub( 241, 58, 19 ), // hwb( 11, 7%, 5%) vivid_reddish_orange
cvf::Color3ub( 255, 122, 92 ), // hwb( 11, 36%, 0%) strong_yellowish_pink
cvf::Color3ub( 129, 112, 102 ), // hwb( 22, 40%, 49%) medium_gray
cvf::Color3ub( 255, 104, 0 ), // hwb( 24, 0%, 0%) vivid_orange
cvf::Color3ub( 89, 51, 21 ), // hwb( 26, 8%, 65%) deep_yellowish_brown
cvf::Color3ub( 255, 142, 0 ), // hwb( 33, 0%, 0%) vivid_orange_yellow
cvf::Color3ub( 206, 162, 98 ), // hwb( 36, 38%, 19%) grayish_yellow
cvf::Color3ub( 244, 200, 0 ), // hwb( 49, 0%, 4%) vivid_greenish_yellow
cvf::Color3ub( 147, 170, 0 ), // hwb( 68, 0%, 33%) vivid_yellowish_green
cvf::Color3ub( 59, 84, 23 ), // hwb( 85, 9%, 67%) dark_olive_green
cvf::Color3ub( 0, 125, 52 ), // hwb(145, 0%, 51%) vivid_green
cvf::Color3ub( 54, 125, 123 ), // hwb(178, 21%, 51%) vivid_blueish_green
cvf::Color3ub( 0, 83, 138 ), // hwb(204, 0%, 46%) strong_blue
cvf::Color3ub( 166, 189, 215 ), // hwb(212, 65%, 16%) very_light_blue
cvf::Color3ub( 46, 76, 224 ) // hwb(230, 18%, 12%) medium_blue
};
return colors;
@@ -645,58 +614,58 @@ std::vector<cvf::Color3ub> RiaColorTables::contrastCategoryColors()
// See also http://www.w3schools.com/colors/ for palettes etc.
static std::vector<cvf::Color3ub> colors{
cvf::Color3ub(244, 200, 0), // hwb( 49, 0%, 4%) vivid_greenish_yellow
cvf::Color3ub(128, 62, 117), // hwb(310, 24%, 50%) strong_purple
cvf::Color3ub(255, 104, 0), // hwb( 24, 0%, 0%) vivid_orange
cvf::Color3ub(166, 189, 215), // hwb(212, 65%, 16%) very_light_blue
cvf::Color3ub(193, 0, 32), // hwb(350, 0%, 24%) vivid_red
cvf::Color3ub(206, 162, 98), // hwb( 36, 38%, 19%) grayish_yellow
cvf::Color3ub(129, 112, 102), // hwb( 22, 40%, 49%) medium_gray
cvf::Color3ub(0, 125, 52), // hwb(145, 0%, 51%) vivid_green
cvf::Color3ub(246, 118, 142), // hwb(349, 46%, 4%) strong_purplish_pink
cvf::Color3ub(0, 83, 138), // hwb(204, 0%, 46%) strong_blue
cvf::Color3ub(255, 122, 92), // hwb( 11, 36%, 0%) strong_yellowish_pink
cvf::Color3ub(212, 28, 132), // hwb(326, 11%, 17%) strong_purplish_red
cvf::Color3ub(255, 142, 0), // hwb( 33, 0%, 0%) vivid_orange_yellow
cvf::Color3ub(59, 84, 23), // hwb( 85, 9%, 67%) dark_olive_green
cvf::Color3ub(127, 24, 13), // hwb( 6, 5%, 50%) strong_reddish_brown
cvf::Color3ub(54, 125, 123), // hwb(178, 21%, 51%) vivid_blueish_green
cvf::Color3ub(241, 58, 19), // hwb( 11, 7%, 5%) vivid_reddish_orange
cvf::Color3ub(147, 170, 0), // hwb( 68, 0%, 33%) vivid_yellowish_green
cvf::Color3ub(46, 76, 224), // hwb(230, 18%, 12%) medium_blue
cvf::Color3ub(89, 51, 21), // hwb( 26, 8%, 65%) deep_yellowish_brown
cvf::Color3ub(0, 0, 0) // hwb(0, 0%, 100%) black
cvf::Color3ub( 244, 200, 0 ), // hwb( 49, 0%, 4%) vivid_greenish_yellow
cvf::Color3ub( 128, 62, 117 ), // hwb(310, 24%, 50%) strong_purple
cvf::Color3ub( 255, 104, 0 ), // hwb( 24, 0%, 0%) vivid_orange
cvf::Color3ub( 166, 189, 215 ), // hwb(212, 65%, 16%) very_light_blue
cvf::Color3ub( 193, 0, 32 ), // hwb(350, 0%, 24%) vivid_red
cvf::Color3ub( 206, 162, 98 ), // hwb( 36, 38%, 19%) grayish_yellow
cvf::Color3ub( 129, 112, 102 ), // hwb( 22, 40%, 49%) medium_gray
cvf::Color3ub( 0, 125, 52 ), // hwb(145, 0%, 51%) vivid_green
cvf::Color3ub( 246, 118, 142 ), // hwb(349, 46%, 4%) strong_purplish_pink
cvf::Color3ub( 0, 83, 138 ), // hwb(204, 0%, 46%) strong_blue
cvf::Color3ub( 255, 122, 92 ), // hwb( 11, 36%, 0%) strong_yellowish_pink
cvf::Color3ub( 212, 28, 132 ), // hwb(326, 11%, 17%) strong_purplish_red
cvf::Color3ub( 255, 142, 0 ), // hwb( 33, 0%, 0%) vivid_orange_yellow
cvf::Color3ub( 59, 84, 23 ), // hwb( 85, 9%, 67%) dark_olive_green
cvf::Color3ub( 127, 24, 13 ), // hwb( 6, 5%, 50%) strong_reddish_brown
cvf::Color3ub( 54, 125, 123 ), // hwb(178, 21%, 51%) vivid_blueish_green
cvf::Color3ub( 241, 58, 19 ), // hwb( 11, 7%, 5%) vivid_reddish_orange
cvf::Color3ub( 147, 170, 0 ), // hwb( 68, 0%, 33%) vivid_yellowish_green
cvf::Color3ub( 46, 76, 224 ), // hwb(230, 18%, 12%) medium_blue
cvf::Color3ub( 89, 51, 21 ), // hwb( 26, 8%, 65%) deep_yellowish_brown
cvf::Color3ub( 0, 0, 0 ) // hwb(0, 0%, 100%) black
};
return colors;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
std::vector<cvf::Color3ub> RiaColorTables::invertedCategoryColors()
{
static std::vector<cvf::Color3ub> colors{
cvf::Color3ub( 46, 76, 224), // hwb(230, 18%, 12%) medium_blue
cvf::Color3ub(166, 189, 215), // hwb(212, 65%, 16%) very_light_blue
cvf::Color3ub( 0, 83, 138), // hwb(204, 0%, 46%) strong_blue
cvf::Color3ub( 54, 125, 123), // hwb(178, 21%, 51%) vivid_blueish_green
cvf::Color3ub( 0, 125, 52), // hwb(145, 0%, 51%) vivid_green
cvf::Color3ub( 59, 84, 23), // hwb( 85, 9%, 67%) dark_olive_green
cvf::Color3ub(147, 170, 0), // hwb( 68, 0%, 33%) vivid_yellowish_green
cvf::Color3ub(244, 200, 0), // hwb( 49, 0%, 4%) vivid_greenish_yellow
cvf::Color3ub(206, 162, 98), // hwb( 36, 38%, 19%) grayish_yellow
cvf::Color3ub(255, 142, 0), // hwb( 33, 0%, 0%) vivid_orange_yellow
cvf::Color3ub( 89, 51, 21), // hwb( 26, 8%, 65%) deep_yellowish_brown
cvf::Color3ub(255, 104, 0), // hwb( 24, 0%, 0%) vivid_orange
cvf::Color3ub(129, 112, 102), // hwb( 22, 40%, 49%) medium_gray
cvf::Color3ub(255, 122, 92), // hwb( 11, 36%, 0%) strong_yellowish_pink
cvf::Color3ub(241, 58, 19), // hwb( 11, 7%, 5%) vivid_reddish_orange
cvf::Color3ub(127, 24, 13), // hwb( 6, 5%, 50%) strong_reddish_brown
cvf::Color3ub(193, 0, 32), // hwb(350, 0%, 24%) vivid_red
cvf::Color3ub(246, 118, 142), // hwb(349, 46%, 4%) strong_purplish_pink
cvf::Color3ub(212, 28, 132), // hwb(326, 11%, 17%) strong_purplish_red
cvf::Color3ub(128, 62, 117) // hwb(310, 24%, 50%) strong_purple
cvf::Color3ub( 46, 76, 224 ), // hwb(230, 18%, 12%) medium_blue
cvf::Color3ub( 166, 189, 215 ), // hwb(212, 65%, 16%) very_light_blue
cvf::Color3ub( 0, 83, 138 ), // hwb(204, 0%, 46%) strong_blue
cvf::Color3ub( 54, 125, 123 ), // hwb(178, 21%, 51%) vivid_blueish_green
cvf::Color3ub( 0, 125, 52 ), // hwb(145, 0%, 51%) vivid_green
cvf::Color3ub( 59, 84, 23 ), // hwb( 85, 9%, 67%) dark_olive_green
cvf::Color3ub( 147, 170, 0 ), // hwb( 68, 0%, 33%) vivid_yellowish_green
cvf::Color3ub( 244, 200, 0 ), // hwb( 49, 0%, 4%) vivid_greenish_yellow
cvf::Color3ub( 206, 162, 98 ), // hwb( 36, 38%, 19%) grayish_yellow
cvf::Color3ub( 255, 142, 0 ), // hwb( 33, 0%, 0%) vivid_orange_yellow
cvf::Color3ub( 89, 51, 21 ), // hwb( 26, 8%, 65%) deep_yellowish_brown
cvf::Color3ub( 255, 104, 0 ), // hwb( 24, 0%, 0%) vivid_orange
cvf::Color3ub( 129, 112, 102 ), // hwb( 22, 40%, 49%) medium_gray
cvf::Color3ub( 255, 122, 92 ), // hwb( 11, 36%, 0%) strong_yellowish_pink
cvf::Color3ub( 241, 58, 19 ), // hwb( 11, 7%, 5%) vivid_reddish_orange
cvf::Color3ub( 127, 24, 13 ), // hwb( 6, 5%, 50%) strong_reddish_brown
cvf::Color3ub( 193, 0, 32 ), // hwb(350, 0%, 24%) vivid_red
cvf::Color3ub( 246, 118, 142 ), // hwb(349, 46%, 4%) strong_purplish_pink
cvf::Color3ub( 212, 28, 132 ), // hwb(326, 11%, 17%) strong_purplish_red
cvf::Color3ub( 128, 62, 117 ) // hwb(310, 24%, 50%) strong_purple
};
return colors;

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017 Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE.
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -23,8 +23,8 @@
#include <map>
//==================================================================================================
///
///
///
///
//==================================================================================================
class RiaColorTables
{
@@ -68,10 +68,10 @@ public:
static cvf::Color3f defaultGridLineColor();
static cvf::Color3f defaultFaultLineColor();
static cvf::Color3f defaultWellLabelColor();
static cvf::Color3f defaultViewerBackgroundColor();
static cvf::Color3f defaultViewerBackgroundColor();
static caf::ColorTable createBrightnessBasedColorTable( cvf::Color3ub baseColor, int brightnessLevelCount );
static caf::ColorTable createBrightnessBasedColorTable(cvf::Color3ub baseColor, int brightnessLevelCount);
private:
static std::vector<cvf::Color3ub> categoryColors();
static std::vector<cvf::Color3ub> contrastCategoryColors();

View File

@@ -31,9 +31,9 @@
/// Luminance is between [0, 1] so anything above 0.5 is considered in the bright half of the spectrum.
/// However, subjectively the contrast looks better if the threshold is to 0.4 so black contrast is used a bit more often.
//--------------------------------------------------------------------------------------------------
bool RiaColorTools::isBrightnessAboveThreshold(cvf::Color3f backgroundColor)
bool RiaColorTools::isBrightnessAboveThreshold( cvf::Color3f backgroundColor )
{
if (relativeLuminance(backgroundColor) > 0.4)
if ( relativeLuminance( backgroundColor ) > 0.4 )
{
return true;
}
@@ -44,27 +44,28 @@ bool RiaColorTools::isBrightnessAboveThreshold(cvf::Color3f backgroundColor)
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
cvf::Color3f RiaColorTools::computeOffsetColor(cvf::Color3f color, float offsetFactor)
cvf::Color3f RiaColorTools::computeOffsetColor( cvf::Color3f color, float offsetFactor )
{
float gridR = 0.0;
float gridG = 0.0;
float gridB = 0.0;
if (isBrightnessAboveThreshold(color))
if ( isBrightnessAboveThreshold( color ) )
{
gridR = color.r() - (color.r() * offsetFactor);
gridG = color.g() - (color.g() * offsetFactor);
gridB = color.b() - (color.b() * offsetFactor);
gridR = color.r() - ( color.r() * offsetFactor );
gridG = color.g() - ( color.g() * offsetFactor );
gridB = color.b() - ( color.b() * offsetFactor );
}
else
{
gridR = color.r() + (1.0f - color.r()) * offsetFactor;
gridG = color.g() + (1.0f - color.g()) * offsetFactor;
gridB = color.b() + (1.0f - color.b()) * offsetFactor;
gridR = color.r() + ( 1.0f - color.r() ) * offsetFactor;
gridG = color.g() + ( 1.0f - color.g() ) * offsetFactor;
gridB = color.b() + ( 1.0f - color.b() ) * offsetFactor;
}
return cvf::Color3f(
cvf::Math::clamp(gridR, 0.0f, 1.0f), cvf::Math::clamp(gridG, 0.0f, 1.0f), cvf::Math::clamp(gridB, 0.0f, 1.0f));
return cvf::Color3f( cvf::Math::clamp( gridR, 0.0f, 1.0f ),
cvf::Math::clamp( gridG, 0.0f, 1.0f ),
cvf::Math::clamp( gridB, 0.0f, 1.0f ) );
}
//--------------------------------------------------------------------------------------------------
@@ -72,7 +73,7 @@ cvf::Color3f RiaColorTools::computeOffsetColor(cvf::Color3f color, float offsetF
//--------------------------------------------------------------------------------------------------
cvf::Color3f RiaColorTools::darkContrastColor()
{
return cvf::Color3f::fromByteColor(10, 10, 10);
return cvf::Color3f::fromByteColor( 10, 10, 10 );
}
//--------------------------------------------------------------------------------------------------
@@ -88,7 +89,7 @@ cvf::Color3f RiaColorTools::brightContrastColor()
//--------------------------------------------------------------------------------------------------
cvf::Color3f RiaColorTools::darkContrastColorSofter()
{
return cvf::Color3f::fromByteColor(30, 30, 30);
return cvf::Color3f::fromByteColor( 30, 30, 30 );
}
//--------------------------------------------------------------------------------------------------
@@ -96,87 +97,84 @@ cvf::Color3f RiaColorTools::darkContrastColorSofter()
//--------------------------------------------------------------------------------------------------
cvf::Color3f RiaColorTools::brightContrastColorSofter()
{
return cvf::Color3f::fromByteColor(200, 200, 200);
return cvf::Color3f::fromByteColor( 200, 200, 200 );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
cvf::Color3f RiaColorTools::contrastColor(cvf::Color3f backgroundColor, bool softerContrast)
cvf::Color3f RiaColorTools::contrastColor( cvf::Color3f backgroundColor, bool softerContrast )
{
if (isBrightnessAboveThreshold(backgroundColor))
if ( isBrightnessAboveThreshold( backgroundColor ) )
{
if (softerContrast)
return darkContrastColorSofter();
if ( softerContrast ) return darkContrastColorSofter();
return darkContrastColor();
}
if (softerContrast)
return brightContrastColorSofter();
if ( softerContrast ) return brightContrastColorSofter();
return brightContrastColor();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QColor RiaColorTools::toQColor(cvf::Color3f color, float alpha)
QColor RiaColorTools::toQColor( cvf::Color3f color, float alpha )
{
QColor qcolor(color.rByte(), color.gByte(), color.bByte());
qcolor.setAlphaF(alpha);
QColor qcolor( color.rByte(), color.gByte(), color.bByte() );
qcolor.setAlphaF( alpha );
return qcolor;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QColor RiaColorTools::toQColor(cvf::Color4f color)
QColor RiaColorTools::toQColor( cvf::Color4f color )
{
return toQColor(color.toColor3f(), color.a());
return toQColor( color.toColor3f(), color.a() );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
cvf::Color3f RiaColorTools::fromQColorTo3f(QColor color)
cvf::Color3f RiaColorTools::fromQColorTo3f( QColor color )
{
return cvf::Color3f(color.redF(), color.greenF(), color.blueF());
return cvf::Color3f( color.redF(), color.greenF(), color.blueF() );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
cvf::Color3f RiaColorTools::blendCvfColors(const cvf::Color3f& color1,
const cvf::Color3f& color2,
int weight1 /*= 1*/,
int weight2 /*= 1*/)
cvf::Color3f RiaColorTools::blendCvfColors( const cvf::Color3f& color1,
const cvf::Color3f& color2,
int weight1 /*= 1*/,
int weight2 /*= 1*/ )
{
CVF_ASSERT(weight1 > 0 && weight2 > 0);
CVF_ASSERT( weight1 > 0 && weight2 > 0 );
int weightsum = weight1 + weight2;
return cvf::Color3f((color1.r() * weight1 + color2.r() * weight2) / weightsum,
(color1.g() * weight1 + color2.g() * weight2) / weightsum,
(color1.b() * weight1 + color2.b() * weight2) / weightsum);
return cvf::Color3f( ( color1.r() * weight1 + color2.r() * weight2 ) / weightsum,
( color1.g() * weight1 + color2.g() * weight2 ) / weightsum,
( color1.b() * weight1 + color2.b() * weight2 ) / weightsum );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QColor RiaColorTools::blendQColors(const QColor& color1, const QColor& color2, int weight1 /*= 1*/, int weight2 /*= 1*/)
QColor RiaColorTools::blendQColors( const QColor& color1, const QColor& color2, int weight1 /*= 1*/, int weight2 /*= 1*/ )
{
CVF_ASSERT(weight1 > 0 && weight2 > 0);
CVF_ASSERT( weight1 > 0 && weight2 > 0 );
int weightsum = weight1 + weight2;
return QColor((color1.red() * weight1 + color2.red() * weight2) / weightsum,
(color1.green() * weight1 + color2.green() * weight2) / weightsum,
(color1.blue() * weight1 + color2.blue() * weight2) / weightsum);
return QColor( ( color1.red() * weight1 + color2.red() * weight2 ) / weightsum,
( color1.green() * weight1 + color2.green() * weight2 ) / weightsum,
( color1.blue() * weight1 + color2.blue() * weight2 ) / weightsum );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
float RiaColorTools::relativeLuminance(cvf::Color3f backgroundColor)
float RiaColorTools::relativeLuminance( cvf::Color3f backgroundColor )
{
float R = calculateNonLinearColorValue(backgroundColor.r());
float G = calculateNonLinearColorValue(backgroundColor.g());
float B = calculateNonLinearColorValue(backgroundColor.b());
float R = calculateNonLinearColorValue( backgroundColor.r() );
float G = calculateNonLinearColorValue( backgroundColor.g() );
float B = calculateNonLinearColorValue( backgroundColor.b() );
double luminance = 0.2126 * R + 0.7152 * G + 0.0722 * B;
return luminance;
@@ -185,7 +183,7 @@ float RiaColorTools::relativeLuminance(cvf::Color3f backgroundColor)
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
float RiaColorTools::calculateNonLinearColorValue(float colorFraction)
float RiaColorTools::calculateNonLinearColorValue( float colorFraction )
{
return colorFraction <= 0.03928 ? colorFraction / 12.92 : std::pow((colorFraction + 0.055) / 1.055, 2.4);
return colorFraction <= 0.03928 ? colorFraction / 12.92 : std::pow( ( colorFraction + 0.055 ) / 1.055, 2.4 );
}

View File

@@ -19,34 +19,34 @@
#pragma once
#include "cvfArray.h"
#include <QColor>
//==================================================================================================
///
///
///
///
//==================================================================================================
class RiaColorTools
{
public:
static bool isBrightnessAboveThreshold(cvf::Color3f backgroundColor);
static cvf::Color3f computeOffsetColor(cvf::Color3f color, float offsetFactor);
static bool isBrightnessAboveThreshold( cvf::Color3f backgroundColor );
static cvf::Color3f computeOffsetColor( cvf::Color3f color, float offsetFactor );
static cvf::Color3f darkContrastColor();
static cvf::Color3f brightContrastColor();
static cvf::Color3f darkContrastColorSofter();
static cvf::Color3f brightContrastColorSofter();
static cvf::Color3f contrastColor(cvf::Color3f backgroundColor, bool softerContrast = false);
static QColor toQColor(cvf::Color3f color, float alpha = 1.0f);
static QColor toQColor(cvf::Color4f color);
static cvf::Color3f fromQColorTo3f(QColor);
static cvf::Color3f contrastColor( cvf::Color3f backgroundColor, bool softerContrast = false );
static QColor toQColor( cvf::Color3f color, float alpha = 1.0f );
static QColor toQColor( cvf::Color4f color );
static cvf::Color3f fromQColorTo3f( QColor );
static cvf::Color3f blendCvfColors(const cvf::Color3f& color1, const cvf::Color3f& color2, int weight1 = 1, int weight2 = 1);
static QColor blendQColors(const QColor& color1, const QColor& color2, int weight1 = 1, int weight2 = 1);
static cvf::Color3f
blendCvfColors( const cvf::Color3f& color1, const cvf::Color3f& color2, int weight1 = 1, int weight2 = 1 );
static QColor blendQColors( const QColor& color1, const QColor& color2, int weight1 = 1, int weight2 = 1 );
private:
static float relativeLuminance(cvf::Color3f backgroundColor);
static float calculateNonLinearColorValue(float colorFraction);
static float relativeLuminance( cvf::Color3f backgroundColor );
static float calculateNonLinearColorValue( float colorFraction );
};

View File

@@ -2,52 +2,50 @@
//
// Copyright (C) 2015- Statoil ASA
// Copyright (C) 2015- Ceetron Solutions 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>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
#include "RiaCurveDataTools.h"
#include <cmath> // Needed for HUGE_VAL on Linux
#include <cmath> // Needed for HUGE_VAL on Linux
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
RiaCurveDataTools::CurveIntervals RiaCurveDataTools::calculateIntervalsOfValidValues(const std::vector<double>& values,
bool includePositiveValuesOnly)
RiaCurveDataTools::CurveIntervals RiaCurveDataTools::calculateIntervalsOfValidValues( const std::vector<double>& values,
bool includePositiveValuesOnly )
{
CurveIntervals intervals;
int startIdx = -1;
size_t vIdx = 0;
int startIdx = -1;
size_t vIdx = 0;
size_t valueCount = values.size();
while (vIdx < valueCount)
while ( vIdx < valueCount )
{
bool isValid = RiaCurveDataTools::isValidValue(values[vIdx], includePositiveValuesOnly);
bool isValid = RiaCurveDataTools::isValidValue( values[vIdx], includePositiveValuesOnly );
if (!isValid)
if ( !isValid )
{
if (startIdx >= 0)
if ( startIdx >= 0 )
{
intervals.push_back(std::make_pair(startIdx, vIdx - 1));
intervals.push_back( std::make_pair( startIdx, vIdx - 1 ) );
startIdx = -1;
}
}
else if (startIdx < 0)
else if ( startIdx < 0 )
{
startIdx = (int)vIdx;
}
@@ -55,30 +53,29 @@ RiaCurveDataTools::CurveIntervals RiaCurveDataTools::calculateIntervalsOfValidVa
vIdx++;
}
if (startIdx >= 0 && startIdx < ((int)valueCount))
if ( startIdx >= 0 && startIdx < ( (int)valueCount ) )
{
intervals.push_back(std::make_pair(startIdx, valueCount - 1));
intervals.push_back( std::make_pair( startIdx, valueCount - 1 ) );
}
return intervals;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
std::vector<std::pair<size_t, size_t>> RiaCurveDataTools::computePolyLineStartStopIndices(const CurveIntervals& intervals)
std::vector<std::pair<size_t, size_t>> RiaCurveDataTools::computePolyLineStartStopIndices( const CurveIntervals& intervals )
{
std::vector<std::pair<size_t, size_t>> lineStartAndStopIndices;
const size_t intervalCount = intervals.size();
if (intervalCount < 1) return lineStartAndStopIndices;
if ( intervalCount < 1 ) return lineStartAndStopIndices;
size_t index = 0;
for (size_t intIdx = 0; intIdx < intervalCount; intIdx++)
for ( size_t intIdx = 0; intIdx < intervalCount; intIdx++ )
{
size_t intervalSize = intervals[intIdx].second - intervals[intIdx].first + 1;
lineStartAndStopIndices.push_back(std::make_pair(index, index + intervalSize - 1));
lineStartAndStopIndices.push_back( std::make_pair( index, index + intervalSize - 1 ) );
index += intervalSize;
}
@@ -86,22 +83,20 @@ std::vector<std::pair<size_t, size_t>> RiaCurveDataTools::computePolyLineStartSt
return lineStartAndStopIndices;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool RiaCurveDataTools::isValidValue(double value, bool allowPositiveValuesOnly)
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool RiaCurveDataTools::isValidValue( double value, bool allowPositiveValuesOnly )
{
if (value == HUGE_VAL || value == -HUGE_VAL || value != value)
if ( value == HUGE_VAL || value == -HUGE_VAL || value != value )
{
return false;
}
if (allowPositiveValuesOnly && value <= 0)
if ( allowPositiveValuesOnly && value <= 0 )
{
return false;
}
return true;
}

View File

@@ -2,17 +2,17 @@
//
// Copyright (C) 2015- Statoil ASA
// Copyright (C) 2015- Ceetron Solutions 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>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -22,15 +22,14 @@
#include "cvfAssert.h"
#include <cstddef>
#include <vector>
#include <utility>
#include <set>
#include <utility>
#include <vector>
class QDateTime;
//==================================================================================================
///
///
//==================================================================================================
class RiaCurveDataTools
{
@@ -38,28 +37,27 @@ public:
typedef std::vector<std::pair<size_t, size_t>> CurveIntervals;
public:
static CurveIntervals calculateIntervalsOfValidValues(const std::vector<double>& values,
bool includePositiveValuesOnly);
static CurveIntervals calculateIntervalsOfValidValues( const std::vector<double>& values,
bool includePositiveValuesOnly );
template <typename T>
static void getValuesByIntervals(const std::vector<T>& values,
const CurveIntervals& intervals,
std::vector<T>* filteredValues)
static void getValuesByIntervals( const std::vector<T>& values,
const CurveIntervals& intervals,
std::vector<T>* filteredValues )
{
CVF_ASSERT(filteredValues);
CVF_ASSERT( filteredValues );
for (size_t intIdx = 0; intIdx < intervals.size(); intIdx++)
for ( size_t intIdx = 0; intIdx < intervals.size(); intIdx++ )
{
for (size_t vIdx = intervals[intIdx].first; vIdx <= intervals[intIdx].second; vIdx++)
for ( size_t vIdx = intervals[intIdx].first; vIdx <= intervals[intIdx].second; vIdx++ )
{
filteredValues->push_back(values[vIdx]);
filteredValues->push_back( values[vIdx] );
}
}
}
static std::vector<std::pair<size_t, size_t>> computePolyLineStartStopIndices(const CurveIntervals& intervals);
static std::vector<std::pair<size_t, size_t>> computePolyLineStartStopIndices( const CurveIntervals& intervals );
public:
static bool isValidValue(double value, bool allowPositiveValuesOnly);
static bool isValidValue( double value, bool allowPositiveValuesOnly );
};

View File

@@ -6,15 +6,15 @@
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
template<>
bool XValueComparator<double>::equals(const double& lhs, const double& rhs)
template <>
bool XValueComparator<double>::equals( const double& lhs, const double& rhs )
{
double eps = 1.0e-12 * std::max(std::fabs(lhs), std::fabs(rhs));
return std::fabs(lhs - rhs) < eps;
double eps = 1.0e-12 * std::max( std::fabs( lhs ), std::fabs( rhs ) );
return std::fabs( lhs - rhs ) < eps;
}
template<>
double XValueComparator<time_t>::diff(const time_t& lhs, const time_t& rhs)
template <>
double XValueComparator<time_t>::diff( const time_t& lhs, const time_t& rhs )
{
return difftime(lhs, rhs);
return difftime( lhs, rhs );
}

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017 Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE.
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -22,66 +22,65 @@
#include <ctime>
template<typename XValueType>
template <typename XValueType>
class XValueComparator
{
public:
bool operator()(const XValueType& lhs, const XValueType& rhs) const;
static bool equals(const XValueType& lhs, const XValueType& rhs);
static double diff(const XValueType& lhs, const XValueType& rhs);
bool operator()( const XValueType& lhs, const XValueType& rhs ) const;
static bool equals( const XValueType& lhs, const XValueType& rhs );
static double diff( const XValueType& lhs, const XValueType& rhs );
};
//==================================================================================================
///
///
//==================================================================================================
template<typename XValueType>
template <typename XValueType>
class RiaCurveMerger
{
public:
typedef XValueComparator<XValueType> XComparator;
RiaCurveMerger();
void addCurveData(const std::vector<XValueType>& xValues, const std::vector<double>& yValues);
void addCurveData( const std::vector<XValueType>& xValues, const std::vector<double>& yValues );
size_t curveCount() const;
void computeInterpolatedValues(bool includeValuesFromPartialCurves = true);
void computeInterpolatedValues( bool includeValuesFromPartialCurves = true );
RiaCurveDataTools::CurveIntervals validIntervalsForAllXValues() const;
const std::vector<XValueType>& allXValues() const;
const std::vector<double>& interpolatedYValuesForAllXValues(size_t curveIdx) const;
RiaCurveDataTools::CurveIntervals validIntervalsForAllXValues() const;
const std::vector<XValueType>& allXValues() const;
const std::vector<double>& interpolatedYValuesForAllXValues( size_t curveIdx ) const;
// Non-const access is not required by any clients, but the expression parser has no available const interface
// for specifying a data source for an expression variable. Allow non-const access to avoid copy of the contained
// for specifying a data source for an expression variable. Allow non-const access to avoid copy of the contained
// values, interpolated for all time steps
//
// See ExpressionParserImpl::assignVector()
std::vector<double>& interpolatedYValuesForAllXValues(size_t curveIdx);
std::vector<double>& interpolatedYValuesForAllXValues( size_t curveIdx );
public:
// Helper methods, available as public to be able to access from unit tests
static double interpolatedYValue(const XValueType& xValue,
const std::vector<XValueType>& curveXValues,
const std::vector<double>& curveYValues);
static double interpolatedYValue( const XValueType& xValue,
const std::vector<XValueType>& curveXValues,
const std::vector<double>& curveYValues );
private:
void computeUnionOfXValues(bool includeValuesFromPartialCurves);
void computeUnionOfXValues( bool includeValuesFromPartialCurves );
private:
std::vector<std::pair<std::vector<XValueType>, std::vector<double>>> m_originalValues;
RiaCurveDataTools::CurveIntervals m_validIntervalsForAllXValues;
RiaCurveDataTools::CurveIntervals m_validIntervalsForAllXValues;
std::vector<XValueType> m_allXValues;
std::vector<std::vector<double>> m_interpolatedValuesForAllCurves;
std::vector<XValueType> m_allXValues;
std::vector<std::vector<double>> m_interpolatedValuesForAllCurves;
};
typedef RiaCurveMerger<time_t> RiaTimeHistoryCurveMerger;
template<>
bool XValueComparator<double>::equals(const double& lhs, const double& rhs);
template<>
double XValueComparator<time_t>::diff(const time_t& lhs, const time_t& rhs);
template <>
bool XValueComparator<double>::equals( const double& lhs, const double& rhs );
template <>
double XValueComparator<time_t>::diff( const time_t& lhs, const time_t& rhs );
#include "RiaCurveMerger.inl"

View File

@@ -1,66 +1,52 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017 Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE.
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
#include "RiaDateStringParser.h"
#include "RiaStdStringTools.h"
#include "RiaQDateTimeTools.h"
#include "RiaStdStringTools.h"
#include <algorithm>
const std::string MONTH_NAMES[] =
{
"january",
"february",
"march",
"april",
"may",
"june",
"july",
"august",
"september",
"october",
"november",
"december"
};
{"january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"};
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QDateTime RiaDateStringParser::parseDateString(const QString& dateString)
QDateTime RiaDateStringParser::parseDateString( const QString& dateString )
{
return RiaDateStringParser::parseDateString(dateString.toStdString());
return RiaDateStringParser::parseDateString( dateString.toStdString() );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QDateTime RiaDateStringParser::parseDateString(const std::string& dateString)
QDateTime RiaDateStringParser::parseDateString( const std::string& dateString )
{
int year, month, day;
bool parsedOk =
tryParseYearFirst(dateString, year, month, day) ||
tryParseDayFirst(dateString, year, month, day) ||
tryParseMonthFirst(dateString, year, month, day);
int year, month, day;
bool parsedOk = tryParseYearFirst( dateString, year, month, day ) ||
tryParseDayFirst( dateString, year, month, day ) ||
tryParseMonthFirst( dateString, year, month, day );
QDateTime dt;
dt.setTimeSpec(RiaQDateTimeTools::currentTimeSpec());
if (parsedOk) dt.setDate(QDate(year, month, day));
dt.setTimeSpec( RiaQDateTimeTools::currentTimeSpec() );
if ( parsedOk ) dt.setDate( QDate( year, month, day ) );
return dt;
}
@@ -77,25 +63,25 @@ QDateTime RiaDateStringParser::parseDateString(const std::string& dateString)
/// 'yyyy.MMM.dd'
/// MMM is month name (shortened)
//--------------------------------------------------------------------------------------------------
bool RiaDateStringParser::tryParseYearFirst(const std::string& s, int& year, int& month, int& day)
bool RiaDateStringParser::tryParseYearFirst( const std::string& s, int& year, int& month, int& day )
{
auto firstSep = s.find_first_of(" -_.");
auto lastSep = s.find_first_of(" -_.", firstSep + 1);
auto firstSep = s.find_first_of( " -_." );
auto lastSep = s.find_first_of( " -_.", firstSep + 1 );
if (firstSep == std::string::npos || lastSep == std::string::npos) return false;
if ( firstSep == std::string::npos || lastSep == std::string::npos ) return false;
auto sYear = s.substr(0, firstSep);
auto sMonth = s.substr(firstSep + 1, lastSep - firstSep - 1);
auto sDay = s.substr(lastSep + 1);
auto sYear = s.substr( 0, firstSep );
auto sMonth = s.substr( firstSep + 1, lastSep - firstSep - 1 );
auto sDay = s.substr( lastSep + 1 );
return tryParseYear(sYear, year) && tryParseMonth(sMonth, month) && tryParseDay(sDay, day);
return tryParseYear( sYear, year ) && tryParseMonth( sMonth, month ) && tryParseDay( sDay, day );
}
//--------------------------------------------------------------------------------------------------
/// Try parse formats
/// 'dd mm yyyy'
/// 'dd mm yyyy'
/// 'dd MMM yyyy'
/// 'dd_mm_yyyy'
/// 'dd_mm_yyyy'
/// 'dd_MMM_yyyy'
/// 'dd-mm-yyyy'
/// 'dd-MMM-yyyy'
@@ -103,47 +89,47 @@ bool RiaDateStringParser::tryParseYearFirst(const std::string& s, int& year, int
/// 'dd.MMM.yyyy'
/// MMM is month name (shortened)
//--------------------------------------------------------------------------------------------------
bool RiaDateStringParser::tryParseDayFirst(const std::string& s, int& year, int& month, int& day)
bool RiaDateStringParser::tryParseDayFirst( const std::string& s, int& year, int& month, int& day )
{
auto firstSep = s.find_first_of(" -_.");
auto lastSep = s.find_first_of(" -_.", firstSep + 1);
auto firstSep = s.find_first_of( " -_." );
auto lastSep = s.find_first_of( " -_.", firstSep + 1 );
if (firstSep == std::string::npos || lastSep == std::string::npos) return false;
if ( firstSep == std::string::npos || lastSep == std::string::npos ) return false;
auto sDay = s.substr(0, firstSep);
auto sMonth = s.substr(firstSep + 1, lastSep - firstSep - 1);
auto sYear = s.substr(lastSep + 1);
auto sDay = s.substr( 0, firstSep );
auto sMonth = s.substr( firstSep + 1, lastSep - firstSep - 1 );
auto sYear = s.substr( lastSep + 1 );
return tryParseYear(sYear, year) && tryParseMonth(sMonth, month) && tryParseDay(sDay, day);
return tryParseYear( sYear, year ) && tryParseMonth( sMonth, month ) && tryParseDay( sDay, day );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
bool RiaDateStringParser::tryParseMonthFirst(const std::string& s, int& year, int& month, int& day)
bool RiaDateStringParser::tryParseMonthFirst( const std::string& s, int& year, int& month, int& day )
{
auto firstSep = s.find_first_of(" -_.");
auto lastSep = s.find_first_of(" -_.", firstSep + 1);
auto firstSep = s.find_first_of( " -_." );
auto lastSep = s.find_first_of( " -_.", firstSep + 1 );
if (firstSep == std::string::npos || lastSep == std::string::npos) return false;
if ( firstSep == std::string::npos || lastSep == std::string::npos ) return false;
auto sMonth = s.substr(0, firstSep);
auto sDay = s.substr(firstSep + 1, lastSep - firstSep - 1);
auto sYear = s.substr(lastSep + 1);
auto sMonth = s.substr( 0, firstSep );
auto sDay = s.substr( firstSep + 1, lastSep - firstSep - 1 );
auto sYear = s.substr( lastSep + 1 );
return tryParseYear(sYear, year) && tryParseMonth(sMonth, month) && tryParseDay(sDay, day);
return tryParseYear( sYear, year ) && tryParseMonth( sMonth, month ) && tryParseDay( sDay, day );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
bool RiaDateStringParser::tryParseYear(const std::string& s, int &year)
bool RiaDateStringParser::tryParseYear( const std::string& s, int& year )
{
if (RiaStdStringTools::containsAlphabetic(s)) return false;
if ( RiaStdStringTools::containsAlphabetic( s ) ) return false;
auto today = QDate::currentDate();
int y = RiaStdStringTools::toInt(s);
if (y > 1970 && y <= today.year())
int y = RiaStdStringTools::toInt( s );
if ( y > 1970 && y <= today.year() )
{
year = y;
@@ -154,20 +140,21 @@ bool RiaDateStringParser::tryParseYear(const std::string& s, int &year)
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
bool RiaDateStringParser::tryParseMonth(const std::string& s, int &month)
bool RiaDateStringParser::tryParseMonth( const std::string& s, int& month )
{
if (RiaStdStringTools::containsAlphabetic(s))
if ( RiaStdStringTools::containsAlphabetic( s ) )
{
auto sMonth = s;
sMonth = trimString(sMonth);
std::transform(sMonth.begin(), sMonth.end(), sMonth.begin(),
[](const char c) -> char { return (char)::tolower(c); });
sMonth = trimString( sMonth );
std::transform( sMonth.begin(), sMonth.end(), sMonth.begin(), []( const char c ) -> char {
return (char)::tolower( c );
} );
for (int i = 0; i < 12; i++)
for ( int i = 0; i < 12; i++ )
{
if (MONTH_NAMES[i].compare(0, sMonth.size(), sMonth) == 0)
if ( MONTH_NAMES[i].compare( 0, sMonth.size(), sMonth ) == 0 )
{
month = i + 1;
return true;
@@ -176,11 +163,11 @@ bool RiaDateStringParser::tryParseMonth(const std::string& s, int &month)
}
else
{
int m = RiaStdStringTools::toInt(s);
if (m >= 1 && m <= 12)
int m = RiaStdStringTools::toInt( s );
if ( m >= 1 && m <= 12 )
{
month = m;
return true;
}
}
@@ -189,14 +176,14 @@ bool RiaDateStringParser::tryParseMonth(const std::string& s, int &month)
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
bool RiaDateStringParser::tryParseDay(const std::string& s, int &day)
bool RiaDateStringParser::tryParseDay( const std::string& s, int& day )
{
if (RiaStdStringTools::containsAlphabetic(s)) return false;
if ( RiaStdStringTools::containsAlphabetic( s ) ) return false;
int d = RiaStdStringTools::toInt(s);
if (d >= 1 && d <= 31)
int d = RiaStdStringTools::toInt( s );
if ( d >= 1 && d <= 31 )
{
day = d;
@@ -207,11 +194,11 @@ bool RiaDateStringParser::tryParseDay(const std::string& s, int &day)
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
std::string RiaDateStringParser::trimString(const std::string& s)
std::string RiaDateStringParser::trimString( const std::string& s )
{
auto sCopy = s.substr(0, s.find_last_not_of(' ') + 1);
sCopy = sCopy.substr(sCopy.find_first_not_of(' '));
auto sCopy = s.substr( 0, s.find_last_not_of( ' ' ) + 1 );
sCopy = sCopy.substr( sCopy.find_first_not_of( ' ' ) );
return sCopy;
}

View File

@@ -1,47 +1,46 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017 Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE.
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
#pragma once
#include <string>
#include <QString>
#include <QDateTime>
#include <QString>
#include <string>
//==================================================================================================
//
//
//
//
//==================================================================================================
class RiaDateStringParser
{
public:
static QDateTime parseDateString(const QString& dateString);
static QDateTime parseDateString(const std::string& dateString);
static QDateTime parseDateString( const QString& dateString );
static QDateTime parseDateString( const std::string& dateString );
private:
static bool tryParseYearFirst(const std::string& s, int& year, int& month, int& day);
static bool tryParseDayFirst(const std::string& s, int& year, int& month, int& day);
static bool tryParseMonthFirst(const std::string& s, int& year, int& month, int& day);
static bool tryParseYearFirst( const std::string& s, int& year, int& month, int& day );
static bool tryParseDayFirst( const std::string& s, int& year, int& month, int& day );
static bool tryParseMonthFirst( const std::string& s, int& year, int& month, int& day );
static bool tryParseYear(const std::string& s, int &year);
static bool tryParseMonth(const std::string& s, int &month);
static bool tryParseDay(const std::string& s, int &day);
static bool tryParseYear( const std::string& s, int& year );
static bool tryParseMonth( const std::string& s, int& month );
static bool tryParseDay( const std::string& s, int& day );
static std::string trimString(const std::string& s);
static std::string trimString( const std::string& s );
};

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017- Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE.
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -25,21 +25,21 @@
namespace caf
{
template<>
void RiaEclipseUnitTools::UnitSystemType::setUp()
{
addItem(RiaEclipseUnitTools::UNITS_METRIC, "UNITS_METRIC", "Metric");
addItem(RiaEclipseUnitTools::UNITS_FIELD, "UNITS_FIELD", "Field");
addItem(RiaEclipseUnitTools::UNITS_UNKNOWN, "UNITS_UNKNOWN", "Unknown");
template <>
void RiaEclipseUnitTools::UnitSystemType::setUp()
{
addItem( RiaEclipseUnitTools::UNITS_METRIC, "UNITS_METRIC", "Metric" );
addItem( RiaEclipseUnitTools::UNITS_FIELD, "UNITS_FIELD", "Field" );
addItem( RiaEclipseUnitTools::UNITS_UNKNOWN, "UNITS_UNKNOWN", "Unknown" );
setDefault(RiaEclipseUnitTools::UNITS_METRIC);
}
setDefault( RiaEclipseUnitTools::UNITS_METRIC );
}
} // namespace caf
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
double RiaEclipseUnitTools::darcysConstant(UnitSystem unitSystem)
double RiaEclipseUnitTools::darcysConstant( UnitSystem unitSystem )
{
// See "Cartesian transmissibility calculations" in the "Eclipse Technical Description"
// CDARCY Darcys constant
@@ -47,109 +47,115 @@ double RiaEclipseUnitTools::darcysConstant(UnitSystem unitSystem)
// = 0.00112712 (E300); 0.001127 (ECLIPSE 100) (FIELD)
// = 3.6 (LAB)
// = 0.00864 (PVT - M)
switch (unitSystem)
switch ( unitSystem )
{
case UNITS_FIELD:
return 0.001127;
case UNITS_METRIC:
return 0.008527;
default:
CVF_ASSERT(false);
return 0.0;
case UNITS_FIELD:
return 0.001127;
case UNITS_METRIC:
return 0.008527;
default:
CVF_ASSERT( false );
return 0.0;
}
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
RiaDefines::DepthUnitType RiaEclipseUnitTools::depthUnit(UnitSystem unit)
RiaDefines::DepthUnitType RiaEclipseUnitTools::depthUnit( UnitSystem unit )
{
switch (unit)
switch ( unit )
{
case RiaEclipseUnitTools::UNITS_METRIC:
return RiaDefines::UNIT_METER;
break;
case RiaEclipseUnitTools::UNITS_FIELD:
return RiaDefines::UNIT_FEET;
break;
case RiaEclipseUnitTools::UNITS_LAB:
return RiaDefines::UNIT_NONE;
break;
case RiaEclipseUnitTools::UNITS_UNKNOWN:
return RiaDefines::UNIT_NONE;
break;
default:
return RiaDefines::UNIT_NONE;
break;
case RiaEclipseUnitTools::UNITS_METRIC:
return RiaDefines::UNIT_METER;
break;
case RiaEclipseUnitTools::UNITS_FIELD:
return RiaDefines::UNIT_FEET;
break;
case RiaEclipseUnitTools::UNITS_LAB:
return RiaDefines::UNIT_NONE;
break;
case RiaEclipseUnitTools::UNITS_UNKNOWN:
return RiaDefines::UNIT_NONE;
break;
default:
return RiaDefines::UNIT_NONE;
break;
}
}
//--------------------------------------------------------------------------------------------------
/// Convert Gas to oil equivalents
/// If field unit, the Gas is in Mega ft^3 while the others are in [stb] (barrel)
/// If field unit, the Gas is in Mega ft^3 while the others are in [stb] (barrel)
//--------------------------------------------------------------------------------------------------
double RiaEclipseUnitTools::convertSurfaceGasFlowRateToOilEquivalents(UnitSystem caseUnitSystem, double eclGasFlowRate)
double RiaEclipseUnitTools::convertSurfaceGasFlowRateToOilEquivalents( UnitSystem caseUnitSystem, double eclGasFlowRate )
{
/// Unused Gas to Barrel conversion :
/// we convert gas to stb as well. Based on
/// we convert gas to stb as well. Based on
/// 1 [stb] = 0.15898729492800007 [m^3]
/// 1 [ft] = 0.3048 [m]
/// megaFt3ToStbFactor = 1.0 / (1.0e-6 * 0.15898729492800007 * ( 1.0 / 0.3048 )^3 )
/// double megaFt3ToStbFactor = 178107.60668;
double fieldGasToOilEquivalent = 1.0e6/5800; // Mega ft^3 to BOE
double metricGasToOilEquivalent = 1.0/1.0e3; // Sm^3 Gas to Sm^3 oe
double fieldGasToOilEquivalent = 1.0e6 / 5800; // Mega ft^3 to BOE
double metricGasToOilEquivalent = 1.0 / 1.0e3; // Sm^3 Gas to Sm^3 oe
double oilEquivalentGasRate = HUGE_VAL;
if (caseUnitSystem == RiaEclipseUnitTools::UNITS_FIELD) oilEquivalentGasRate = fieldGasToOilEquivalent * eclGasFlowRate;
if (caseUnitSystem == RiaEclipseUnitTools::UNITS_METRIC) oilEquivalentGasRate = metricGasToOilEquivalent * eclGasFlowRate;
if ( caseUnitSystem == RiaEclipseUnitTools::UNITS_FIELD )
oilEquivalentGasRate = fieldGasToOilEquivalent * eclGasFlowRate;
if ( caseUnitSystem == RiaEclipseUnitTools::UNITS_METRIC )
oilEquivalentGasRate = metricGasToOilEquivalent * eclGasFlowRate;
return oilEquivalentGasRate;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QString RiaEclipseUnitTools::unitStringPressure(UnitSystem unitSystem)
QString RiaEclipseUnitTools::unitStringPressure( UnitSystem unitSystem )
{
switch (unitSystem)
switch ( unitSystem )
{
case RiaEclipseUnitTools::UNITS_METRIC: return "barsa";
case RiaEclipseUnitTools::UNITS_FIELD: return "psia";
case RiaEclipseUnitTools::UNITS_LAB: return "atma";
case RiaEclipseUnitTools::UNITS_UNKNOWN: return "";
default: return "";
case RiaEclipseUnitTools::UNITS_METRIC:
return "barsa";
case RiaEclipseUnitTools::UNITS_FIELD:
return "psia";
case RiaEclipseUnitTools::UNITS_LAB:
return "atma";
case RiaEclipseUnitTools::UNITS_UNKNOWN:
return "";
default:
return "";
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
double RiaEclipseUnitTools::convertToMeter(double sourceValue, const QString& sourceValueUnitText)
double RiaEclipseUnitTools::convertToMeter( double sourceValue, const QString& sourceValueUnitText )
{
QString timmed = sourceValueUnitText.trimmed();
if (timmed.compare("m", Qt::CaseInsensitive) == 0 || timmed.compare("md-m", Qt::CaseInsensitive) == 0)
if ( timmed.compare( "m", Qt::CaseInsensitive ) == 0 || timmed.compare( "md-m", Qt::CaseInsensitive ) == 0 )
{
return sourceValue;
}
else if (timmed.compare("cm", Qt::CaseInsensitive) == 0)
else if ( timmed.compare( "cm", Qt::CaseInsensitive ) == 0 )
{
return sourceValue / 100.0;
}
else if (timmed.compare("mm", Qt::CaseInsensitive) == 0)
else if ( timmed.compare( "mm", Qt::CaseInsensitive ) == 0 )
{
return sourceValue / 1000.0;
}
else if (timmed.compare("in", Qt::CaseInsensitive) == 0)
else if ( timmed.compare( "in", Qt::CaseInsensitive ) == 0 )
{
return RiaEclipseUnitTools::inchToMeter(sourceValue);
return RiaEclipseUnitTools::inchToMeter( sourceValue );
}
else if (timmed.compare("ft", Qt::CaseInsensitive) == 0 || timmed.compare("md-ft", Qt::CaseInsensitive) == 0)
else if ( timmed.compare( "ft", Qt::CaseInsensitive ) == 0 || timmed.compare( "md-ft", Qt::CaseInsensitive ) == 0 )
{
return RiaEclipseUnitTools::feetToMeter(sourceValue);
return RiaEclipseUnitTools::feetToMeter( sourceValue );
}
return HUGE_VAL;
@@ -158,31 +164,31 @@ double RiaEclipseUnitTools::convertToMeter(double sourceValue, const QString& so
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
double RiaEclipseUnitTools::convertToFeet(double sourceValue, const QString& sourceValueUnitText)
double RiaEclipseUnitTools::convertToFeet( double sourceValue, const QString& sourceValueUnitText )
{
QString timmed = sourceValueUnitText.trimmed();
if (timmed.compare("ft", Qt::CaseInsensitive) == 0 || timmed.compare("md-ft", Qt::CaseInsensitive) == 0)
if ( timmed.compare( "ft", Qt::CaseInsensitive ) == 0 || timmed.compare( "md-ft", Qt::CaseInsensitive ) == 0 )
{
return sourceValue;
}
else if (timmed.compare("in", Qt::CaseInsensitive) == 0)
else if ( timmed.compare( "in", Qt::CaseInsensitive ) == 0 )
{
return RiaEclipseUnitTools::inchToFeet(sourceValue);
return RiaEclipseUnitTools::inchToFeet( sourceValue );
}
else if (timmed.compare("cm", Qt::CaseInsensitive) == 0)
else if ( timmed.compare( "cm", Qt::CaseInsensitive ) == 0 )
{
double meter = sourceValue / 100.0;
return RiaEclipseUnitTools::meterToFeet(meter);
return RiaEclipseUnitTools::meterToFeet( meter );
}
else if (timmed.compare("mm", Qt::CaseInsensitive) == 0)
else if ( timmed.compare( "mm", Qt::CaseInsensitive ) == 0 )
{
double meter = sourceValue / 1000.0;
return RiaEclipseUnitTools::meterToFeet(meter);
return RiaEclipseUnitTools::meterToFeet( meter );
}
else if (timmed.compare("m", Qt::CaseInsensitive) == 0 || timmed.compare("md-m", Qt::CaseInsensitive) == 0)
else if ( timmed.compare( "m", Qt::CaseInsensitive ) == 0 || timmed.compare( "md-m", Qt::CaseInsensitive ) == 0 )
{
return RiaEclipseUnitTools::meterToFeet(sourceValue);
return RiaEclipseUnitTools::meterToFeet( sourceValue );
}
return HUGE_VAL;

View File

@@ -1,29 +1,28 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017- Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE.
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
#pragma once
#include "cafAppEnum.h"
#include "RiaDefines.h"
#include "cafAppEnum.h"
class RiaEclipseUnitTools
{
public:
enum UnitSystem
{
@@ -33,28 +32,54 @@ public:
UNITS_UNKNOWN,
};
typedef caf::AppEnum< RiaEclipseUnitTools::UnitSystem > UnitSystemType;
typedef caf::AppEnum<RiaEclipseUnitTools::UnitSystem> UnitSystemType;
static double feetPerMeter() { return 3.2808399; }
static double meterPerFeet() { return 0.3048000; }
static double feetPerMeter()
{
return 3.2808399;
}
static double meterPerFeet()
{
return 0.3048000;
}
static double meterToFeet(double meter) { return meter * feetPerMeter(); }
static double feetToMeter(double feet) { return feet * meterPerFeet();}
static double meterToInch(double meter) { return meter * feetPerMeter()*12.0; }
static double inchToMeter(double inch) { return (inch / 12.0) * meterPerFeet(); }
static double inchToFeet (double inch) { return (inch / 12.0); }
static double mmToMeter(double mm) { return mm / 1000.0; }
static double meterToMm(double meter) { return 1000.0 * meter; }
static double meterToFeet( double meter )
{
return meter * feetPerMeter();
}
static double feetToMeter( double feet )
{
return feet * meterPerFeet();
}
static double meterToInch( double meter )
{
return meter * feetPerMeter() * 12.0;
}
static double inchToMeter( double inch )
{
return ( inch / 12.0 ) * meterPerFeet();
}
static double inchToFeet( double inch )
{
return ( inch / 12.0 );
}
static double mmToMeter( double mm )
{
return mm / 1000.0;
}
static double meterToMm( double meter )
{
return 1000.0 * meter;
}
static double darcysConstant(UnitSystem unitSystem);
static double darcysConstant( UnitSystem unitSystem );
static RiaDefines::DepthUnitType depthUnit(UnitSystem unit);
static RiaDefines::DepthUnitType depthUnit( UnitSystem unit );
static double convertSurfaceGasFlowRateToOilEquivalents(UnitSystem, double eclGasFlowRate);
static double convertSurfaceGasFlowRateToOilEquivalents( UnitSystem, double eclGasFlowRate );
static QString unitStringPressure(UnitSystem unitSystem);
static QString unitStringPressure( UnitSystem unitSystem );
static double convertToMeter(double sourceValue, const QString& unitText);
static double convertToFeet(double sourceValue, const QString& unitText);
static double convertToMeter( double sourceValue, const QString& unitText );
static double convertToFeet( double sourceValue, const QString& unitText );
};

View File

@@ -30,50 +30,54 @@
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RigEclipseWellLogExtractor* RiaExtractionTools::wellLogExtractorEclipseCase(RimWellPath* wellPath, RimEclipseCase* eclipseCase)
RigEclipseWellLogExtractor* RiaExtractionTools::wellLogExtractorEclipseCase( RimWellPath* wellPath,
RimEclipseCase* eclipseCase )
{
auto wlPlotCollection = wellLogPlotCollection();
if (!wlPlotCollection) return nullptr;
if ( !wlPlotCollection ) return nullptr;
return wlPlotCollection->findOrCreateExtractor(wellPath, eclipseCase);
return wlPlotCollection->findOrCreateExtractor( wellPath, eclipseCase );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RigGeoMechWellLogExtractor* RiaExtractionTools::wellLogExtractorGeoMechCase(RimWellPath* wellPath, RimGeoMechCase* geomCase)
RigGeoMechWellLogExtractor* RiaExtractionTools::wellLogExtractorGeoMechCase( RimWellPath* wellPath,
RimGeoMechCase* geomCase )
{
auto wlPlotCollection = wellLogPlotCollection();
if (!wlPlotCollection) return nullptr;
if ( !wlPlotCollection ) return nullptr;
return wlPlotCollection->findOrCreateExtractor(wellPath, geomCase);
return wlPlotCollection->findOrCreateExtractor( wellPath, geomCase );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RigEclipseWellLogExtractor* RiaExtractionTools::findOrCreateSimWellExtractor(const RimSimWellInView* simWell,
const RigWellPath* wellPathGeom)
RigEclipseWellLogExtractor* RiaExtractionTools::findOrCreateSimWellExtractor( const RimSimWellInView* simWell,
const RigWellPath* wellPathGeom )
{
auto wlPlotCollection = wellLogPlotCollection();
if (!wlPlotCollection) return nullptr;
if ( !wlPlotCollection ) return nullptr;
if (!(simWell && wellPathGeom))
if ( !( simWell && wellPathGeom ) )
{
return nullptr;
}
RimEclipseCase* eclipseCase = nullptr;
simWell->firstAncestorOrThisOfType(eclipseCase);
if (!(eclipseCase && eclipseCase->eclipseCaseData()))
simWell->firstAncestorOrThisOfType( eclipseCase );
if ( !( eclipseCase && eclipseCase->eclipseCaseData() ) )
{
return nullptr;
}
QString caseUserDescription = eclipseCase->caseUserDescription();
return wlPlotCollection->findOrCreateSimWellExtractor(
simWell->name, caseUserDescription, wellPathGeom, eclipseCase->eclipseCaseData());
return wlPlotCollection->findOrCreateSimWellExtractor( simWell->name,
caseUserDescription,
wellPathGeom,
eclipseCase->eclipseCaseData() );
}
//--------------------------------------------------------------------------------------------------
@@ -82,10 +86,10 @@ RigEclipseWellLogExtractor* RiaExtractionTools::findOrCreateSimWellExtractor(con
RimWellLogPlotCollection* RiaExtractionTools::wellLogPlotCollection()
{
auto proj = RiaApplication::instance()->project();
if (!proj) return nullptr;
if ( !proj ) return nullptr;
auto plotCollection = proj->mainPlotCollection();
if (!plotCollection) return nullptr;
if ( !plotCollection ) return nullptr;
auto wellLogPlotCollection = plotCollection->wellLogPlotCollection();
return wellLogPlotCollection;

View File

@@ -34,10 +34,11 @@ class QString;
//==================================================================================================
namespace RiaExtractionTools
{
RigEclipseWellLogExtractor* wellLogExtractorEclipseCase(RimWellPath* wellPath, RimEclipseCase* eclipseCase);
RigGeoMechWellLogExtractor* wellLogExtractorGeoMechCase(RimWellPath* wellPath, RimGeoMechCase* geomCase);
RigEclipseWellLogExtractor* wellLogExtractorEclipseCase( RimWellPath* wellPath, RimEclipseCase* eclipseCase );
RigGeoMechWellLogExtractor* wellLogExtractorGeoMechCase( RimWellPath* wellPath, RimGeoMechCase* geomCase );
RigEclipseWellLogExtractor* findOrCreateSimWellExtractor(const RimSimWellInView* simWell, const RigWellPath* wellPathGeom);
RigEclipseWellLogExtractor* findOrCreateSimWellExtractor( const RimSimWellInView* simWell,
const RigWellPath* wellPathGeom );
RimWellLogPlotCollection* wellLogPlotCollection();

View File

@@ -28,17 +28,17 @@
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaFieldhandleTools::disableWriteAndSetFieldHidden(caf::PdmFieldHandle* fieldHandle)
void RiaFieldhandleTools::disableWriteAndSetFieldHidden( caf::PdmFieldHandle* fieldHandle )
{
CVF_ASSERT(fieldHandle);
CVF_ASSERT( fieldHandle );
if (fieldHandle->uiCapability())
if ( fieldHandle->uiCapability() )
{
fieldHandle->uiCapability()->setUiHidden(true);
fieldHandle->uiCapability()->setUiHidden( true );
}
if (fieldHandle->xmlCapability())
if ( fieldHandle->xmlCapability() )
{
fieldHandle->xmlCapability()->setIOWritable(false);
fieldHandle->xmlCapability()->setIOWritable( false );
}
}

View File

@@ -30,5 +30,5 @@ class PdmFieldHandle;
class RiaFieldhandleTools
{
public:
static void disableWriteAndSetFieldHidden(caf::PdmFieldHandle* fieldHandle);
static void disableWriteAndSetFieldHidden( caf::PdmFieldHandle* fieldHandle );
};

View File

@@ -3,17 +3,17 @@
// Copyright (C) 2011- Statoil ASA
// Copyright (C) 2013- Ceetron Solutions AS
// Copyright (C) 2011-2012 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>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -22,20 +22,19 @@
#include <QDir>
#include <set>
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const QChar RiaFilePathTools::SEPARATOR = '/';
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QString RiaFilePathTools::toInternalSeparator(const QString& path)
QString RiaFilePathTools::toInternalSeparator( const QString& path )
{
QString currNativeSep = QDir::separator();
if (currNativeSep == "/")
if ( currNativeSep == "/" )
{
// On Linux like system -> Do not convert separators
return path;
@@ -43,33 +42,33 @@ QString RiaFilePathTools::toInternalSeparator(const QString& path)
// On other systems (i.e. Windows) -> Convert to internal separator (/)
QString output = path;
return output.replace(QString("\\"), SEPARATOR);
return output.replace( QString( "\\" ), SEPARATOR );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QString& RiaFilePathTools::appendSeparatorIfNo(QString& path)
QString& RiaFilePathTools::appendSeparatorIfNo( QString& path )
{
if (!path.endsWith(SEPARATOR))
if ( !path.endsWith( SEPARATOR ) )
{
path.append(SEPARATOR);
path.append( SEPARATOR );
}
return path;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QString RiaFilePathTools::relativePath(const QString& rootDir, const QString& dir)
QString RiaFilePathTools::relativePath( const QString& rootDir, const QString& dir )
{
if (dir.startsWith(rootDir))
if ( dir.startsWith( rootDir ) )
{
QString relPath = dir;
relPath.remove(0, rootDir.size());
relPath.remove( 0, rootDir.size() );
if (relPath.startsWith(SEPARATOR)) relPath.remove(0, 1);
return appendSeparatorIfNo(relPath);
if ( relPath.startsWith( SEPARATOR ) ) relPath.remove( 0, 1 );
return appendSeparatorIfNo( relPath );
}
else
{
@@ -78,87 +77,86 @@ QString RiaFilePathTools::relativePath(const QString& rootDir, const QString& di
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
bool RiaFilePathTools::equalPaths(const QString& path1, const QString& path2)
bool RiaFilePathTools::equalPaths( const QString& path1, const QString& path2 )
{
QString p1 = path1;
QString p2 = path2;
appendSeparatorIfNo(p1);
appendSeparatorIfNo(p2);
appendSeparatorIfNo( p1 );
appendSeparatorIfNo( p2 );
return p1 == p2;
}
//--------------------------------------------------------------------------------------------------
/// Own canonicalPath method since the QDir::canonicalPath seems to not work
//--------------------------------------------------------------------------------------------------
QString RiaFilePathTools::canonicalPath(const QString& path)
QString RiaFilePathTools::canonicalPath( const QString& path )
{
return QDir(path).absolutePath();
return QDir( path ).absolutePath();
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
std::pair<QString, QString> RiaFilePathTools::toFolderAndFileName(const QString& absFileName)
std::pair<QString, QString> RiaFilePathTools::toFolderAndFileName( const QString& absFileName )
{
auto absFN = toInternalSeparator(absFileName);
int lastSep = absFN.lastIndexOf(SEPARATOR);
if (lastSep > 0)
auto absFN = toInternalSeparator( absFileName );
int lastSep = absFN.lastIndexOf( SEPARATOR );
if ( lastSep > 0 )
{
return std::make_pair(absFN.left(lastSep), absFN.mid(lastSep+1));
return std::make_pair( absFN.left( lastSep ), absFN.mid( lastSep + 1 ) );
}
else
{
return std::make_pair("", absFN);
return std::make_pair( "", absFN );
}
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QString RiaFilePathTools::removeDuplicatePathSeparators(const QString& path)
QString RiaFilePathTools::removeDuplicatePathSeparators( const QString& path )
{
QString correctedPath = path;
int len;
int len;
do
{
len = correctedPath.size();
correctedPath.replace(QString("%1%1").arg(SEPARATOR), SEPARATOR);
} while (correctedPath.size() != len);
correctedPath.replace( QString( "%1%1" ).arg( SEPARATOR ), SEPARATOR );
} while ( correctedPath.size() != len );
return correctedPath;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QString RiaFilePathTools::rootSearchPathFromSearchFilter(const QString& searchFilter)
QString RiaFilePathTools::rootSearchPathFromSearchFilter( const QString& searchFilter )
{
std::set<QChar> globStartCharacters = {'*', '?', '['}; // ']' not needed
QStringList pathPartList = searchFilter.split(SEPARATOR);
QStringList pathPartList = searchFilter.split( SEPARATOR );
QStringList::iterator pathPartIt= pathPartList.begin();
QStringList::iterator pathPartIt = pathPartList.begin();
for ( ; pathPartIt != pathPartList.end(); ++pathPartIt)
for ( ; pathPartIt != pathPartList.end(); ++pathPartIt )
{
QString pathPart = *pathPartIt;
// Remove allowed escaping of wildcards
pathPart.replace("[[]", "");
pathPart.replace("[]]", "");
pathPart.replace("[?]", "");
pathPart.replace("[*]", "");
if (pathPart.contains("*")) break;
if (pathPart.contains("?")) break;
if (pathPart.contains("[")) break;
pathPart.replace( "[[]", "" );
pathPart.replace( "[]]", "" );
pathPart.replace( "[?]", "" );
pathPart.replace( "[*]", "" );
if ( pathPart.contains( "*" ) ) break;
if ( pathPart.contains( "?" ) ) break;
if ( pathPart.contains( "[" ) ) break;
}
pathPartList.erase(pathPartIt, pathPartList.end());
pathPartList.erase( pathPartIt, pathPartList.end() );
return pathPartList.join(SEPARATOR);
return pathPartList.join( SEPARATOR );
}

View File

@@ -3,30 +3,30 @@
// Copyright (C) 2011- Statoil ASA
// Copyright (C) 2013- Ceetron Solutions AS
// Copyright (C) 2011-2012 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>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
#pragma once
#include <QString>
#include <QByteArray>
#include <QString>
#include <string>
//==================================================================================================
//
//
//
//
//==================================================================================================
class RiaFilePathTools
@@ -34,12 +34,12 @@ class RiaFilePathTools
public:
static const QChar SEPARATOR;
static QString toInternalSeparator(const QString& path);
static QString& appendSeparatorIfNo(QString& path);
static QString relativePath(const QString& rootDir, const QString& dir);
static bool equalPaths(const QString& path1, const QString& path2);
static QString canonicalPath(const QString& path);
static std::pair<QString, QString> toFolderAndFileName(const QString& absFileName);
static QString removeDuplicatePathSeparators(const QString& path);
static QString rootSearchPathFromSearchFilter(const QString& searchFilter);
static QString toInternalSeparator( const QString& path );
static QString& appendSeparatorIfNo( QString& path );
static QString relativePath( const QString& rootDir, const QString& dir );
static bool equalPaths( const QString& path1, const QString& path2 );
static QString canonicalPath( const QString& path );
static std::pair<QString, QString> toFolderAndFileName( const QString& absFileName );
static QString removeDuplicatePathSeparators( const QString& path );
static QString rootSearchPathFromSearchFilter( const QString& searchFilter );
};

View File

@@ -26,8 +26,8 @@
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RiaGitDiff::RiaGitDiff(const QString& pathToDiffTool)
: m_pathToGitTool(pathToDiffTool)
RiaGitDiff::RiaGitDiff( const QString& pathToDiffTool )
: m_pathToGitTool( pathToDiffTool )
{
reset();
}
@@ -51,32 +51,32 @@ void RiaGitDiff::reset()
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool RiaGitDiff::executeDiff(const QString& baseFolder)
bool RiaGitDiff::executeDiff( const QString& baseFolder )
{
reset();
QString fullFilePath = "git";
if (!m_pathToGitTool.isEmpty())
if ( !m_pathToGitTool.isEmpty() )
{
fullFilePath = m_pathToGitTool + "/" + fullFilePath;
}
QString incomingCurrentPath = QDir::currentPath();
QDir::setCurrent(baseFolder);
QDir::setCurrent( baseFolder );
QString args = "diff";
QString completeCommand = QString("\"%1\" %2").arg(fullFilePath).arg(args);
QString completeCommand = QString( "\"%1\" %2" ).arg( fullFilePath ).arg( args );
// Launch process and wait
QProcess proc;
proc.start(completeCommand);
proc.waitForFinished(30000);
proc.start( completeCommand );
proc.waitForFinished( 30000 );
QDir::setCurrent(incomingCurrentPath);
QDir::setCurrent( incomingCurrentPath );
QProcess::ProcessError procError = proc.error();
if (procError != QProcess::UnknownError)
if ( procError != QProcess::UnknownError )
{
m_lastError = SEVERE_ERROR;
m_errorMsg = "Error running 'git' tool process";

View File

@@ -36,10 +36,10 @@ public:
};
public:
explicit RiaGitDiff(const QString& pathToGitTool);
explicit RiaGitDiff( const QString& pathToGitTool );
~RiaGitDiff();
bool executeDiff(const QString& baseFolder);
bool executeDiff( const QString& baseFolder );
ErrorType error() const;
QString errorMessage() const;
QString errorDetails() const;

View File

@@ -1,66 +1,66 @@
/////////////////////////////////////////////////////////////////////////////////
//
// 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>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
#include "RiaImageCompareReporter.h"
#include <iostream>
#include <fstream>
#include <QDir>
#include <fstream>
#include <iostream>
RiaImageCompareReporter::RiaImageCompareReporter(void)
RiaImageCompareReporter::RiaImageCompareReporter( void )
{
m_showOriginal = true;
m_showGenerated = true;
m_showOriginal = true;
m_showGenerated = true;
m_showInteractiveDiff = false;
}
RiaImageCompareReporter::~RiaImageCompareReporter(void)
{
}
RiaImageCompareReporter::~RiaImageCompareReporter( void ) {}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaImageCompareReporter::addImageDirectoryComparisonSet(const std::string& title, const std::string& baseImageDir, const std::string& newImagesDir, const std::string& diffImagesDir)
void RiaImageCompareReporter::addImageDirectoryComparisonSet( const std::string& title,
const std::string& baseImageDir,
const std::string& newImagesDir,
const std::string& diffImagesDir )
{
m_directorySets.push_back(DirSet(title, baseImageDir, newImagesDir, diffImagesDir));
m_directorySets.push_back( DirSet( title, baseImageDir, newImagesDir, diffImagesDir ) );
}
std::string removeCommonStart(const std::string& mask, const std::string& filename)
std::string removeCommonStart( const std::string& mask, const std::string& filename )
{
size_t i;
for (i = 0; i < mask.size() && i < filename.size(); ++i)
for ( i = 0; i < mask.size() && i < filename.size(); ++i )
{
if (mask[i] != filename[i]) break;
if ( mask[i] != filename[i] ) break;
}
return filename.substr(i);
return filename.substr( i );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaImageCompareReporter::generateHTMLReport(const std::string& fileName, const std::string& diff2htmlHeaderText)
void RiaImageCompareReporter::generateHTMLReport( const std::string& fileName, const std::string& diff2htmlHeaderText )
{
if (m_directorySets.size() == 0) return;
if ( m_directorySets.size() == 0 ) return;
std::ofstream output(fileName.c_str());
if (!output)
std::ofstream output( fileName.c_str() );
if ( !output )
{
std::cout << "Trouble opening test report file: " << fileName;
return;
@@ -71,7 +71,7 @@ void RiaImageCompareReporter::generateHTMLReport(const std::string& fileName, co
html += "<html>\n";
html += "<head>\n";
if (m_showInteractiveDiff)
if ( m_showInteractiveDiff )
{
html += cssString();
}
@@ -84,42 +84,48 @@ void RiaImageCompareReporter::generateHTMLReport(const std::string& fileName, co
html += "<title>Regression-Test Report</title>\n";
html += "\n";
for (size_t dsIdx = 0; dsIdx < m_directorySets.size(); ++dsIdx)
for ( size_t dsIdx = 0; dsIdx < m_directorySets.size(); ++dsIdx )
{
std::vector<std::string> baseImageNames = getPngFilesInDirectory(m_directorySets[dsIdx].m_baseImageDir);
std::vector<std::string> baseImageNames = getPngFilesInDirectory( m_directorySets[dsIdx].m_baseImageDir );
html += "<table>\n";
html += " <tr>\n";
html += " <td colspan=\"3\" bgcolor=\"darkblue\" height=\"40\"> <b><font color=\"white\" size=\"3\"> " + m_directorySets[dsIdx].m_title + " </font></b> </td>\n";
html += " <td colspan=\"3\" bgcolor=\"darkblue\" height=\"40\"> <b><font color=\"white\" size=\"3\"> " +
m_directorySets[dsIdx].m_title + " </font></b> </td>\n";
html += " </tr>\n";
std::string baseImageFolder = removeCommonStart(fileName, m_directorySets[dsIdx].m_baseImageDir );
std::string genImageFolder = removeCommonStart(fileName, m_directorySets[dsIdx].m_newImagesDir );
std::string diffImageFolder = removeCommonStart(fileName, m_directorySets[dsIdx].m_diffImagesDir);
std::string baseImageFolder = removeCommonStart( fileName, m_directorySets[dsIdx].m_baseImageDir );
std::string genImageFolder = removeCommonStart( fileName, m_directorySets[dsIdx].m_newImagesDir );
std::string diffImageFolder = removeCommonStart( fileName, m_directorySets[dsIdx].m_diffImagesDir );
for (size_t fIdx = 0; fIdx < baseImageNames.size(); ++fIdx)
for ( size_t fIdx = 0; fIdx < baseImageNames.size(); ++fIdx )
{
html += " <tr>\n";
html += " <td colspan=\"3\" bgcolor=\"lightgray\"> " + baseImageNames[fIdx] + "</td>\n";
html += " </tr>\n";
html += " <tr>\n";
if (m_showOriginal)
if ( m_showOriginal )
{
html += " <td> <img src=\"" + baseImageFolder + "/" + baseImageNames[fIdx] + "\" width=\"100%\" alt=\"" + baseImageFolder + "/" + baseImageNames[fIdx] + "\" > </td>\n";
html += " <td> <img src=\"" + baseImageFolder + "/" + baseImageNames[fIdx] +
"\" width=\"100%\" alt=\"" + baseImageFolder + "/" + baseImageNames[fIdx] + "\" > </td>\n";
}
if (m_showGenerated)
if ( m_showGenerated )
{
html += " <td> <img src=\"" + genImageFolder + "/" + baseImageNames[fIdx] + "\" width=\"100%\" alt=\"" + genImageFolder + "/" + baseImageNames[fIdx] + "\" > </td>\n";
html += " <td> <img src=\"" + genImageFolder + "/" + baseImageNames[fIdx] +
"\" width=\"100%\" alt=\"" + genImageFolder + "/" + baseImageNames[fIdx] + "\" > </td>\n";
}
if (m_showInteractiveDiff)
if ( m_showInteractiveDiff )
{
html += " <td> <div class = \"image-slider\"> <div> <img src=\"" + baseImageFolder + "/" + baseImageNames[fIdx] + "\" > </div> <img src = \"" + genImageFolder + "/" + baseImageNames[fIdx] + "\" > </div> </td>\n";
html += " <td> <div class = \"image-slider\"> <div> <img src=\"" + baseImageFolder + "/" +
baseImageNames[fIdx] + "\" > </div> <img src = \"" + genImageFolder + "/" +
baseImageNames[fIdx] + "\" > </div> </td>\n";
}
html += " <td> <img src=\"" + diffImageFolder + "/" + baseImageNames[fIdx] + "\" width=\"100%\" alt=\"" + diffImageFolder + "/" + baseImageNames[fIdx] + "\" > </td>\n";
html += " <td> <img src=\"" + diffImageFolder + "/" + baseImageNames[fIdx] +
"\" width=\"100%\" alt=\"" + diffImageFolder + "/" + baseImageNames[fIdx] + "\" > </td>\n";
html += " </tr>\n";
// A little air between images
@@ -135,12 +141,12 @@ void RiaImageCompareReporter::generateHTMLReport(const std::string& fileName, co
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaImageCompareReporter::showInteractiveOnly()
{
m_showOriginal = false;
m_showGenerated = false;
m_showOriginal = false;
m_showGenerated = false;
m_showInteractiveDiff = true;
}
@@ -148,28 +154,28 @@ void RiaImageCompareReporter::showInteractiveOnly()
/// Retuns the names of the *.png files in a directory. The names are without path, but with extention
//--------------------------------------------------------------------------------------------------
std::vector<std::string> RiaImageCompareReporter::getPngFilesInDirectory(const std::string& searchPath)
std::vector<std::string> RiaImageCompareReporter::getPngFilesInDirectory( const std::string& searchPath )
{
QDir searchDir(QString::fromStdString(searchPath));
QDir searchDir( QString::fromStdString( searchPath ) );
searchDir.setFilter(QDir::Files);
//QStringList filter;
//filter.append("*.png");
//searchDir.setNameFilters(filter);
searchDir.setFilter( QDir::Files );
// QStringList filter;
// filter.append("*.png");
// searchDir.setNameFilters(filter);
QStringList imageFiles = searchDir.entryList();
std::vector<std::string> fileNames;
for (int i = 0; i < imageFiles.size(); ++i)
for ( int i = 0; i < imageFiles.size(); ++i )
{
fileNames.push_back(imageFiles[i].toStdString());
fileNames.push_back( imageFiles[i].toStdString() );
}
return fileNames;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
std::string RiaImageCompareReporter::cssString() const
{
@@ -179,36 +185,36 @@ std::string RiaImageCompareReporter::cssString() const
html += "";
html += ".image-slider {";
html += "position:relative;";
html += "display: inline-block;";
html += "line-height: 0;";
html += "position:relative;";
html += "display: inline-block;";
html += "line-height: 0;";
html += "}";
html += ".image-slider > div {";
html += "position: absolute;";
html += "top: 0; bottom: 0; left: 0;";
html += "width: 25px;";
html += "max-width: 100%;";
html += "overflow: hidden;";
html += "resize: horizontal;";
html += "position: absolute;";
html += "top: 0; bottom: 0; left: 0;";
html += "width: 25px;";
html += "max-width: 100%;";
html += "overflow: hidden;";
html += "resize: horizontal;";
html += "}";
html += ".image-slider > div:before {";
html += "content: '';";
html += "position: absolute;";
html += "right: 0; bottom: 0;";
html += "width: 23px; height: 23px;";
html += "padding: 5px;";
html += "background: linear-gradient(-45deg, gray 50%, transparent 0);";
html += "background-clip: content-box;";
html += "cursor: ew-resize;";
html += "-webkit-filter: drop-shadow(0 0 6px black);";
html += "filter: drop-shadow(0 0 6px black);";
html += "content: '';";
html += "position: absolute;";
html += "right: 0; bottom: 0;";
html += "width: 23px; height: 23px;";
html += "padding: 5px;";
html += "background: linear-gradient(-45deg, gray 50%, transparent 0);";
html += "background-clip: content-box;";
html += "cursor: ew-resize;";
html += "-webkit-filter: drop-shadow(0 0 6px black);";
html += "filter: drop-shadow(0 0 6px black);";
html += "}";
html += ".image-slider img {";
html += "user-select: none;";
html += "max-width: 1000px;";
html += "user-select: none;";
html += "max-width: 1000px;";
html += "}";
html += "</style>";

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// 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>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -27,25 +27,31 @@ public:
RiaImageCompareReporter();
virtual ~RiaImageCompareReporter();
void addImageDirectoryComparisonSet(const std::string& title, const std::string& baseImageDir, const std::string& newImagesDir, const std::string& diffImagesDir );
void generateHTMLReport(const std::string& filenName, const std::string& pathToDiff2html);
void addImageDirectoryComparisonSet( const std::string& title,
const std::string& baseImageDir,
const std::string& newImagesDir,
const std::string& diffImagesDir );
void generateHTMLReport( const std::string& filenName, const std::string& pathToDiff2html );
void showInteractiveOnly();
private:
static std::vector<std::string> getPngFilesInDirectory(const std::string& searchPath);
std::string cssString() const;
static std::vector<std::string> getPngFilesInDirectory( const std::string& searchPath );
std::string cssString() const;
private:
struct DirSet
{
DirSet(const std::string& title, const std::string& baseImageDir, const std::string& newImagesDir, const std::string& diffImagesDir )
: m_title(title),
m_baseImageDir(baseImageDir),
m_newImagesDir(newImagesDir),
m_diffImagesDir(diffImagesDir)
{}
DirSet( const std::string& title,
const std::string& baseImageDir,
const std::string& newImagesDir,
const std::string& diffImagesDir )
: m_title( title )
, m_baseImageDir( baseImageDir )
, m_newImagesDir( newImagesDir )
, m_diffImagesDir( diffImagesDir )
{
}
std::string m_title;
std::string m_baseImageDir;
@@ -59,4 +65,3 @@ private:
bool m_showGenerated;
bool m_showInteractiveDiff;
};

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// 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>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -19,89 +19,89 @@
#include "RiaImageFileCompare.h"
#include <QtCore/QProcess>
//==================================================================================================
//
//
//
//
//==================================================================================================
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
RiaImageFileCompare::RiaImageFileCompare(QString compareExecutable)
: m_compareExecutable(compareExecutable)
RiaImageFileCompare::RiaImageFileCompare( QString compareExecutable )
: m_compareExecutable( compareExecutable )
{
reset();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RiaImageFileCompare::~RiaImageFileCompare() {}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RiaImageFileCompare::~RiaImageFileCompare()
{
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaImageFileCompare::reset()
{
m_imagesEqual = false;
m_lastError = IC_NO_ERROR;
m_errorMsg = "";
m_imagesEqual = false;
m_lastError = IC_NO_ERROR;
m_errorMsg = "";
m_errorDetails = "";
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
bool RiaImageFileCompare::runComparison(QString imgFileName, QString refFileName, QString diffFileName)
bool RiaImageFileCompare::runComparison( QString imgFileName, QString refFileName, QString diffFileName )
{
reset();
if (m_compareExecutable.isEmpty())
if ( m_compareExecutable.isEmpty() )
{
m_lastError = SEVERE_ERROR;
m_errorMsg = "Cannot compare images, no compare executable set";
m_errorMsg = "Cannot compare images, no compare executable set";
return false;
}
//QString args = QString("-fuzz 2% -lowlight-color white -metric ae \"%1\" \"%2\" \"%3\"").arg(imgFileName).arg(refFileName).arg((diffFileName));
// QString args = QString("-fuzz 2% -lowlight-color white -metric ae \"%1\" \"%2\"
// \"%3\"").arg(imgFileName).arg(refFileName).arg((diffFileName));
// The ImageMagick compare tool on RedHat 5 does not support the lowlight-color options
// Use GCC version as a crude mechanism for disabling use of this option on RedHat5
#if (__GNUC__ == 4 && __GNUC_MINOR__ <= 1)
QString args = QString("-fuzz 0.4% -metric ae \"%1\" \"%2\" \"%3\"").arg(imgFileName).arg(refFileName).arg((diffFileName));
#if ( __GNUC__ == 4 && __GNUC_MINOR__ <= 1 )
QString args = QString( "-fuzz 0.4% -metric ae \"%1\" \"%2\" \"%3\"" )
.arg( imgFileName )
.arg( refFileName )
.arg( ( diffFileName ) );
#else
QString args = QString("-fuzz 0.4% -lowlight-color white -metric ae \"%1\" \"%2\" \"%3\"").arg(imgFileName).arg(refFileName).arg((diffFileName));
QString args = QString( "-fuzz 0.4% -lowlight-color white -metric ae \"%1\" \"%2\" \"%3\"" )
.arg( imgFileName )
.arg( refFileName )
.arg( ( diffFileName ) );
#endif
QString completeCommand = QString("\"%1\" %2").arg(m_compareExecutable).arg(args);
QString completeCommand = QString( "\"%1\" %2" ).arg( m_compareExecutable ).arg( args );
// Launch process and wait
QProcess proc;
proc.start(completeCommand);
proc.waitForFinished(30000);
proc.start( completeCommand );
proc.waitForFinished( 30000 );
QProcess::ProcessError procError = proc.error();
if (procError != QProcess::UnknownError)
if ( procError != QProcess::UnknownError )
{
m_lastError = SEVERE_ERROR;
m_errorMsg = "Error running compare tool process";
m_lastError = SEVERE_ERROR;
m_errorMsg = "Error running compare tool process";
m_errorDetails = completeCommand;
return false;
}
QByteArray stdErr = proc.readAllStandardError();
int procExitCode = proc.exitCode();
if (procExitCode == 0)
QByteArray stdErr = proc.readAllStandardError();
int procExitCode = proc.exitCode();
if ( procExitCode == 0 )
{
// Strip out whitespace and look for 0 (as in zero pixel differences)
stdErr = stdErr.simplified();
if (!stdErr.isEmpty() && stdErr[0] == '0')
if ( !stdErr.isEmpty() && stdErr[0] == '0' )
{
m_imagesEqual = true;
}
@@ -111,44 +111,40 @@ bool RiaImageFileCompare::runComparison(QString imgFileName, QString refFileName
else
{
// Report non-severe error
m_lastError = IC_ERROR;
m_errorMsg = "Error running compare tool process";
m_lastError = IC_ERROR;
m_errorMsg = "Error running compare tool process";
m_errorDetails = stdErr;
return false;
}
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
bool RiaImageFileCompare::imagesEqual() const
{
return m_imagesEqual;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
RiaImageFileCompare::ErrorType RiaImageFileCompare::error() const
{
return m_lastError;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QString RiaImageFileCompare::errorMessage() const
{
return m_errorMsg;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QString RiaImageFileCompare::errorDetails() const
{

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// 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>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -30,31 +30,28 @@ class RiaImageFileCompare
public:
enum ErrorType
{
IC_NO_ERROR, // No error occurred
IC_ERROR, // An error occurred
SEVERE_ERROR // Severe error occurred, it is likely that another call to compare() will also fail
IC_NO_ERROR, // No error occurred
IC_ERROR, // An error occurred
SEVERE_ERROR // Severe error occurred, it is likely that another call to compare() will also fail
};
public:
explicit RiaImageFileCompare(QString compareExecutable);
explicit RiaImageFileCompare( QString compareExecutable );
~RiaImageFileCompare();
bool runComparison(QString imgFileName, QString refFileName, QString diffFileName);
bool imagesEqual() const;
ErrorType error() const;
QString errorMessage() const;
QString errorDetails() const;
bool runComparison( QString imgFileName, QString refFileName, QString diffFileName );
bool imagesEqual() const;
ErrorType error() const;
QString errorMessage() const;
QString errorDetails() const;
private:
void reset();
void reset();
private:
QString m_compareExecutable; // The executable for the ImageMagick compare tool
bool m_imagesEqual; // Result of last comparison
ErrorType m_lastError; // Error for last execution
QString m_errorMsg;
QString m_errorDetails;
QString m_compareExecutable; // The executable for the ImageMagick compare tool
bool m_imagesEqual; // Result of last comparison
ErrorType m_lastError; // Error for last execution
QString m_errorMsg;
QString m_errorDetails;
};

View File

@@ -14,13 +14,13 @@
/// http://fab.cba.mit.edu/classes/S62.12/docs/Meijster_distance.pdf
/// Currently Euclidean only, but can be easily extended by replacing the lambda functions.
//--------------------------------------------------------------------------------------------------
void RiaImageTools::distanceTransform2d(std::vector<std::vector<unsigned int>>& image)
void RiaImageTools::distanceTransform2d( std::vector<std::vector<unsigned int>>& image )
{
if (image.empty())
if ( image.empty() )
{
return;
}
if (image.front().empty())
if ( image.front().empty() )
{
return;
}
@@ -28,22 +28,22 @@ void RiaImageTools::distanceTransform2d(std::vector<std::vector<unsigned int>>&
const int64_t N = (int64_t)image.front().size();
int64_t infVal = M + N;
CVF_ASSERT(infVal <= std::numeric_limits<unsigned int>::max());
CVF_ASSERT( infVal <= std::numeric_limits<unsigned int>::max() );
// First phase
std::vector<std::vector<int64_t>> g(M);
std::vector<std::vector<int64_t>> g( M );
#pragma omp parallel for
for (int64_t x = 0; x < M; ++x)
for ( int64_t x = 0; x < M; ++x )
{
g[x].resize(N, infVal);
if (image[x][0])
g[x].resize( N, infVal );
if ( image[x][0] )
{
g[x][0] = 0;
}
for (int64_t y = 1; y < N - 1; ++y)
for ( int64_t y = 1; y < N - 1; ++y )
{
if (image[x][y])
if ( image[x][y] )
{
g[x][y] = 0;
}
@@ -52,50 +52,50 @@ void RiaImageTools::distanceTransform2d(std::vector<std::vector<unsigned int>>&
g[x][y] = 1 + g[x][y - 1];
}
}
for (int64_t y = N - 2; y >= 0; --y)
for ( int64_t y = N - 2; y >= 0; --y )
{
if (g[x][y + 1] < g[x][y])
if ( g[x][y + 1] < g[x][y] )
{
g[x][y] = 1 + g[x][y + 1];
}
}
}
auto f = [](int64_t x, int64_t i, const std::vector<std::vector<int64_t>>& g, int64_t y) {
return (x - i) * (x - i) + g[i][y] * g[i][y];
auto f = []( int64_t x, int64_t i, const std::vector<std::vector<int64_t>>& g, int64_t y ) {
return ( x - i ) * ( x - i ) + g[i][y] * g[i][y];
};
auto sep = [](int64_t i, int64_t u, const std::vector<std::vector<int64_t>>& g, int64_t y) {
if (i == u) return (int64_t)0;
auto sep = []( int64_t i, int64_t u, const std::vector<std::vector<int64_t>>& g, int64_t y ) {
if ( i == u ) return (int64_t)0;
int64_t numerator = u * u - i * i + g[u][y] * g[u][y] - g[i][y] * g[i][y];
int64_t divisor = 2 * (u - i);
int64_t divisor = 2 * ( u - i );
return numerator / divisor;
};
// Second phase
#pragma omp parallel for
for (int64_t y = 0; y < N; ++y)
for ( int64_t y = 0; y < N; ++y )
{
int64_t q = 0;
std::vector<int64_t> s(std::max(N, M), (int64_t) 0);
std::vector<int64_t> t(std::max(N, M), (int64_t) 0);
int64_t q = 0;
std::vector<int64_t> s( std::max( N, M ), (int64_t)0 );
std::vector<int64_t> t( std::max( N, M ), (int64_t)0 );
for (int64_t u = 1; u < M - 1; ++u)
for ( int64_t u = 1; u < M - 1; ++u )
{
while (q >= 0 && f(t[q], s[q], g, y) > f(t[q], u, g, y))
while ( q >= 0 && f( t[q], s[q], g, y ) > f( t[q], u, g, y ) )
{
q--;
}
if (q < 0)
if ( q < 0 )
{
q = 0;
s[0] = u;
}
else
{
int64_t w = 1 + sep((int64_t)s[q], u, g, y);
if (w < M)
int64_t w = 1 + sep( (int64_t)s[q], u, g, y );
if ( w < M )
{
q++;
s[q] = u;
@@ -103,12 +103,12 @@ void RiaImageTools::distanceTransform2d(std::vector<std::vector<unsigned int>>&
}
}
}
for (int64_t u = M - 1; u >= 0; --u)
for ( int64_t u = M - 1; u >= 0; --u )
{
int64_t fVal = f(u, s[q], g, y);
CVF_ASSERT(fVal <= std::numeric_limits<double>::max());
image[u][y] = static_cast<unsigned int>(fVal);
if (u == t[q])
int64_t fVal = f( u, s[q], g, y );
CVF_ASSERT( fVal <= std::numeric_limits<double>::max() );
image[u][y] = static_cast<unsigned int>( fVal );
if ( u == t[q] )
{
q = q - 1;
}
@@ -119,18 +119,17 @@ void RiaImageTools::distanceTransform2d(std::vector<std::vector<unsigned int>>&
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaImageTools::makeGrayScale(QImage& image)
void RiaImageTools::makeGrayScale( QImage& image )
{
for (int i = 0; i < image.height(); i++)
for ( int i = 0; i < image.height(); i++ )
{
uchar* scanLine = image.scanLine(i);
for (int j = 0; j < image.width(); j++)
uchar* scanLine = image.scanLine( i );
for ( int j = 0; j < image.width(); j++ )
{
QRgb* pixel = reinterpret_cast<QRgb*>(scanLine + j * 4);
int gray = qGray(*pixel);
int alpha = qAlpha(*pixel);
*pixel = QColor(gray, gray, gray, alpha).rgba();
QRgb* pixel = reinterpret_cast<QRgb*>( scanLine + j * 4 );
int gray = qGray( *pixel );
int alpha = qAlpha( *pixel );
*pixel = QColor( gray, gray, gray, alpha ).rgba();
}
}
}

View File

@@ -25,8 +25,6 @@ class QImage;
class RiaImageTools
{
public:
static void distanceTransform2d(std::vector<std::vector<unsigned int>>& image);
static void makeGrayScale(QImage& image);
static void distanceTransform2d( std::vector<std::vector<unsigned int>>& image );
static void makeGrayScale( QImage& image );
};

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017 Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE.
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -20,8 +20,8 @@
#include "ApplicationCommands/RicShowMainWindowFeature.h"
#include "SummaryPlotCommands/RicNewSummaryPlotFeature.h"
#include "SummaryPlotCommands/RicNewSummaryCurveFeature.h"
#include "SummaryPlotCommands/RicNewSummaryPlotFeature.h"
#include "SummaryPlotCommands/RicSummaryPlotFeatureImpl.h"
#include "RiaApplication.h"
@@ -61,85 +61,88 @@
#include "RiuPlotMainWindow.h"
#include "RiuPlotMainWindowTools.h"
#include "cafUtils.h"
#include "cafProgressInfo.h"
#include "cafUtils.h"
#include <QFileInfo>
#include <QMessageBox>
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
bool RiaImportEclipseCaseTools::openEclipseCasesFromFile(const QStringList& fileNames, FileCaseIdMap* openedFilesOut, bool noDialog)
bool RiaImportEclipseCaseTools::openEclipseCasesFromFile( const QStringList& fileNames,
FileCaseIdMap* openedFilesOut,
bool noDialog )
{
RiaApplication* app = RiaApplication::instance();
RimProject* project = app->project();
RiaApplication* app = RiaApplication::instance();
RimProject* project = app->project();
// Get list of files to import
RifSummaryCaseRestartSelector selector;
if(noDialog) selector.showDialog(false);
selector.determineFilesToImportFromGridFiles(fileNames);
if ( noDialog ) selector.showDialog( false );
selector.determineFilesToImportFromGridFiles( fileNames );
std::vector<RifSummaryCaseFileResultInfo> summaryFileInfos = selector.summaryFileInfos();
FileCaseIdMap openedFiles;
// Import eclipse case files
for (const QString& gridCaseFile : selector.gridCaseFiles())
for ( const QString& gridCaseFile : selector.gridCaseFiles() )
{
int caseId = RiaImportEclipseCaseTools::openEclipseCaseFromFile(gridCaseFile);
if (caseId >= 0)
int caseId = RiaImportEclipseCaseTools::openEclipseCaseFromFile( gridCaseFile );
if ( caseId >= 0 )
{
openedFiles.insert(std::make_pair(gridCaseFile, caseId));
openedFiles.insert( std::make_pair( gridCaseFile, caseId ) );
}
}
// Import summary cases
if (!summaryFileInfos.empty())
if ( !summaryFileInfos.empty() )
{
RimSummaryCaseMainCollection* sumCaseColl = project->activeOilField() ? project->activeOilField()->summaryCaseMainCollection() : nullptr;
if (sumCaseColl)
RimSummaryCaseMainCollection* sumCaseColl = project->activeOilField()
? project->activeOilField()->summaryCaseMainCollection()
: nullptr;
if ( sumCaseColl )
{
std::vector<RimSummaryCase*> newSumCases = sumCaseColl->createSummaryCasesFromFileInfos(summaryFileInfos);
for (RimSummaryCase* newSumCase : newSumCases)
std::vector<RimSummaryCase*> newSumCases = sumCaseColl->createSummaryCasesFromFileInfos( summaryFileInfos );
for ( RimSummaryCase* newSumCase : newSumCases )
{
RimSummaryCaseCollection* existingCollection = nullptr;
QString gridCaseFile = RifEclipseSummaryTools::findGridCaseFileFromSummaryHeaderFile(newSumCase->summaryHeaderFilename());
RimEclipseCase* gridCase = project->eclipseCaseFromGridFileName(gridCaseFile);
if (gridCase)
QString gridCaseFile = RifEclipseSummaryTools::findGridCaseFileFromSummaryHeaderFile(
newSumCase->summaryHeaderFilename() );
RimEclipseCase* gridCase = project->eclipseCaseFromGridFileName( gridCaseFile );
if ( gridCase )
{
RimSummaryCase* existingSummaryCase = sumCaseColl->findSummaryCaseFromFileName(newSumCase->summaryHeaderFilename());
RimGridSummaryCase* existingGridSummaryCase = dynamic_cast<RimGridSummaryCase*>(existingSummaryCase);
RimFileSummaryCase* existingFileSummaryCase = dynamic_cast<RimFileSummaryCase*>(existingSummaryCase);
if (existingGridSummaryCase)
RimSummaryCase* existingSummaryCase = sumCaseColl->findSummaryCaseFromFileName(
newSumCase->summaryHeaderFilename() );
RimGridSummaryCase* existingGridSummaryCase = dynamic_cast<RimGridSummaryCase*>( existingSummaryCase );
RimFileSummaryCase* existingFileSummaryCase = dynamic_cast<RimFileSummaryCase*>( existingSummaryCase );
if ( existingGridSummaryCase )
{
delete newSumCase; // No need to add anything new. Already have one.
continue;
}
else if (existingFileSummaryCase)
else if ( existingFileSummaryCase )
{
existingFileSummaryCase->firstAncestorOrThisOfType(existingCollection);
existingFileSummaryCase->firstAncestorOrThisOfType( existingCollection );
// Replace all occurrences of file sum with ecl sum
std::vector<RimSummaryCurve*> objects;
existingFileSummaryCase->objectsWithReferringPtrFieldsOfType(objects);
existingFileSummaryCase->objectsWithReferringPtrFieldsOfType( objects );
// UI settings of a curve filter is updated based
// on the new case association for the curves in the curve filter
// UI is updated by loadDataAndUpdate()
for (RimSummaryCurve* summaryCurve : objects)
for ( RimSummaryCurve* summaryCurve : objects )
{
if (summaryCurve)
if ( summaryCurve )
{
RimSummaryCurveCollection* parentCollection = nullptr;
summaryCurve->firstAncestorOrThisOfType(parentCollection);
if (parentCollection)
summaryCurve->firstAncestorOrThisOfType( parentCollection );
if ( parentCollection )
{
parentCollection->loadDataAndUpdate(true);
parentCollection->loadDataAndUpdate( true );
parentCollection->updateConnectedEditors();
break;
}
@@ -147,43 +150,43 @@ bool RiaImportEclipseCaseTools::openEclipseCasesFromFile(const QStringList& file
}
// Remove existing case
sumCaseColl->removeCase(existingFileSummaryCase);
sumCaseColl->removeCase( existingFileSummaryCase );
delete existingFileSummaryCase;
}
}
if (existingCollection)
if ( existingCollection )
{
existingCollection->addCase(newSumCase);
existingCollection->addCase( newSumCase );
}
else
{
sumCaseColl->addCase(newSumCase);
sumCaseColl->addCase( newSumCase );
}
sumCaseColl->updateAllRequiredEditors();
}
if (!newSumCases.empty())
if ( !newSumCases.empty() )
{
RimSummaryPlotCollection* summaryPlotColl = project->mainPlotCollection()->summaryPlotCollection();
RicSummaryPlotFeatureImpl::ensureAtLeastOnePlot(summaryPlotColl, newSumCases.front());
RicSummaryPlotFeatureImpl::ensureAtLeastOnePlot( summaryPlotColl, newSumCases.front() );
RiuPlotMainWindowTools::setExpanded(newSumCases.front());
RiuPlotMainWindowTools::setExpanded( newSumCases.front() );
}
}
}
if (selector.foundErrors())
if ( selector.foundErrors() )
{
QString errorMessage = selector.createCombinedErrorMessage();
RiaLogging::error(errorMessage);
RiaLogging::error( errorMessage );
}
project->activeOilField()->completionTemplateCollection()->setDefaultUnitSystemBasedOnLoadedCases();
RiuPlotMainWindowTools::refreshToolbars();
RiuPlotMainWindowTools::refreshToolbars();
if (openedFilesOut)
if ( openedFilesOut )
{
*openedFilesOut = openedFiles;
}
@@ -192,65 +195,67 @@ bool RiaImportEclipseCaseTools::openEclipseCasesFromFile(const QStringList& file
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
int RiaImportEclipseCaseTools::openEclipseCaseFromFile(const QString& fileName)
int RiaImportEclipseCaseTools::openEclipseCaseFromFile( const QString& fileName )
{
if (!caf::Utils::fileExists(fileName)) return -1;
if ( !caf::Utils::fileExists( fileName ) ) return -1;
return RiaImportEclipseCaseTools::openEclipseCaseShowTimeStepFilterImpl(fileName, false);
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool RiaImportEclipseCaseTools::openEclipseCaseShowTimeStepFilter(const QString& fileName)
{
if (!caf::Utils::fileExists(fileName)) return false;
return RiaImportEclipseCaseTools::openEclipseCaseShowTimeStepFilterImpl(fileName, true) >= 0;
return RiaImportEclipseCaseTools::openEclipseCaseShowTimeStepFilterImpl( fileName, false );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool RiaImportEclipseCaseTools::openEclipseInputCaseFromFileNames(const QStringList& fileNames, QString* fileContainingGrid/*=nullptr*/)
bool RiaImportEclipseCaseTools::openEclipseCaseShowTimeStepFilter( const QString& fileName )
{
if ( !caf::Utils::fileExists( fileName ) ) return false;
return RiaImportEclipseCaseTools::openEclipseCaseShowTimeStepFilterImpl( fileName, true ) >= 0;
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool RiaImportEclipseCaseTools::openEclipseInputCaseFromFileNames( const QStringList& fileNames,
QString* fileContainingGrid /*=nullptr*/ )
{
RimEclipseInputCase* rimInputReservoir = new RimEclipseInputCase();
RiaApplication* app = RiaApplication::instance();
RimProject* project = app->project();
project->assignCaseIdToCase(rimInputReservoir);
project->assignCaseIdToCase( rimInputReservoir );
bool gridImportSuccess = rimInputReservoir->openDataFileSet(fileNames);
if (!gridImportSuccess)
bool gridImportSuccess = rimInputReservoir->openDataFileSet( fileNames );
if ( !gridImportSuccess )
{
RiaLogging::error("Failed to import grid");
RiaLogging::error( "Failed to import grid" );
return false;
}
RimEclipseCaseCollection* analysisModels = project->activeOilField() ? project->activeOilField()->analysisModels() : nullptr;
if (analysisModels == nullptr) return false;
RimEclipseCaseCollection* analysisModels = project->activeOilField() ? project->activeOilField()->analysisModels()
: nullptr;
if ( analysisModels == nullptr ) return false;
analysisModels->cases.push_back(rimInputReservoir);
analysisModels->cases.push_back( rimInputReservoir );
RimEclipseView* riv = rimInputReservoir->createAndAddReservoirView();
riv->cellResult()->setResultType(RiaDefines::INPUT_PROPERTY);
riv->cellResult()->setResultType( RiaDefines::INPUT_PROPERTY );
riv->loadDataAndUpdate();
if (!riv->cellResult()->hasResult())
if ( !riv->cellResult()->hasResult() )
{
riv->cellResult()->setResultVariable(RiaDefines::undefinedResultName());
riv->cellResult()->setResultVariable( RiaDefines::undefinedResultName() );
}
analysisModels->updateConnectedEditors();
Riu3DMainWindowTools::selectAsCurrentItem(riv->cellResult());
Riu3DMainWindowTools::selectAsCurrentItem( riv->cellResult() );
if (fileContainingGrid)
if ( fileContainingGrid )
{
*fileContainingGrid = rimInputReservoir->gridFileName();
}
@@ -259,44 +264,45 @@ bool RiaImportEclipseCaseTools::openEclipseInputCaseFromFileNames(const QStringL
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
bool RiaImportEclipseCaseTools::openMockModel(const QString& name)
bool RiaImportEclipseCaseTools::openMockModel( const QString& name )
{
return RiaImportEclipseCaseTools::openEclipseCaseShowTimeStepFilterImpl(name, false);
return RiaImportEclipseCaseTools::openEclipseCaseShowTimeStepFilterImpl( name, false );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
int RiaImportEclipseCaseTools::openEclipseCaseShowTimeStepFilterImpl(const QString& fileName, bool showTimeStepFilter)
int RiaImportEclipseCaseTools::openEclipseCaseShowTimeStepFilterImpl( const QString& fileName, bool showTimeStepFilter )
{
QFileInfo gridFileName(fileName);
QString caseName = gridFileName.completeBaseName();
QFileInfo gridFileName( fileName );
QString caseName = gridFileName.completeBaseName();
RimEclipseResultCase* rimResultReservoir = new RimEclipseResultCase();
rimResultReservoir->setCaseInfo(caseName, fileName);
rimResultReservoir->setCaseInfo( caseName, fileName );
RiaApplication* app = RiaApplication::instance();
RimProject* project = app->project();
RiaApplication* app = RiaApplication::instance();
RimProject* project = app->project();
RimEclipseCaseCollection* analysisModels = project->activeOilField() ? project->activeOilField()->analysisModels() : nullptr;
if (analysisModels == nullptr)
RimEclipseCaseCollection* analysisModels = project->activeOilField() ? project->activeOilField()->analysisModels()
: nullptr;
if ( analysisModels == nullptr )
{
delete rimResultReservoir;
return -1;
}
if (RiaGuiApplication::isRunning())
if ( RiaGuiApplication::isRunning() )
{
RicShowMainWindowFeature::showMainWindow();
}
analysisModels->cases.push_back(rimResultReservoir);
analysisModels->cases.push_back( rimResultReservoir );
if (!rimResultReservoir->importGridAndResultMetaData(showTimeStepFilter))
if ( !rimResultReservoir->importGridAndResultMetaData( showTimeStepFilter ) )
{
analysisModels->removeCaseFromAllGroups(rimResultReservoir);
analysisModels->removeCaseFromAllGroups( rimResultReservoir );
delete rimResultReservoir;
@@ -307,86 +313,87 @@ int RiaImportEclipseCaseTools::openEclipseCaseShowTimeStepFilterImpl(const QStri
riv->loadDataAndUpdate();
if (!riv->cellResult()->hasResult())
if ( !riv->cellResult()->hasResult() )
{
riv->cellResult()->setResultVariable(RiaDefines::undefinedResultName());
riv->cellResult()->setResultVariable( RiaDefines::undefinedResultName() );
}
analysisModels->updateConnectedEditors();
if (RiaGuiApplication::isRunning())
if ( RiaGuiApplication::isRunning() )
{
RiuMainWindow::instance()->selectAsCurrentItem(riv->cellResult());
RiuMainWindow::instance()->selectAsCurrentItem( riv->cellResult() );
}
return rimResultReservoir->caseId();
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
bool RiaImportEclipseCaseTools::addEclipseCases(const QStringList& fileNames, RimIdenticalGridCaseGroup** resultingCaseGroup/*=nullptr*/)
bool RiaImportEclipseCaseTools::addEclipseCases( const QStringList& fileNames,
RimIdenticalGridCaseGroup** resultingCaseGroup /*=nullptr*/ )
{
if (fileNames.size() == 0) return true;
if ( fileNames.size() == 0 ) return true;
// First file is read completely including grid.
// The main grid from the first case is reused directly in for the other cases.
// The main grid from the first case is reused directly in for the other cases.
// When reading active cell info, only the total cell count is tested for consistency
RimEclipseResultCase* mainResultCase = nullptr;
std::vector< std::vector<int> > mainCaseGridDimensions;
RimIdenticalGridCaseGroup* gridCaseGroup = nullptr;
RimEclipseResultCase* mainResultCase = nullptr;
std::vector<std::vector<int>> mainCaseGridDimensions;
RimIdenticalGridCaseGroup* gridCaseGroup = nullptr;
RiaApplication* app = RiaApplication::instance();
RimProject* project = app->project();
RiaApplication* app = RiaApplication::instance();
RimProject* project = app->project();
{
QString firstFileName = fileNames[0];
QFileInfo gridFileName(firstFileName);
QString firstFileName = fileNames[0];
QFileInfo gridFileName( firstFileName );
QString caseName = gridFileName.completeBaseName();
RimEclipseResultCase* rimResultReservoir = new RimEclipseResultCase();
rimResultReservoir->setCaseInfo(caseName, firstFileName);
if (!rimResultReservoir->openEclipseGridFile())
rimResultReservoir->setCaseInfo( caseName, firstFileName );
if ( !rimResultReservoir->openEclipseGridFile() )
{
delete rimResultReservoir;
return false;
}
rimResultReservoir->readGridDimensions(mainCaseGridDimensions);
rimResultReservoir->readGridDimensions( mainCaseGridDimensions );
mainResultCase = rimResultReservoir;
mainResultCase = rimResultReservoir;
RimOilField* oilField = project->activeOilField();
if (oilField && oilField->analysisModels())
if ( oilField && oilField->analysisModels() )
{
gridCaseGroup = oilField->analysisModels->createIdenticalCaseGroupFromMainCase(mainResultCase);
gridCaseGroup = oilField->analysisModels->createIdenticalCaseGroupFromMainCase( mainResultCase );
}
}
caf::ProgressInfo info(fileNames.size(), "Reading Active Cell data");
caf::ProgressInfo info( fileNames.size(), "Reading Active Cell data" );
for (int i = 1; i < fileNames.size(); i++)
for ( int i = 1; i < fileNames.size(); i++ )
{
QString caseFileName = fileNames[i];
QFileInfo gridFileName(caseFileName);
QString caseFileName = fileNames[i];
QFileInfo gridFileName( caseFileName );
QString caseName = gridFileName.completeBaseName();
RimEclipseResultCase* rimResultReservoir = new RimEclipseResultCase();
rimResultReservoir->setCaseInfo(caseName, caseFileName);
rimResultReservoir->setCaseInfo( caseName, caseFileName );
std::vector< std::vector<int> > caseGridDimensions;
rimResultReservoir->readGridDimensions(caseGridDimensions);
std::vector<std::vector<int>> caseGridDimensions;
rimResultReservoir->readGridDimensions( caseGridDimensions );
bool identicalGrid = RigGridManager::isGridDimensionsEqual(mainCaseGridDimensions, caseGridDimensions);
if (identicalGrid)
bool identicalGrid = RigGridManager::isGridDimensionsEqual( mainCaseGridDimensions, caseGridDimensions );
if ( identicalGrid )
{
if (rimResultReservoir->openAndReadActiveCellData(mainResultCase->eclipseCaseData()))
if ( rimResultReservoir->openAndReadActiveCellData( mainResultCase->eclipseCaseData() ) )
{
RimOilField* oilField = project->activeOilField();
if (oilField && oilField->analysisModels())
if ( oilField && oilField->analysisModels() )
{
oilField->analysisModels()->insertCaseInCaseGroup(gridCaseGroup, rimResultReservoir);
oilField->analysisModels()->insertCaseInCaseGroup( gridCaseGroup, rimResultReservoir );
}
}
else
@@ -399,15 +406,15 @@ bool RiaImportEclipseCaseTools::addEclipseCases(const QStringList& fileNames, Ri
delete rimResultReservoir;
}
info.setProgress(i);
info.setProgress( i );
}
if (gridCaseGroup)
if ( gridCaseGroup )
{
// Create placeholder results and propagate results info from main case to all other cases
// Create placeholder results and propagate results info from main case to all other cases
gridCaseGroup->loadMainCaseAndActiveCellInfo();
if (resultingCaseGroup)
if ( resultingCaseGroup )
{
*resultingCaseGroup = gridCaseGroup;
}
@@ -415,11 +422,11 @@ bool RiaImportEclipseCaseTools::addEclipseCases(const QStringList& fileNames, Ri
project->activeOilField()->analysisModels()->updateConnectedEditors();
if (RiaGuiApplication::isRunning() && gridCaseGroup && gridCaseGroup->statisticsCaseCollection()->reservoirs.size() > 0)
if ( RiaGuiApplication::isRunning() && gridCaseGroup &&
gridCaseGroup->statisticsCaseCollection()->reservoirs.size() > 0 )
{
RiuMainWindow::instance()->selectAsCurrentItem(gridCaseGroup->statisticsCaseCollection()->reservoirs[0]);
RiuMainWindow::instance()->selectAsCurrentItem( gridCaseGroup->statisticsCaseCollection()->reservoirs[0] );
}
return true;
}

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017 Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE.
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -26,23 +26,24 @@ class QStringList;
class RimIdenticalGridCaseGroup;
//==================================================================================================
///
///
//==================================================================================================
class RiaImportEclipseCaseTools
{
public:
typedef std::map<QString, int> FileCaseIdMap;
static bool openEclipseCasesFromFile(const QStringList& fileNames, FileCaseIdMap* openedFilesOut = nullptr, bool noDialog = false);
static bool openEclipseCaseShowTimeStepFilter(const QString& fileName);
static bool openEclipseInputCaseFromFileNames(const QStringList& fileNames, QString* fileContainingGrid = nullptr);
static bool openMockModel(const QString& name);
static bool addEclipseCases(const QStringList& fileNames, RimIdenticalGridCaseGroup** resultingCaseGroup = nullptr);
static bool openEclipseCasesFromFile( const QStringList& fileNames,
FileCaseIdMap* openedFilesOut = nullptr,
bool noDialog = false );
static bool openEclipseCaseShowTimeStepFilter( const QString& fileName );
static bool openEclipseInputCaseFromFileNames( const QStringList& fileNames, QString* fileContainingGrid = nullptr );
static bool openMockModel( const QString& name );
static bool addEclipseCases( const QStringList& fileNames, RimIdenticalGridCaseGroup** resultingCaseGroup = nullptr );
private:
static int openEclipseCaseFromFile(const QString& fileName);
static int openEclipseCaseShowTimeStepFilterImpl(const QString& fileName, bool showTimeStepFilter);
static int openEclipseCaseFromFile( const QString& fileName );
static int openEclipseCaseShowTimeStepFilterImpl( const QString& fileName, bool showTimeStepFilter );
};

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017 Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE.
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -22,26 +22,24 @@
#include <sstream>
#ifdef WIN32
#pragma warning (push)
#pragma warning (disable: 4668)
#pragma warning( push )
#pragma warning( disable : 4668 )
// Define this one to tell windows.h to not define min() and max() as macros
#if defined WIN32 && !defined NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#pragma warning (pop)
#pragma warning( pop )
#else
#include <cstring>
#include <cstdio>
#include <cstring>
#endif
#include "QString"
//==================================================================================================
//
//
//
//
//==================================================================================================
class RiaDefaultConsoleLogger : public RiaLogger
@@ -49,33 +47,31 @@ class RiaDefaultConsoleLogger : public RiaLogger
public:
RiaDefaultConsoleLogger();
int level() const override;
void setLevel(int logLevel) override;
void error( const char* message) override;
void warning(const char* message) override;
void info( const char* message) override;
void debug( const char* message) override;
int level() const override;
void setLevel( int logLevel ) override;
void error( const char* message ) override;
void warning( const char* message ) override;
void info( const char* message ) override;
void debug( const char* message ) override;
private:
static void writeMessageToConsole(const char* prefix, const char* message);
static void writeToConsole(const std::string& str);
static void writeMessageToConsole( const char* prefix, const char* message );
static void writeToConsole( const std::string& str );
private:
int m_logLevel;
int m_logLevel;
};
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
RiaDefaultConsoleLogger::RiaDefaultConsoleLogger()
: m_logLevel(RI_LL_WARNING)
: m_logLevel( RI_LL_WARNING )
{
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
int RiaDefaultConsoleLogger::level() const
{
@@ -83,59 +79,56 @@ int RiaDefaultConsoleLogger::level() const
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaDefaultConsoleLogger::setLevel(int logLevel)
void RiaDefaultConsoleLogger::setLevel( int logLevel )
{
m_logLevel = logLevel;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaDefaultConsoleLogger::error(const char* message)
void RiaDefaultConsoleLogger::error( const char* message )
{
writeMessageToConsole("ERROR: ", message);
writeMessageToConsole( "ERROR: ", message );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaDefaultConsoleLogger::warning(const char* message)
void RiaDefaultConsoleLogger::warning( const char* message )
{
writeMessageToConsole("warn: ", message);
writeMessageToConsole( "warn: ", message );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaDefaultConsoleLogger::info(const char* message)
void RiaDefaultConsoleLogger::info( const char* message )
{
writeMessageToConsole("info: ", message);
writeMessageToConsole( "info: ", message );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaDefaultConsoleLogger::debug(const char* message)
void RiaDefaultConsoleLogger::debug( const char* message )
{
writeMessageToConsole("debug: ", message);
writeMessageToConsole( "debug: ", message );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaDefaultConsoleLogger::writeMessageToConsole(const char* prefix, const char* message)
void RiaDefaultConsoleLogger::writeMessageToConsole( const char* prefix, const char* message )
{
std::ostringstream oss;
// VF_ASSERT(prefix);
// VF_ASSERT(prefix);
oss << prefix;
if (message)
if ( message )
{
oss << message << std::endl;
}
@@ -144,54 +137,52 @@ void RiaDefaultConsoleLogger::writeMessageToConsole(const char* prefix, const ch
oss << "<no message>" << std::endl;
}
writeToConsole(oss.str());
writeToConsole( oss.str() );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaDefaultConsoleLogger::writeToConsole(const std::string& str)
void RiaDefaultConsoleLogger::writeToConsole( const std::string& str )
{
#ifdef WIN32
AllocConsole();
HANDLE hStdOutputHandle = GetStdHandle(STD_OUTPUT_HANDLE);
if (hStdOutputHandle)
HANDLE hStdOutputHandle = GetStdHandle( STD_OUTPUT_HANDLE );
if ( hStdOutputHandle )
{
DWORD stringLength = static_cast<DWORD>(str.length());
DWORD stringLength = static_cast<DWORD>( str.length() );
unsigned long iDum = 0;
WriteConsoleA(hStdOutputHandle, str.c_str(), stringLength, &iDum, nullptr);
WriteConsoleA( hStdOutputHandle, str.c_str(), stringLength, &iDum, nullptr );
}
#else
fputs(str.c_str(), stderr);
fputs( str.c_str(), stderr );
#endif
}
//==================================================================================================
//
//
//
//
//==================================================================================================
RiaLogger* RiaLogging::sm_logger = new RiaDefaultConsoleLogger;
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
RiaLogger* RiaLogging::loggerInstance()
{
return sm_logger;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaLogging::setLoggerInstance(RiaLogger* loggerInstance)
void RiaLogging::setLoggerInstance( RiaLogger* loggerInstance )
{
// Only delete if we're currently using our own default impl
if (dynamic_cast<RiaDefaultConsoleLogger*>(sm_logger))
if ( dynamic_cast<RiaDefaultConsoleLogger*>( sm_logger ) )
{
delete sm_logger;
}
@@ -199,9 +190,8 @@ void RiaLogging::setLoggerInstance(RiaLogger* loggerInstance)
sm_logger = loggerInstance;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaLogging::deleteLoggerInstance()
{
@@ -210,50 +200,50 @@ void RiaLogging::deleteLoggerInstance()
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaLogging::error(const QString& message)
void RiaLogging::error( const QString& message )
{
if (sm_logger && sm_logger->level() >= RI_LL_ERROR)
if ( sm_logger && sm_logger->level() >= RI_LL_ERROR )
{
#pragma omp critical(critical_section_logging)
sm_logger->error(message.toLatin1().constData());
#pragma omp critical( critical_section_logging )
sm_logger->error( message.toLatin1().constData() );
}
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaLogging::warning(const QString& message)
void RiaLogging::warning( const QString& message )
{
if (sm_logger && sm_logger->level() >= RI_LL_WARNING)
if ( sm_logger && sm_logger->level() >= RI_LL_WARNING )
{
#pragma omp critical(critical_section_logging)
sm_logger->warning(message.toLatin1().constData());
#pragma omp critical( critical_section_logging )
sm_logger->warning( message.toLatin1().constData() );
}
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaLogging::info(const QString& message)
void RiaLogging::info( const QString& message )
{
if (sm_logger && sm_logger->level() >= RI_LL_INFO)
if ( sm_logger && sm_logger->level() >= RI_LL_INFO )
{
#pragma omp critical(critical_section_logging)
sm_logger->info(message.toLatin1().constData());
#pragma omp critical( critical_section_logging )
sm_logger->info( message.toLatin1().constData() );
}
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaLogging::debug(const QString& message)
void RiaLogging::debug( const QString& message )
{
if (sm_logger && sm_logger->level() >= RI_LL_DEBUG)
if ( sm_logger && sm_logger->level() >= RI_LL_DEBUG )
{
#pragma omp critical(critical_section_logging)
sm_logger->debug(message.toLatin1().constData());
#pragma omp critical( critical_section_logging )
sm_logger->debug( message.toLatin1().constData() );
}
}
@@ -261,7 +251,7 @@ void RiaLogging::debug(const QString& message)
///
//--------------------------------------------------------------------------------------------------
RiuMessageLoggerBase::RiuMessageLoggerBase()
: m_logLevel(RI_LL_WARNING)
: m_logLevel( RI_LL_WARNING )
{
}
@@ -276,7 +266,7 @@ int RiuMessageLoggerBase::level() const
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiuMessageLoggerBase::setLevel(int logLevel)
void RiuMessageLoggerBase::setLevel( int logLevel )
{
m_logLevel = logLevel;
}
@@ -284,45 +274,45 @@ void RiuMessageLoggerBase::setLevel(int logLevel)
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiuMessageLoggerBase::error(const char* message)
void RiuMessageLoggerBase::error( const char* message )
{
writeMessageWithPrefixToLogger("ERROR: ", message);
writeMessageWithPrefixToLogger( "ERROR: ", message );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiuMessageLoggerBase::warning(const char* message)
void RiuMessageLoggerBase::warning( const char* message )
{
writeMessageWithPrefixToLogger("warning: ", message);
writeMessageWithPrefixToLogger( "warning: ", message );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiuMessageLoggerBase::info(const char* message)
void RiuMessageLoggerBase::info( const char* message )
{
writeMessageWithPrefixToLogger("info: ", message);
writeMessageWithPrefixToLogger( "info: ", message );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiuMessageLoggerBase::debug(const char* message)
void RiuMessageLoggerBase::debug( const char* message )
{
writeMessageWithPrefixToLogger("debug: ", message);
writeMessageWithPrefixToLogger( "debug: ", message );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiuMessageLoggerBase::writeMessageWithPrefixToLogger(const char* prefix, const char* message)
void RiuMessageLoggerBase::writeMessageWithPrefixToLogger( const char* prefix, const char* message )
{
std::ostringstream oss;
oss << prefix;
if (message)
if ( message )
{
oss << message << std::endl;
}
@@ -331,13 +321,13 @@ void RiuMessageLoggerBase::writeMessageWithPrefixToLogger(const char* prefix, co
oss << "<no message>" << std::endl;
}
writeMessageToLogger(oss.str());
writeMessageToLogger( oss.str() );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaStdOutLogger::writeMessageToLogger(const std::string& str)
void RiaStdOutLogger::writeMessageToLogger( const std::string& str )
{
std::cout << str;
}

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017 Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE.
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -24,14 +24,12 @@ class QString;
enum RILogLevel
{
RI_LL_ERROR = 1,
RI_LL_ERROR = 1,
RI_LL_WARNING = 2,
RI_LL_INFO = 3,
RI_LL_DEBUG = 4
RI_LL_INFO = 3,
RI_LL_DEBUG = 4
};
//==================================================================================================
//
// Logger interface for the application
@@ -42,36 +40,34 @@ class RiaLogger
public:
virtual ~RiaLogger() {}
virtual int level() const = 0;
virtual void setLevel(int logLevel) = 0;
virtual int level() const = 0;
virtual void setLevel( int logLevel ) = 0;
virtual void error( const char* message) = 0;
virtual void warning(const char* message) = 0;
virtual void info( const char* message) = 0;
virtual void debug( const char* message) = 0;
virtual void error( const char* message ) = 0;
virtual void warning( const char* message ) = 0;
virtual void info( const char* message ) = 0;
virtual void debug( const char* message ) = 0;
};
//==================================================================================================
//
//
//
//
//==================================================================================================
class RiaLogging
{
public:
static RiaLogger* loggerInstance();
static void setLoggerInstance(RiaLogger* loggerInstance);
static void deleteLoggerInstance();
static RiaLogger* loggerInstance();
static void setLoggerInstance( RiaLogger* loggerInstance );
static void deleteLoggerInstance();
static void error( const QString& message);
static void warning(const QString& message);
static void info( const QString& message);
static void debug( const QString& message);
static void error( const QString& message );
static void warning( const QString& message );
static void info( const QString& message );
static void debug( const QString& message );
private:
static RiaLogger* sm_logger;
static RiaLogger* sm_logger;
};
//==================================================================================================
@@ -83,18 +79,18 @@ public:
explicit RiuMessageLoggerBase();
int level() const override;
void setLevel(int logLevel) override;
void setLevel( int logLevel ) override;
void error(const char* message) override;
void warning(const char* message) override;
void info(const char* message) override;
void debug(const char* message) override;
void error( const char* message ) override;
void warning( const char* message ) override;
void info( const char* message ) override;
void debug( const char* message ) override;
protected:
virtual void writeMessageToLogger(const std::string& str) = 0;
virtual void writeMessageToLogger( const std::string& str ) = 0;
private:
void writeMessageWithPrefixToLogger(const char* prefix, const char* message);
void writeMessageWithPrefixToLogger( const char* prefix, const char* message );
private:
int m_logLevel;
@@ -106,5 +102,5 @@ private:
class RiaStdOutLogger : public RiuMessageLoggerBase
{
public:
void writeMessageToLogger(const std::string& str) override;
void writeMessageToLogger( const std::string& str ) override;
};

View File

@@ -18,8 +18,8 @@
#pragma once
#include <array>
#include "cvfVector3.h"
#include <array>
#include <cmath>
// Y - North, X - East, Z - up but depth is negative Z
@@ -31,49 +31,61 @@ const double singularityEpsilon = 1.0e-5;
class RiaOffshoreSphericalCoords
{
public:
explicit RiaOffshoreSphericalCoords(const cvf::Vec3f& vec)
explicit RiaOffshoreSphericalCoords( const cvf::Vec3f& vec )
{
// Azimuth:
if ( fabs(vec[0]) < singularityEpsilon && fabs(vec[1]) < singularityEpsilon ) incAziR[1] = 0.0f;
else incAziR[1] = atan2(vec[0], vec[1]); // atan2(Y, X)
// Azimuth:
if ( fabs( vec[0] ) < singularityEpsilon && fabs( vec[1] ) < singularityEpsilon )
incAziR[1] = 0.0f;
else
incAziR[1] = atan2( vec[0], vec[1] ); // atan2(Y, X)
// R
incAziR[2] = vec.length();
// Inclination from vertical down
if (fabs( incAziR[2]) < singularityEpsilon) incAziR[0] = 0.0f;
else incAziR[0] = acos(-vec[2]/incAziR[2]);
if ( fabs( incAziR[2] ) < singularityEpsilon )
incAziR[0] = 0.0f;
else
incAziR[0] = acos( -vec[2] / incAziR[2] );
}
explicit RiaOffshoreSphericalCoords(const cvf::Vec3d& vec)
explicit RiaOffshoreSphericalCoords( const cvf::Vec3d& vec )
{
// Azimuth:
if (fabs(vec[0]) < singularityEpsilon && fabs(vec[1]) < singularityEpsilon ) incAziR[1] = 0.0;
else incAziR[1] = atan2(vec[0], vec[1]); // atan2(Y, X)
// Azimuth:
if ( fabs( vec[0] ) < singularityEpsilon && fabs( vec[1] ) < singularityEpsilon )
incAziR[1] = 0.0;
else
incAziR[1] = atan2( vec[0], vec[1] ); // atan2(Y, X)
// R
// R
incAziR[2] = vec.length();
// Inclination from vertical down
if (fabs( incAziR[2]) < singularityEpsilon) incAziR[0] = 0.0;
else incAziR[0] = acos(-vec[2]/incAziR[2]);
if ( fabs( incAziR[2] ) < singularityEpsilon )
incAziR[0] = 0.0;
else
incAziR[0] = acos( -vec[2] / incAziR[2] );
}
double inc() const
{
return incAziR[0];
}
double azi() const
{
return incAziR[1];
}
double r() const
{
return incAziR[2];
}
double inc() const { return incAziR[0];}
double azi() const { return incAziR[1];}
double r() const { return incAziR[2];}
// Note that this is a double function, while the rest of the class is float.
// Todo: Convert class to a template to enable float and double versions of everything
static cvf::Vec3d unitVectorFromAziInc(double azimuth, double inclination)
static cvf::Vec3d unitVectorFromAziInc( double azimuth, double inclination )
{
return cvf::Vec3d(sin(azimuth)*sin(inclination),
cos(azimuth)*sin(inclination),
-cos(inclination));
return cvf::Vec3d( sin( azimuth ) * sin( inclination ), cos( azimuth ) * sin( inclination ), -cos( inclination ) );
}
private:
std::array<double, 3> incAziR;
};

View File

@@ -24,15 +24,16 @@
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaOptionItemFactory::appendOptionItemFromViewNameAndCaseName(Rim3dView* view, QList<caf::PdmOptionItemInfo>* optionItems)
void RiaOptionItemFactory::appendOptionItemFromViewNameAndCaseName( Rim3dView* view,
QList<caf::PdmOptionItemInfo>* optionItems )
{
if (!view || !optionItems) return;
if ( !view || !optionItems ) return;
QString caseName;
RimCase* rimCase = nullptr;
view->firstAncestorOrThisOfType(rimCase);
if (rimCase)
view->firstAncestorOrThisOfType( rimCase );
if ( rimCase )
{
caseName = rimCase->caseUserDescription();
}
@@ -45,5 +46,5 @@ void RiaOptionItemFactory::appendOptionItemFromViewNameAndCaseName(Rim3dView* vi
caf::QIconProvider iconProvider = view->uiCapability()->uiIconProvider();
optionItems->push_back(caf::PdmOptionItemInfo(displayName, view, false, iconProvider));
optionItems->push_back( caf::PdmOptionItemInfo( displayName, view, false, iconProvider ) );
}

View File

@@ -27,5 +27,5 @@ class Rim3dView;
class RiaOptionItemFactory
{
public:
static void appendOptionItemFromViewNameAndCaseName(Rim3dView* view, QList<caf::PdmOptionItemInfo>* optionItems);
static void appendOptionItemFromViewNameAndCaseName( Rim3dView* view, QList<caf::PdmOptionItemInfo>* optionItems );
};

View File

@@ -23,62 +23,73 @@
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool RiaProjectFileVersionTools::isCandidateVersionNewerThanOther(const QString& candidateProjectFileVersion,
const QString& projectFileVersion)
bool RiaProjectFileVersionTools::isCandidateVersionNewerThanOther( const QString& candidateProjectFileVersion,
const QString& projectFileVersion )
{
int candidateMajorVersion = 0;
int candidateMinorVersion = 0;
int candidatePatchNumber = 0;
int candidateDevelopmentId = 0;
RiaProjectFileVersionTools::decodeVersionString(candidateProjectFileVersion, &candidateMajorVersion, &candidateMinorVersion,
&candidatePatchNumber, &candidateDevelopmentId);
RiaProjectFileVersionTools::decodeVersionString( candidateProjectFileVersion,
&candidateMajorVersion,
&candidateMinorVersion,
&candidatePatchNumber,
&candidateDevelopmentId );
int majorVersion = 0;
int minorVersion = 0;
int patchNumber = 0;
int developmentId = 0;
RiaProjectFileVersionTools::decodeVersionString(projectFileVersion, &majorVersion, &minorVersion, &patchNumber,
&developmentId);
RiaProjectFileVersionTools::decodeVersionString( projectFileVersion,
&majorVersion,
&minorVersion,
&patchNumber,
&developmentId );
return RiaProjectFileVersionTools::isCandidateNewerThanOther(candidateMajorVersion, candidateMinorVersion,
candidatePatchNumber, candidateDevelopmentId, majorVersion,
minorVersion, patchNumber, developmentId);
return RiaProjectFileVersionTools::isCandidateNewerThanOther( candidateMajorVersion,
candidateMinorVersion,
candidatePatchNumber,
candidateDevelopmentId,
majorVersion,
minorVersion,
patchNumber,
developmentId );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaProjectFileVersionTools::decodeVersionString(const QString& projectFileVersion, int* majorVersion, int* minorVersion,
int* patch, int* developmentId)
void RiaProjectFileVersionTools::decodeVersionString(
const QString& projectFileVersion, int* majorVersion, int* minorVersion, int* patch, int* developmentId )
{
if (projectFileVersion.isEmpty()) return;
if ( projectFileVersion.isEmpty() ) return;
QStringList subStrings = projectFileVersion.split(".");
QStringList subStrings = projectFileVersion.split( "." );
if (subStrings.size() > 0)
if ( subStrings.size() > 0 )
{
*majorVersion = subStrings[0].toInt();
}
if (subStrings.size() > 1)
if ( subStrings.size() > 1 )
{
*minorVersion = subStrings[1].toInt();
}
if (subStrings.size() > 2)
if ( subStrings.size() > 2 )
{
QString candidate = subStrings[2];
QString candidateDigitsOnly = RiaProjectFileVersionTools::stringOfDigits(candidate);
QString candidateDigitsOnly = RiaProjectFileVersionTools::stringOfDigits( candidate );
*patch = candidateDigitsOnly.toInt();
}
if (subStrings.size() > 3)
if ( subStrings.size() > 3 )
{
QString candidate = subStrings.back();
QString candidateDigitsOnly = RiaProjectFileVersionTools::stringOfDigits(candidate);
QString candidateDigitsOnly = RiaProjectFileVersionTools::stringOfDigits( candidate );
*developmentId = candidateDigitsOnly.toInt();
}
@@ -87,29 +98,33 @@ void RiaProjectFileVersionTools::decodeVersionString(const QString& projectFileV
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool RiaProjectFileVersionTools::isCandidateNewerThanOther(int candidateMajorVersion, int candidateMinorVersion,
int candidatePatchNumber, int candidateDevelopmentId,
int otherMajorVersion, int otherMinorVersion, int otherPatchNumber,
int otherDevelopmentId)
bool RiaProjectFileVersionTools::isCandidateNewerThanOther( int candidateMajorVersion,
int candidateMinorVersion,
int candidatePatchNumber,
int candidateDevelopmentId,
int otherMajorVersion,
int otherMinorVersion,
int otherPatchNumber,
int otherDevelopmentId )
{
if (candidateMajorVersion != otherMajorVersion)
if ( candidateMajorVersion != otherMajorVersion )
{
return (candidateMajorVersion > otherMajorVersion);
return ( candidateMajorVersion > otherMajorVersion );
}
if (candidateMinorVersion != otherMinorVersion)
if ( candidateMinorVersion != otherMinorVersion )
{
return (candidateMinorVersion > otherMinorVersion);
return ( candidateMinorVersion > otherMinorVersion );
}
if (candidatePatchNumber != otherPatchNumber)
if ( candidatePatchNumber != otherPatchNumber )
{
return (candidatePatchNumber > otherPatchNumber);
return ( candidatePatchNumber > otherPatchNumber );
}
if (candidateDevelopmentId != otherDevelopmentId)
if ( candidateDevelopmentId != otherDevelopmentId )
{
return (candidateDevelopmentId > otherDevelopmentId);
return ( candidateDevelopmentId > otherDevelopmentId );
}
return false;
@@ -118,19 +133,19 @@ bool RiaProjectFileVersionTools::isCandidateNewerThanOther(int candidateMajorVer
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString RiaProjectFileVersionTools::stringOfDigits(const QString& string)
QString RiaProjectFileVersionTools::stringOfDigits( const QString& string )
{
QString digitsOnly;
for (const auto& c : string)
for ( const auto& c : string )
{
if (c.isDigit())
if ( c.isDigit() )
{
digitsOnly += c;
}
else
{
if (!digitsOnly.isEmpty())
if ( !digitsOnly.isEmpty() )
{
return digitsOnly;
}
@@ -139,4 +154,3 @@ QString RiaProjectFileVersionTools::stringOfDigits(const QString& string)
return digitsOnly;
}

View File

@@ -26,17 +26,22 @@
class RiaProjectFileVersionTools
{
public:
static bool isCandidateVersionNewerThanOther(const QString& candidateProjectFileVersion,
const QString& otherProjectFileVersion);
static bool isCandidateVersionNewerThanOther( const QString& candidateProjectFileVersion,
const QString& otherProjectFileVersion );
// Public to be able to unit test function, not intended to be used
static void decodeVersionString(const QString& projectFileVersion, int* majorVersion, int* minorVersion, int* patch,
int* developmentId);
static void decodeVersionString(
const QString& projectFileVersion, int* majorVersion, int* minorVersion, int* patch, int* developmentId );
private:
static bool isCandidateNewerThanOther(int candidateMajorVersion, int candidateMinorVersion, int candidatePatchNumber,
int candidateDevelopmentId, int otherMajorVersion, int otherMinorVersion,
int otherPatchNumber, int otherDevelopmentId);
static bool isCandidateNewerThanOther( int candidateMajorVersion,
int candidateMinorVersion,
int candidatePatchNumber,
int candidateDevelopmentId,
int otherMajorVersion,
int otherMinorVersion,
int otherPatchNumber,
int otherDevelopmentId );
static QString stringOfDigits(const QString& string);
static QString stringOfDigits( const QString& string );
};

View File

@@ -2,17 +2,17 @@
//
// Copyright (C) Statoil ASA
// Copyright (C) Ceetron Solutions 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>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -28,131 +28,128 @@
#include "RimOilField.h"
#include "RimProject.h"
#include <QFileInfo>
#include <QDir>
#include <QFileInfo>
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
RiaProjectModifier::RiaProjectModifier()
RiaProjectModifier::RiaProjectModifier() {}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaProjectModifier::setReplaceCaseFirstOccurrence( QString newGridFileName )
{
m_caseIdToGridFileNameMap[RiaProjectModifier::firstOccurrenceId()] = makeFilePathAbsolute( newGridFileName );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaProjectModifier::setReplaceCaseFirstOccurrence(QString newGridFileName)
void RiaProjectModifier::setReplaceCase( int caseIdToReplace, QString newGridFileName )
{
m_caseIdToGridFileNameMap[RiaProjectModifier::firstOccurrenceId()] = makeFilePathAbsolute(newGridFileName);
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaProjectModifier::setReplaceCase(int caseIdToReplace, QString newGridFileName)
{
if (caseIdToReplace >= 0)
if ( caseIdToReplace >= 0 )
{
m_caseIdToGridFileNameMap[caseIdToReplace] = makeFilePathAbsolute(newGridFileName);
m_caseIdToGridFileNameMap[caseIdToReplace] = makeFilePathAbsolute( newGridFileName );
}
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaProjectModifier::setReplaceSourceCasesFirstOccurrence(std::vector<QString> newGridFileNames)
void RiaProjectModifier::setReplaceSourceCasesFirstOccurrence( std::vector<QString> newGridFileNames )
{
m_groupIdToGridFileNamesMap[RiaProjectModifier::firstOccurrenceId()] = newGridFileNames;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaProjectModifier::setReplaceSourceCasesById(int caseGroupIdToReplace, std::vector<QString> newGridFileNames)
void RiaProjectModifier::setReplaceSourceCasesById( int caseGroupIdToReplace, std::vector<QString> newGridFileNames )
{
if (caseGroupIdToReplace >= 0)
if ( caseGroupIdToReplace >= 0 )
{
m_groupIdToGridFileNamesMap[caseGroupIdToReplace] = newGridFileNames;
}
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaProjectModifier::setReplacePropertiesFolderFirstOccurrence(QString newPropertiesFolder)
void RiaProjectModifier::setReplacePropertiesFolderFirstOccurrence( QString newPropertiesFolder )
{
m_caseIdToPropertiesFolderMap[RiaProjectModifier::firstOccurrenceId()] = makeFilePathAbsolute(newPropertiesFolder);
m_caseIdToPropertiesFolderMap[RiaProjectModifier::firstOccurrenceId()] = makeFilePathAbsolute( newPropertiesFolder );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaProjectModifier::setReplacePropertiesFolder(int caseIdToReplace, QString newPropertiesFolder)
void RiaProjectModifier::setReplacePropertiesFolder( int caseIdToReplace, QString newPropertiesFolder )
{
if (caseIdToReplace >= 0)
if ( caseIdToReplace >= 0 )
{
m_caseIdToPropertiesFolderMap[caseIdToReplace] = makeFilePathAbsolute(newPropertiesFolder);
m_caseIdToPropertiesFolderMap[caseIdToReplace] = makeFilePathAbsolute( newPropertiesFolder );
}
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
bool RiaProjectModifier::applyModificationsToProject(RimProject* project)
bool RiaProjectModifier::applyModificationsToProject( RimProject* project )
{
if (m_caseIdToGridFileNameMap.size() > 0)
if ( m_caseIdToGridFileNameMap.size() > 0 )
{
replaceCase(project);
replaceCase( project );
}
if (m_groupIdToGridFileNamesMap.size() > 0)
if ( m_groupIdToGridFileNamesMap.size() > 0 )
{
replaceSourceCases(project);
replaceSourceCases( project );
}
if (m_caseIdToPropertiesFolderMap.size() > 0)
if ( m_caseIdToPropertiesFolderMap.size() > 0 )
{
replacePropertiesFolder(project);
replacePropertiesFolder( project );
}
return true;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaProjectModifier::replaceSourceCases(RimProject* project)
void RiaProjectModifier::replaceSourceCases( RimProject* project )
{
for (RimOilField* oilField : project->oilFields())
for ( RimOilField* oilField : project->oilFields() )
{
RimEclipseCaseCollection* analysisModels = oilField ? oilField->analysisModels() : nullptr;
if (analysisModels)
if ( analysisModels )
{
for (RimIdenticalGridCaseGroup* caseGroup : analysisModels->caseGroups)
for ( RimIdenticalGridCaseGroup* caseGroup : analysisModels->caseGroups )
{
for (auto item : m_groupIdToGridFileNamesMap)
for ( auto item : m_groupIdToGridFileNamesMap )
{
int groupIdToReplace = item.first;
if (groupIdToReplace == RiaProjectModifier::firstOccurrenceId())
if ( groupIdToReplace == RiaProjectModifier::firstOccurrenceId() )
{
groupIdToReplace = firstGroupId(project);
groupIdToReplace = firstGroupId( project );
}
if (groupIdToReplace == caseGroup->groupId())
if ( groupIdToReplace == caseGroup->groupId() )
{
RimCaseCollection* caseCollection = caseGroup->caseCollection;
caseCollection->reservoirs.deleteAllChildObjects();
for (QString fileName : item.second)
for ( QString fileName : item.second )
{
QString caseName = caseNameFromGridFileName(fileName);
QString caseName = caseNameFromGridFileName( fileName );
// Use this slightly hackish method in order to get a new unique ID
RimEclipseResultCase* resCase = new RimEclipseResultCase;
resCase->setCaseInfo(caseName, fileName);
resCase->setCaseInfo( caseName, fileName );
caseCollection->reservoirs.push_back(resCase);
caseCollection->reservoirs.push_back( resCase );
}
}
}
@@ -162,39 +159,39 @@ void RiaProjectModifier::replaceSourceCases(RimProject* project)
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaProjectModifier::replaceCase(RimProject* project)
void RiaProjectModifier::replaceCase( RimProject* project )
{
std::vector<RimCase*> allCases;
project->allCases(allCases);
for (RimCase* rimCase : allCases)
project->allCases( allCases );
for ( RimCase* rimCase : allCases )
{
RimEclipseResultCase* eclipseResultCase = dynamic_cast<RimEclipseResultCase*>(rimCase);
RimGeoMechCase* geomechCase = dynamic_cast<RimGeoMechCase*>(rimCase);
if (eclipseResultCase || geomechCase)
RimEclipseResultCase* eclipseResultCase = dynamic_cast<RimEclipseResultCase*>( rimCase );
RimGeoMechCase* geomechCase = dynamic_cast<RimGeoMechCase*>( rimCase );
if ( eclipseResultCase || geomechCase )
{
for (auto item : m_caseIdToGridFileNameMap)
for ( auto item : m_caseIdToGridFileNameMap )
{
int caseIdToReplace = item.first;
if (caseIdToReplace == RiaProjectModifier::firstOccurrenceId())
if ( caseIdToReplace == RiaProjectModifier::firstOccurrenceId() )
{
caseIdToReplace = firstCaseId(project);
caseIdToReplace = firstCaseId( project );
}
if (caseIdToReplace == rimCase->caseId())
if ( caseIdToReplace == rimCase->caseId() )
{
QString replaceFileName = item.second;
if (eclipseResultCase)
if ( eclipseResultCase )
{
eclipseResultCase->setGridFileName(replaceFileName);
eclipseResultCase->caseUserDescription = caseNameFromGridFileName(replaceFileName);
eclipseResultCase->setGridFileName( replaceFileName );
eclipseResultCase->caseUserDescription = caseNameFromGridFileName( replaceFileName );
}
else if (geomechCase)
else if ( geomechCase )
{
geomechCase->setFileName(replaceFileName);
geomechCase->caseUserDescription = caseNameFromGridFileName(replaceFileName);
geomechCase->setFileName( replaceFileName );
geomechCase->caseUserDescription = caseNameFromGridFileName( replaceFileName );
}
}
}
@@ -203,31 +200,31 @@ void RiaProjectModifier::replaceCase(RimProject* project)
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaProjectModifier::replacePropertiesFolder(RimProject* project)
void RiaProjectModifier::replacePropertiesFolder( RimProject* project )
{
std::vector<RimCase*> allCases;
project->allCases(allCases);
project->allCases( allCases );
for (RimCase* rimCase : allCases)
for ( RimCase* rimCase : allCases )
{
RimEclipseInputCase* inputCase = dynamic_cast<RimEclipseInputCase*>(rimCase);
RimEclipseInputCase* inputCase = dynamic_cast<RimEclipseInputCase*>( rimCase );
if (inputCase)
if ( inputCase )
{
for (auto item : m_caseIdToPropertiesFolderMap)
for ( auto item : m_caseIdToPropertiesFolderMap )
{
int caseIdToReplace = item.first;
if (caseIdToReplace == RiaProjectModifier::firstOccurrenceId())
if ( caseIdToReplace == RiaProjectModifier::firstOccurrenceId() )
{
caseIdToReplace = firstInputCaseId(project);
caseIdToReplace = firstInputCaseId( project );
}
if (caseIdToReplace == inputCase->caseId())
if ( caseIdToReplace == inputCase->caseId() )
{
inputCase->updateAdditionalFileFolder(item.second);
inputCase->updateAdditionalFileFolder( item.second );
}
}
}
@@ -235,45 +232,45 @@ void RiaProjectModifier::replacePropertiesFolder(RimProject* project)
}
//--------------------------------------------------------------------------------------------------
/// Returns absolute path name to the specified file.
///
/// Returns absolute path name to the specified file.
///
/// If \a relOrAbsolutePath is a relative, the current working directory for the process will be
/// used in order to make the path absolute.
//--------------------------------------------------------------------------------------------------
QString RiaProjectModifier::makeFilePathAbsolute(QString relOrAbsolutePath)
QString RiaProjectModifier::makeFilePathAbsolute( QString relOrAbsolutePath )
{
QFileInfo theFile(relOrAbsolutePath);
QFileInfo theFile( relOrAbsolutePath );
theFile.makeAbsolute();
return theFile.filePath();
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QString RiaProjectModifier::caseNameFromGridFileName(QString fullGridFilePathName)
QString RiaProjectModifier::caseNameFromGridFileName( QString fullGridFilePathName )
{
QString fn = QDir::fromNativeSeparators(fullGridFilePathName);
// Extract file name plus the 'deepest' directory
QString deepestDirPlusFileName = fn.section('/', -2, -1);
QString fn = QDir::fromNativeSeparators( fullGridFilePathName );
deepestDirPlusFileName.replace("/", "--");
// Extract file name plus the 'deepest' directory
QString deepestDirPlusFileName = fn.section( '/', -2, -1 );
deepestDirPlusFileName.replace( "/", "--" );
return deepestDirPlusFileName;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
int RiaProjectModifier::firstCaseId(RimProject* project)
int RiaProjectModifier::firstCaseId( RimProject* project )
{
std::vector<RimCase*> allCases;
project->allCases(allCases);
project->allCases( allCases );
for (RimCase* rimCase : allCases)
for ( RimCase* rimCase : allCases )
{
RimEclipseResultCase* resultCase = dynamic_cast<RimEclipseResultCase*>(rimCase);
if (resultCase)
RimEclipseResultCase* resultCase = dynamic_cast<RimEclipseResultCase*>( rimCase );
if ( resultCase )
{
return resultCase->caseId();
}
@@ -283,17 +280,17 @@ int RiaProjectModifier::firstCaseId(RimProject* project)
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
int RiaProjectModifier::firstGroupId(RimProject* project)
int RiaProjectModifier::firstGroupId( RimProject* project )
{
for (size_t oilFieldIdx = 0; oilFieldIdx < project->oilFields().size(); oilFieldIdx++)
for ( size_t oilFieldIdx = 0; oilFieldIdx < project->oilFields().size(); oilFieldIdx++ )
{
RimOilField* oilField = project->oilFields[oilFieldIdx];
RimOilField* oilField = project->oilFields[oilFieldIdx];
RimEclipseCaseCollection* analysisModels = oilField ? oilField->analysisModels() : nullptr;
if (analysisModels)
if ( analysisModels )
{
if (analysisModels->caseGroups.size() > 0)
if ( analysisModels->caseGroups.size() > 0 )
{
return analysisModels->caseGroups[0]->groupId();
}
@@ -304,17 +301,17 @@ int RiaProjectModifier::firstGroupId(RimProject* project)
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
int RiaProjectModifier::firstInputCaseId(RimProject * project)
int RiaProjectModifier::firstInputCaseId( RimProject* project )
{
std::vector<RimCase*> allCases;
project->allCases(allCases);
project->allCases( allCases );
for (RimCase* rimCase : allCases)
for ( RimCase* rimCase : allCases )
{
RimEclipseInputCase* resultCase = dynamic_cast<RimEclipseInputCase*>(rimCase);
if (resultCase)
RimEclipseInputCase* resultCase = dynamic_cast<RimEclipseInputCase*>( rimCase );
if ( resultCase )
{
return resultCase->caseId();
}
@@ -324,10 +321,9 @@ int RiaProjectModifier::firstInputCaseId(RimProject * project)
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
int RiaProjectModifier::firstOccurrenceId()
{
return -999;
}

View File

@@ -2,38 +2,35 @@
//
// Copyright (C) Statoil ASA
// Copyright (C) Ceetron Solutions 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>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
#pragma once
#include "cvfObject.h"
#include <QString>
#include <vector>
#include <map>
#include <vector>
class RimProject;
//==================================================================================================
//
//
//
//
//==================================================================================================
class RiaProjectModifier : public cvf::Object
@@ -41,34 +38,33 @@ class RiaProjectModifier : public cvf::Object
public:
RiaProjectModifier();
void setReplaceCaseFirstOccurrence(QString newGridFileName);
void setReplaceCase(int caseIdToReplace, QString newGridFileName);
void setReplaceCaseFirstOccurrence( QString newGridFileName );
void setReplaceCase( int caseIdToReplace, QString newGridFileName );
void setReplaceSourceCasesFirstOccurrence(std::vector<QString> newGridFileNames);
void setReplaceSourceCasesById(int caseGroupIdToReplace, std::vector<QString> newGridFileNames);
void setReplaceSourceCasesFirstOccurrence( std::vector<QString> newGridFileNames );
void setReplaceSourceCasesById( int caseGroupIdToReplace, std::vector<QString> newGridFileNames );
void setReplacePropertiesFolderFirstOccurrence(QString newPropertiesFolder);
void setReplacePropertiesFolder(int caseIdToReplace, QString newPropertiesFolder);
void setReplacePropertiesFolderFirstOccurrence( QString newPropertiesFolder );
void setReplacePropertiesFolder( int caseIdToReplace, QString newPropertiesFolder );
bool applyModificationsToProject(RimProject* project);
bool applyModificationsToProject( RimProject* project );
private:
void replaceSourceCases(RimProject* project);
void replaceCase(RimProject* project);
void replacePropertiesFolder(RimProject* project);
void replaceSourceCases( RimProject* project );
void replaceCase( RimProject* project );
void replacePropertiesFolder( RimProject* project );
static QString makeFilePathAbsolute(QString relOrAbsolutePath);
static QString caseNameFromGridFileName(QString fullGridFilePathName);
static QString makeFilePathAbsolute( QString relOrAbsolutePath );
static QString caseNameFromGridFileName( QString fullGridFilePathName );
static int firstCaseId(RimProject* project);
static int firstGroupId(RimProject* project);
static int firstInputCaseId(RimProject* project);
static int firstCaseId( RimProject* project );
static int firstGroupId( RimProject* project );
static int firstInputCaseId( RimProject* project );
static int firstOccurrenceId();
static int firstOccurrenceId();
private:
std::map<int, QString> m_caseIdToGridFileNameMap;
std::map<int, std::vector<QString> > m_groupIdToGridFileNamesMap;
std::map<int, QString> m_caseIdToPropertiesFolderMap;
std::map<int, QString> m_caseIdToGridFileNameMap;
std::map<int, std::vector<QString>> m_groupIdToGridFileNamesMap;
std::map<int, QString> m_caseIdToPropertiesFolderMap;
};

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017 Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE.
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -25,55 +25,53 @@
#include "cafAppEnum.h"
#include <cvfAssert.h>
#include <ctime>
#include <cmath>
#include <ctime>
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const DateTimeSpan RiaQDateTimeTools::TIMESPAN_DAY = DateTimeSpan(0, 0, 1);
const DateTimeSpan RiaQDateTimeTools::TIMESPAN_WEEK = DateTimeSpan(0, 0, 7);
const DateTimeSpan RiaQDateTimeTools::TIMESPAN_MONTH = DateTimeSpan(0, 1, 0);
const DateTimeSpan RiaQDateTimeTools::TIMESPAN_QUARTER = DateTimeSpan(0, 3, 0);
const DateTimeSpan RiaQDateTimeTools::TIMESPAN_HALFYEAR = DateTimeSpan(0, 6, 0);
const DateTimeSpan RiaQDateTimeTools::TIMESPAN_YEAR = DateTimeSpan(1, 0, 0);
const DateTimeSpan RiaQDateTimeTools::TIMESPAN_DECADE = DateTimeSpan(10, 0, 0);
const DateTimeSpan RiaQDateTimeTools::TIMESPAN_DAY = DateTimeSpan( 0, 0, 1 );
const DateTimeSpan RiaQDateTimeTools::TIMESPAN_WEEK = DateTimeSpan( 0, 0, 7 );
const DateTimeSpan RiaQDateTimeTools::TIMESPAN_MONTH = DateTimeSpan( 0, 1, 0 );
const DateTimeSpan RiaQDateTimeTools::TIMESPAN_QUARTER = DateTimeSpan( 0, 3, 0 );
const DateTimeSpan RiaQDateTimeTools::TIMESPAN_HALFYEAR = DateTimeSpan( 0, 6, 0 );
const DateTimeSpan RiaQDateTimeTools::TIMESPAN_YEAR = DateTimeSpan( 1, 0, 0 );
const DateTimeSpan RiaQDateTimeTools::TIMESPAN_DECADE = DateTimeSpan( 10, 0, 0 );
const QString RiaQDateTimeTools::TIMESPAN_DAY_NAME = "Day";
const QString RiaQDateTimeTools::TIMESPAN_WEEK_NAME = "Week";
const QString RiaQDateTimeTools::TIMESPAN_MONTH_NAME = "Month";
const QString RiaQDateTimeTools::TIMESPAN_QUARTER_NAME = "Quarter";
const QString RiaQDateTimeTools::TIMESPAN_DAY_NAME = "Day";
const QString RiaQDateTimeTools::TIMESPAN_WEEK_NAME = "Week";
const QString RiaQDateTimeTools::TIMESPAN_MONTH_NAME = "Month";
const QString RiaQDateTimeTools::TIMESPAN_QUARTER_NAME = "Quarter";
const QString RiaQDateTimeTools::TIMESPAN_HALFYEAR_NAME = "Half Year";
const QString RiaQDateTimeTools::TIMESPAN_YEAR_NAME = "Year";
const QString RiaQDateTimeTools::TIMESPAN_DECADE_NAME = "Decade";
const QString RiaQDateTimeTools::TIMESPAN_YEAR_NAME = "Year";
const QString RiaQDateTimeTools::TIMESPAN_DECADE_NAME = "Decade";
namespace caf
{
template<>
template <>
void caf::AppEnum<RiaQDateTimeTools::DateFormatComponents>::setUp()
{
addItem(RiaQDateTimeTools::DATE_FORMAT_NONE, "NO_DATE", "No Date");
addItem(RiaQDateTimeTools::DATE_FORMAT_YEAR, "YEAR", "Year Only");
addItem(RiaQDateTimeTools::DATE_FORMAT_YEAR_MONTH, "YEAR_MONTH", "Year and Month");
addItem(RiaQDateTimeTools::DATE_FORMAT_YEAR_MONTH_DAY, "YEAR_MONTH_DAY", "Year, Month and Day");
setDefault(RiaQDateTimeTools::DATE_FORMAT_YEAR_MONTH_DAY);
addItem( RiaQDateTimeTools::DATE_FORMAT_NONE, "NO_DATE", "No Date" );
addItem( RiaQDateTimeTools::DATE_FORMAT_YEAR, "YEAR", "Year Only" );
addItem( RiaQDateTimeTools::DATE_FORMAT_YEAR_MONTH, "YEAR_MONTH", "Year and Month" );
addItem( RiaQDateTimeTools::DATE_FORMAT_YEAR_MONTH_DAY, "YEAR_MONTH_DAY", "Year, Month and Day" );
setDefault( RiaQDateTimeTools::DATE_FORMAT_YEAR_MONTH_DAY );
}
template<>
template <>
void caf::AppEnum<RiaQDateTimeTools::TimeFormatComponents>::setUp()
{
addItem(RiaQDateTimeTools::TIME_FORMAT_NONE, "NO_TIME", "No Time of Day");
addItem(RiaQDateTimeTools::TIME_FORMAT_HOUR, "HOUR", "Hour Only");
addItem(RiaQDateTimeTools::TIME_FORMAT_HOUR_MINUTE, "HOUR_MINUTE", "Hour and Minute");
addItem(RiaQDateTimeTools::TIME_FORMAT_HOUR_MINUTE_SECOND, "HOUR_MINUTE_SECONDS", "Hour, Minutes and Seconds");
setDefault(RiaQDateTimeTools::TIME_FORMAT_NONE);
}
addItem( RiaQDateTimeTools::TIME_FORMAT_NONE, "NO_TIME", "No Time of Day" );
addItem( RiaQDateTimeTools::TIME_FORMAT_HOUR, "HOUR", "Hour Only" );
addItem( RiaQDateTimeTools::TIME_FORMAT_HOUR_MINUTE, "HOUR_MINUTE", "Hour and Minute" );
addItem( RiaQDateTimeTools::TIME_FORMAT_HOUR_MINUTE_SECOND, "HOUR_MINUTE_SECONDS", "Hour, Minutes and Seconds" );
setDefault( RiaQDateTimeTools::TIME_FORMAT_NONE );
}
} // namespace caf
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
Qt::TimeSpec RiaQDateTimeTools::currentTimeSpec()
{
@@ -81,7 +79,7 @@ Qt::TimeSpec RiaQDateTimeTools::currentTimeSpec()
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
quint64 RiaQDateTimeTools::secondsInDay()
{
@@ -89,7 +87,7 @@ quint64 RiaQDateTimeTools::secondsInDay()
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
quint64 RiaQDateTimeTools::secondsInYear()
{
@@ -97,262 +95,276 @@ quint64 RiaQDateTimeTools::secondsInYear()
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QDateTime RiaQDateTimeTools::fromString(const QString& dateString, const QString& format)
QDateTime RiaQDateTimeTools::fromString( const QString& dateString, const QString& format )
{
QDateTime dt = QDateTime::fromString(dateString, format);
dt.setTimeSpec(currentTimeSpec());
QDateTime dt = QDateTime::fromString( dateString, format );
dt.setTimeSpec( currentTimeSpec() );
return dt;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QDateTime RiaQDateTimeTools::fromYears(double years)
QDateTime RiaQDateTimeTools::fromYears( double years )
{
double yearsAfterEpoch = years - 1970.0;
QDateTime dt = RiaQDateTimeTools::epoch();
return RiaQDateTimeTools::addYears(dt, yearsAfterEpoch);
return RiaQDateTimeTools::addYears( dt, yearsAfterEpoch );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QDateTime RiaQDateTimeTools::fromTime_t(time_t t)
QDateTime RiaQDateTimeTools::fromTime_t( time_t t )
{
auto qdt = createUtcDateTime();
qdt.setTime_t(t);
qdt.setTime_t( t );
return qdt;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QDateTime RiaQDateTimeTools::addMSecs(const QDateTime& dt, double msecs)
QDateTime RiaQDateTimeTools::addMSecs( const QDateTime& dt, double msecs )
{
return dt.addMSecs(msecs);
return dt.addMSecs( msecs );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QDateTime RiaQDateTimeTools::addDays(const QDateTime& dt, double days)
QDateTime RiaQDateTimeTools::addDays( const QDateTime& dt, double days )
{
double integerPart = 0.0;
double integerPart = 0.0;
double fractionPart = 0.0;
fractionPart = modf(days, &integerPart);
fractionPart = modf( days, &integerPart );
QDateTime tmp = dt.addDays(integerPart);
tmp = tmp.addSecs(fractionPart * RiaQDateTimeTools::secondsInDay());
QDateTime tmp = dt.addDays( integerPart );
tmp = tmp.addSecs( fractionPart * RiaQDateTimeTools::secondsInDay() );
return tmp;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QDateTime RiaQDateTimeTools::addYears(const QDateTime& dt, double years)
QDateTime RiaQDateTimeTools::addYears( const QDateTime& dt, double years )
{
double integerPart = 0.0;
double integerPart = 0.0;
double fractionPart = 0.0;
fractionPart = modf(years, &integerPart);
fractionPart = modf( years, &integerPart );
QDateTime tmp = dt.addYears(integerPart);
tmp = tmp.addSecs(fractionPart * RiaQDateTimeTools::secondsInYear());
QDateTime tmp = dt.addYears( integerPart );
tmp = tmp.addSecs( fractionPart * RiaQDateTimeTools::secondsInYear() );
return tmp;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QDateTime RiaQDateTimeTools::addSpan(const QDateTime& dt, DateTimeSpan span)
QDateTime RiaQDateTimeTools::addSpan( const QDateTime& dt, DateTimeSpan span )
{
return createUtcDateTime(dt)
.addYears(span.years())
.addMonths(span.months())
.addDays(span.days());
return createUtcDateTime( dt ).addYears( span.years() ).addMonths( span.months() ).addDays( span.days() );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QDateTime RiaQDateTimeTools::subtractSpan(const QDateTime& dt, DateTimeSpan span)
QDateTime RiaQDateTimeTools::subtractSpan( const QDateTime& dt, DateTimeSpan span )
{
return createUtcDateTime(dt)
.addYears(-span.years())
.addMonths(-span.months())
.addDays(-span.days());
return createUtcDateTime( dt ).addYears( -span.years() ).addMonths( -span.months() ).addDays( -span.days() );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QDateTime RiaQDateTimeTools::addPeriod(const QDateTime& dt, DateTimePeriod period)
QDateTime RiaQDateTimeTools::addPeriod( const QDateTime& dt, DateTimePeriod period )
{
return addSpan(dt, timeSpan(period));
return addSpan( dt, timeSpan( period ) );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QDateTime RiaQDateTimeTools::subtractPeriod(const QDateTime& dt, DateTimePeriod period)
QDateTime RiaQDateTimeTools::subtractPeriod( const QDateTime& dt, DateTimePeriod period )
{
return subtractSpan(dt, timeSpan(period));
return subtractSpan( dt, timeSpan( period ) );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QDateTime RiaQDateTimeTools::epoch()
{
// NB: Not able to use QDateTime::fromMSecsSinceEpoch as this was introduced in Qt 4.7
QDateTime dt;
dt.setDate(QDate(1970, 1, 1));
dt.setTimeSpec(currentTimeSpec());
dt.setDate( QDate( 1970, 1, 1 ) );
dt.setTimeSpec( currentTimeSpec() );
return dt;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QDateTime RiaQDateTimeTools::createUtcDateTime()
{
auto qdt = QDateTime();
qdt.setTimeSpec(currentTimeSpec());
qdt.setTimeSpec( currentTimeSpec() );
return qdt;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QDateTime RiaQDateTimeTools::createUtcDateTime(const QDate& date)
QDateTime RiaQDateTimeTools::createUtcDateTime( const QDate& date )
{
auto qdt = QDateTime(date);
qdt.setTimeSpec(currentTimeSpec());
auto qdt = QDateTime( date );
qdt.setTimeSpec( currentTimeSpec() );
return qdt;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QDateTime RiaQDateTimeTools::createUtcDateTime(const QDate& date, const QTime& time)
QDateTime RiaQDateTimeTools::createUtcDateTime( const QDate& date, const QTime& time )
{
auto qdt = QDateTime(date, time, currentTimeSpec());
auto qdt = QDateTime( date, time, currentTimeSpec() );
return qdt;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QDateTime RiaQDateTimeTools::createUtcDateTime(const QDateTime& dt)
QDateTime RiaQDateTimeTools::createUtcDateTime( const QDateTime& dt )
{
auto qdt = QDateTime(dt);
qdt.setTimeSpec(currentTimeSpec());
auto qdt = QDateTime( dt );
qdt.setTimeSpec( currentTimeSpec() );
return qdt;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
bool RiaQDateTimeTools::lessThan(const QDateTime& dt1, const QDateTime& dt2)
bool RiaQDateTimeTools::lessThan( const QDateTime& dt1, const QDateTime& dt2 )
{
// dt1 < dt2
return dt1.secsTo(dt2) > 0;
return dt1.secsTo( dt2 ) > 0;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const DateTimeSpan RiaQDateTimeTools::timeSpan(DateTimePeriod period)
const DateTimeSpan RiaQDateTimeTools::timeSpan( DateTimePeriod period )
{
switch (period)
switch ( period )
{
case DateTimePeriod::DAY: return TIMESPAN_DAY;
case DateTimePeriod::WEEK: return TIMESPAN_WEEK;
case DateTimePeriod::MONTH: return TIMESPAN_MONTH;
case DateTimePeriod::QUARTER: return TIMESPAN_QUARTER;
case DateTimePeriod::HALFYEAR: return TIMESPAN_HALFYEAR;
case DateTimePeriod::YEAR: return TIMESPAN_YEAR;
case DateTimePeriod::DECADE: return TIMESPAN_DECADE;
case DateTimePeriod::DAY:
return TIMESPAN_DAY;
case DateTimePeriod::WEEK:
return TIMESPAN_WEEK;
case DateTimePeriod::MONTH:
return TIMESPAN_MONTH;
case DateTimePeriod::QUARTER:
return TIMESPAN_QUARTER;
case DateTimePeriod::HALFYEAR:
return TIMESPAN_HALFYEAR;
case DateTimePeriod::YEAR:
return TIMESPAN_YEAR;
case DateTimePeriod::DECADE:
return TIMESPAN_DECADE;
}
CVF_ASSERT(false);
CVF_ASSERT( false );
return DateTimeSpan();
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QDateTime RiaQDateTimeTools::truncateTime(const QDateTime& dt, DateTimePeriod period)
QDateTime RiaQDateTimeTools::truncateTime( const QDateTime& dt, DateTimePeriod period )
{
int y = dt.date().year();
int m = dt.date().month();
int d = dt.date().day();
int y = dt.date().year();
int m = dt.date().month();
int d = dt.date().day();
int dow = dt.date().dayOfWeek();
switch (period)
switch ( period )
{
case DateTimePeriod::DAY: return createUtcDateTime(QDate(y, m, d));
case DateTimePeriod::WEEK: return createUtcDateTime(QDate(y, m, d).addDays(-dow + 1));
case DateTimePeriod::MONTH: return createUtcDateTime(QDate(y, m, 1));
case DateTimePeriod::QUARTER: return createUtcDateTime(QDate(y, ((m - 1) / 3) * 3 + 1, 1));
case DateTimePeriod::HALFYEAR: return createUtcDateTime(QDate(y, ((m - 1) / 6) * 6 + 1, 1));
case DateTimePeriod::YEAR: return createUtcDateTime(QDate(y, 1, 1));
case DateTimePeriod::DECADE: return createUtcDateTime(QDate((y / 10) * 10, 1, 1));
case DateTimePeriod::DAY:
return createUtcDateTime( QDate( y, m, d ) );
case DateTimePeriod::WEEK:
return createUtcDateTime( QDate( y, m, d ).addDays( -dow + 1 ) );
case DateTimePeriod::MONTH:
return createUtcDateTime( QDate( y, m, 1 ) );
case DateTimePeriod::QUARTER:
return createUtcDateTime( QDate( y, ( ( m - 1 ) / 3 ) * 3 + 1, 1 ) );
case DateTimePeriod::HALFYEAR:
return createUtcDateTime( QDate( y, ( ( m - 1 ) / 6 ) * 6 + 1, 1 ) );
case DateTimePeriod::YEAR:
return createUtcDateTime( QDate( y, 1, 1 ) );
case DateTimePeriod::DECADE:
return createUtcDateTime( QDate( ( y / 10 ) * 10, 1, 1 ) );
}
CVF_ASSERT(false);
CVF_ASSERT( false );
return createUtcDateTime();
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
std::vector<DateTimePeriod> RiaQDateTimeTools::dateTimePeriods()
{
return std::vector<DateTimePeriod>(
{
DateTimePeriod::NONE,
DateTimePeriod::DAY,
DateTimePeriod::WEEK,
DateTimePeriod::MONTH,
DateTimePeriod::QUARTER,
DateTimePeriod::HALFYEAR,
DateTimePeriod::YEAR,
DateTimePeriod::DECADE,
});
return std::vector<DateTimePeriod>( {
DateTimePeriod::NONE,
DateTimePeriod::DAY,
DateTimePeriod::WEEK,
DateTimePeriod::MONTH,
DateTimePeriod::QUARTER,
DateTimePeriod::HALFYEAR,
DateTimePeriod::YEAR,
DateTimePeriod::DECADE,
} );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QString RiaQDateTimeTools::dateTimePeriodName(DateTimePeriod period)
QString RiaQDateTimeTools::dateTimePeriodName( DateTimePeriod period )
{
switch (period)
switch ( period )
{
case DateTimePeriod::DAY: return TIMESPAN_DAY_NAME;
case DateTimePeriod::WEEK: return TIMESPAN_WEEK_NAME;
case DateTimePeriod::MONTH: return TIMESPAN_MONTH_NAME;
case DateTimePeriod::QUARTER: return TIMESPAN_QUARTER_NAME;
case DateTimePeriod::HALFYEAR: return TIMESPAN_HALFYEAR_NAME;
case DateTimePeriod::YEAR: return TIMESPAN_YEAR_NAME;
case DateTimePeriod::DECADE: return TIMESPAN_DECADE_NAME;
default: return "None";
case DateTimePeriod::DAY:
return TIMESPAN_DAY_NAME;
case DateTimePeriod::WEEK:
return TIMESPAN_WEEK_NAME;
case DateTimePeriod::MONTH:
return TIMESPAN_MONTH_NAME;
case DateTimePeriod::QUARTER:
return TIMESPAN_QUARTER_NAME;
case DateTimePeriod::HALFYEAR:
return TIMESPAN_HALFYEAR_NAME;
case DateTimePeriod::YEAR:
return TIMESPAN_YEAR_NAME;
case DateTimePeriod::DECADE:
return TIMESPAN_DECADE_NAME;
default:
return "None";
}
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QString RiaQDateTimeTools::toStringUsingApplicationLocale(const QDateTime& dt, const QString& format)
QString RiaQDateTimeTools::toStringUsingApplicationLocale( const QDateTime& dt, const QString& format )
{
// Default application locale is set in RiaMain
// QLocale::setDefault(QLocale(QLocale::English, QLocale::UnitedStates));
@@ -361,47 +373,46 @@ QString RiaQDateTimeTools::toStringUsingApplicationLocale(const QDateTime& dt, c
QLocale defaultApplicationLocale;
return defaultApplicationLocale.toString(dt, format);
return defaultApplicationLocale.toString( dt, format );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString RiaQDateTimeTools::createTimeFormatStringFromDates(const std::vector<QDateTime>& dates)
QString RiaQDateTimeTools::createTimeFormatStringFromDates( const std::vector<QDateTime>& dates )
{
bool hasHoursAndMinutesInTimesteps = false;
bool hasSecondsInTimesteps = false;
bool hasMillisecondsInTimesteps = false;
for (size_t i = 0; i < dates.size(); i++)
for ( size_t i = 0; i < dates.size(); i++ )
{
if (dates[i].time().msec() != 0.0)
if ( dates[i].time().msec() != 0.0 )
{
hasMillisecondsInTimesteps = true;
hasSecondsInTimesteps = true;
hasHoursAndMinutesInTimesteps = true;
break;
}
else if (dates[i].time().second() != 0.0)
else if ( dates[i].time().second() != 0.0 )
{
hasHoursAndMinutesInTimesteps = true;
hasSecondsInTimesteps = true;
}
else if (dates[i].time().hour() != 0.0 || dates[i].time().minute() != 0.0)
else if ( dates[i].time().hour() != 0.0 || dates[i].time().minute() != 0.0 )
{
hasHoursAndMinutesInTimesteps = true;
}
}
QString formatString = dateFormatString();
if (hasHoursAndMinutesInTimesteps)
if ( hasHoursAndMinutesInTimesteps )
{
formatString += " - hh:mm";
if (hasSecondsInTimesteps)
if ( hasSecondsInTimesteps )
{
formatString += ":ss";
if (hasMillisecondsInTimesteps)
if ( hasMillisecondsInTimesteps )
{
formatString += ".zzz";
}
@@ -429,20 +440,20 @@ std::vector<QString> RiaQDateTimeTools::supportedDateFormats()
// See enum DateFormatComponents in header
// The semi-colon separated components are:
// DATE_FORMAT_YEAR, ..YEAR_MONTH, ..YEAR_MONTH_DAY
dateFormats.push_back("yyyy;yyyy-MM;yyyy-MM-dd");
dateFormats.push_back("yyyy;MMM yyyy;dd. MMM yyyy");
dateFormats.push_back("yyyy;MMM yyyy;MMM dd. yyyy");
dateFormats.push_back("yyyy;MM/yyyy;dd/MM/yyyy");
dateFormats.push_back("yyyy;M/yyyy;d/M/yyyy");
dateFormats.push_back("yyyy;M/yyyy;M/d/yyyy");
dateFormats.push_back("yy;M/yy;d/M/yy");
dateFormats.push_back("yy;M/yy;M/d/yy");
dateFormats.push_back("yyyy;MM-yyyy;dd-MM-yyyy");
dateFormats.push_back("yyyy;MM.yyyy;dd.MM.yyyy");
dateFormats.push_back("yyyy;MM-yyyy;MM-dd-yyyy");
dateFormats.push_back("yyyy;MM.yyyy;MM.dd.yyyy");
dateFormats.push_back("yy;MM-yy;dd-MM-yy");
dateFormats.push_back("yy;MM-yy;MM-dd-yy");
dateFormats.push_back( "yyyy;yyyy-MM;yyyy-MM-dd" );
dateFormats.push_back( "yyyy;MMM yyyy;dd. MMM yyyy" );
dateFormats.push_back( "yyyy;MMM yyyy;MMM dd. yyyy" );
dateFormats.push_back( "yyyy;MM/yyyy;dd/MM/yyyy" );
dateFormats.push_back( "yyyy;M/yyyy;d/M/yyyy" );
dateFormats.push_back( "yyyy;M/yyyy;M/d/yyyy" );
dateFormats.push_back( "yy;M/yy;d/M/yy" );
dateFormats.push_back( "yy;M/yy;M/d/yy" );
dateFormats.push_back( "yyyy;MM-yyyy;dd-MM-yyyy" );
dateFormats.push_back( "yyyy;MM.yyyy;dd.MM.yyyy" );
dateFormats.push_back( "yyyy;MM-yyyy;MM-dd-yyyy" );
dateFormats.push_back( "yyyy;MM.yyyy;MM.dd.yyyy" );
dateFormats.push_back( "yy;MM-yy;dd-MM-yy" );
dateFormats.push_back( "yy;MM-yy;MM-dd-yy" );
return dateFormats;
}
@@ -457,10 +468,10 @@ std::vector<QString> RiaQDateTimeTools::supportedTimeFormats()
// See enum TimeFormatComponents in header
// The semi-colon separated components are:
// TIME_FORMAT_HOUR, ..HOUR_MINUTE, ..HOUR_MINUTE_SECOND and ..HOUR_MINUTE_MILLISECOND
timeFormats.push_back("HH;HH:mm;HH:mm:ss;HH:mm:ss.zzz");
timeFormats.push_back("H;H:mm;H:mm:ss;H:mm:ss.zzz");
timeFormats.push_back("hh AP;hh:mm AP;hh:mm:ss AP;hh:mm:ss.zzz AP");
timeFormats.push_back("h AP;h:mm AP;h:mm:ss AP;h:mm:ss.zzz AP");
timeFormats.push_back( "HH;HH:mm;HH:mm:ss;HH:mm:ss.zzz" );
timeFormats.push_back( "H;H:mm;H:mm:ss;H:mm:ss.zzz" );
timeFormats.push_back( "hh AP;hh:mm AP;hh:mm:ss AP;hh:mm:ss.zzz AP" );
timeFormats.push_back( "h AP;h:mm AP;h:mm:ss AP;h:mm:ss.zzz AP" );
return timeFormats;
}
@@ -468,31 +479,31 @@ std::vector<QString> RiaQDateTimeTools::supportedTimeFormats()
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString RiaQDateTimeTools::dateFormatString(const QString& fullDateFormat, DateFormatComponents dateComponents)
QString RiaQDateTimeTools::dateFormatString( const QString& fullDateFormat, DateFormatComponents dateComponents )
{
if (dateComponents == DATE_FORMAT_NONE) return "";
if ( dateComponents == DATE_FORMAT_NONE ) return "";
QStringList allVariants = fullDateFormat.split(";");
if (static_cast<int>(dateComponents) < allVariants.size())
QStringList allVariants = fullDateFormat.split( ";" );
if ( static_cast<int>( dateComponents ) < allVariants.size() )
{
return allVariants[dateComponents];
}
CVF_ASSERT(false && "Date format string is malformed");
CVF_ASSERT( false && "Date format string is malformed" );
return "";
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString RiaQDateTimeTools::timeFormatString(const QString& fullTimeFormat, TimeFormatComponents timeComponents)
QString RiaQDateTimeTools::timeFormatString( const QString& fullTimeFormat, TimeFormatComponents timeComponents )
{
if (timeComponents == TIME_FORMAT_NONE) return "";
if ( timeComponents == TIME_FORMAT_NONE ) return "";
QStringList allVariants = fullTimeFormat.split(";");
if (static_cast<int>(timeComponents) < allVariants.size())
QStringList allVariants = fullTimeFormat.split( ";" );
if ( static_cast<int>( timeComponents ) < allVariants.size() )
{
return allVariants[timeComponents];
}
CVF_ASSERT(false && "Time format string is malformed");
CVF_ASSERT( false && "Time format string is malformed" );
return "";
}

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017 Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE.
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -36,7 +36,7 @@ class QTime;
class DateTimeSpan;
//==================================================================================================
//
//
//==================================================================================================
enum class DateTimePeriod
{
@@ -51,7 +51,7 @@ enum class DateTimePeriod
};
//==================================================================================================
//
//
//==================================================================================================
class RiaQDateTimeTools
{
@@ -66,9 +66,9 @@ class RiaQDateTimeTools
public:
enum DateFormatComponents
{
DATE_FORMAT_UNSPECIFIED = -2,
DATE_FORMAT_NONE = -1,
DATE_FORMAT_YEAR = 0,
DATE_FORMAT_UNSPECIFIED = -2,
DATE_FORMAT_NONE = -1,
DATE_FORMAT_YEAR = 0,
DATE_FORMAT_YEAR_MONTH,
DATE_FORMAT_YEAR_MONTH_DAY,
DATE_FORMAT_SIZE
@@ -76,8 +76,8 @@ public:
enum TimeFormatComponents
{
TIME_FORMAT_UNSPECIFIED = -2,
TIME_FORMAT_NONE = -1,
TIME_FORMAT_UNSPECIFIED = -2,
TIME_FORMAT_NONE = -1,
TIME_FORMAT_HOUR,
TIME_FORMAT_HOUR_MINUTE,
TIME_FORMAT_HOUR_MINUTE_SECOND,
@@ -95,66 +95,87 @@ public:
static Qt::TimeSpec currentTimeSpec();
static QDateTime fromString(const QString& dateString, const QString& format);
static QDateTime fromYears(double years);
static QDateTime fromTime_t(time_t t);
static QDateTime fromString( const QString& dateString, const QString& format );
static QDateTime fromYears( double years );
static QDateTime fromTime_t( time_t t );
static QDateTime addMSecs(const QDateTime& dt, double msecs);
static QDateTime addDays(const QDateTime& dt, double days);
static QDateTime addYears(const QDateTime& dt, double years);
static QDateTime addSpan(const QDateTime& dt, DateTimeSpan span);
static QDateTime subtractSpan(const QDateTime& dt, DateTimeSpan span);
static QDateTime addPeriod(const QDateTime& dt, DateTimePeriod period);
static QDateTime subtractPeriod(const QDateTime& dt, DateTimePeriod period);
static QDateTime addMSecs( const QDateTime& dt, double msecs );
static QDateTime addDays( const QDateTime& dt, double days );
static QDateTime addYears( const QDateTime& dt, double years );
static QDateTime addSpan( const QDateTime& dt, DateTimeSpan span );
static QDateTime subtractSpan( const QDateTime& dt, DateTimeSpan span );
static QDateTime addPeriod( const QDateTime& dt, DateTimePeriod period );
static QDateTime subtractPeriod( const QDateTime& dt, DateTimePeriod period );
static QDateTime epoch();
static QDateTime createUtcDateTime();
static QDateTime createUtcDateTime(const QDate& date);
static QDateTime createUtcDateTime(const QDate& date, const QTime& time);
static QDateTime createUtcDateTime(const QDateTime& dt);
static QDateTime createUtcDateTime( const QDate& date );
static QDateTime createUtcDateTime( const QDate& date, const QTime& time );
static QDateTime createUtcDateTime( const QDateTime& dt );
static bool lessThan(const QDateTime& dt1, const QDateTime& dt2);
static bool lessThan( const QDateTime& dt1, const QDateTime& dt2 );
static const DateTimeSpan timeSpan(DateTimePeriod period);
static QDateTime truncateTime(const QDateTime& dt, DateTimePeriod period);
static const DateTimeSpan timeSpan( DateTimePeriod period );
static QDateTime truncateTime( const QDateTime& dt, DateTimePeriod period );
static std::vector<DateTimePeriod> dateTimePeriods();
static QString dateTimePeriodName(DateTimePeriod period);
static std::vector<DateTimePeriod> dateTimePeriods();
static QString dateTimePeriodName( DateTimePeriod period );
// This function uses C locale to make sure the text representation of a date is stable, independent of the locale
// settings on local machine. Required for stable regression testing.
static QString toStringUsingApplicationLocale(const QDateTime& dt, const QString& format);
static QString toStringUsingApplicationLocale( const QDateTime& dt, const QString& format );
static QString createTimeFormatStringFromDates(const std::vector<QDateTime>& dates);
static QString createTimeFormatStringFromDates( const std::vector<QDateTime>& dates );
static QString dateFormatString();
static std::vector<QString> supportedDateFormats();
static std::vector<QString> supportedTimeFormats();
static QString dateFormatString(const QString& fullDateFormat, DateFormatComponents dateComponents);
static QString timeFormatString(const QString& fullTimeFormat, TimeFormatComponents timeComponents);
static QString dateFormatString( const QString& fullDateFormat, DateFormatComponents dateComponents );
static QString timeFormatString( const QString& fullTimeFormat, TimeFormatComponents timeComponents );
private:
static quint64 secondsInDay();
static quint64 secondsInYear();
static quint64 secondsInDay();
static quint64 secondsInYear();
};
//==================================================================================================
///
///
//==================================================================================================
class DateTimeSpan
{
public:
DateTimeSpan() : m_years(0), m_months(0), m_days(0) { }
DateTimeSpan(int years, int months, int days) : m_years(years), m_months(months), m_days(days) { }
DateTimeSpan()
: m_years( 0 )
, m_months( 0 )
, m_days( 0 )
{
}
DateTimeSpan( int years, int months, int days )
: m_years( years )
, m_months( months )
, m_days( days )
{
}
int years() const { return m_years; }
int months() const { return m_months; }
int days() const { return m_days; }
int years() const
{
return m_years;
}
int months() const
{
return m_months;
}
int days() const
{
return m_days;
}
bool isEmpty() { return m_years == 0 && m_months == 0 && m_days; }
bool isEmpty()
{
return m_years == 0 && m_months == 0 && m_days;
}
private:
int m_years;

View File

@@ -22,70 +22,80 @@
#include "cafPdmUiFilePathEditor.h"
#include "cafPdmUiTextEditor.h"
CAF_PDM_SOURCE_INIT(RiaRegressionTest, "RiaRegressionTest");
CAF_PDM_SOURCE_INIT( RiaRegressionTest, "RiaRegressionTest" );
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RiaRegressionTest::RiaRegressionTest(void)
RiaRegressionTest::RiaRegressionTest( void )
{
CAF_PDM_InitFieldNoDefault(&folderContainingCompareTool,
"workingFolder",
"Folder containing <b>compare</b>",
"",
"Location of compare tool from Image Magic suite",
"");
folderContainingCompareTool.uiCapability()->setUiEditorTypeName(caf::PdmUiFilePathEditor::uiEditorTypeName());
CAF_PDM_InitFieldNoDefault( &folderContainingCompareTool,
"workingFolder",
"Folder containing <b>compare</b>",
"",
"Location of compare tool from Image Magic suite",
"" );
folderContainingCompareTool.uiCapability()->setUiEditorTypeName( caf::PdmUiFilePathEditor::uiEditorTypeName() );
CAF_PDM_InitFieldNoDefault(&folderContainingDiffTool,
"folderContainingDiffTool",
"Folder containing <b>diff</b>",
"",
"Location of diff tool used for text compare",
"");
folderContainingDiffTool.uiCapability()->setUiEditorTypeName(caf::PdmUiFilePathEditor::uiEditorTypeName());
CAF_PDM_InitFieldNoDefault( &folderContainingDiffTool,
"folderContainingDiffTool",
"Folder containing <b>diff</b>",
"",
"Location of diff tool used for text compare",
"" );
folderContainingDiffTool.uiCapability()->setUiEditorTypeName( caf::PdmUiFilePathEditor::uiEditorTypeName() );
CAF_PDM_InitFieldNoDefault(&folderContainingGitTool,
"folderContainingGitTool",
"Folder containing <b>git</b>",
"",
"Location of git tool used for text compare",
"");
folderContainingGitTool.uiCapability()->setUiEditorTypeName(caf::PdmUiFilePathEditor::uiEditorTypeName());
CAF_PDM_InitFieldNoDefault( &folderContainingGitTool,
"folderContainingGitTool",
"Folder containing <b>git</b>",
"",
"Location of git tool used for text compare",
"" );
folderContainingGitTool.uiCapability()->setUiEditorTypeName( caf::PdmUiFilePathEditor::uiEditorTypeName() );
CAF_PDM_InitFieldNoDefault(&regressionTestFolder, "regressionTestFolder", "Regression Test Folder", "", "", "");
regressionTestFolder.uiCapability()->setUiEditorTypeName(caf::PdmUiFilePathEditor::uiEditorTypeName());
CAF_PDM_InitFieldNoDefault( &regressionTestFolder, "regressionTestFolder", "Regression Test Folder", "", "", "" );
regressionTestFolder.uiCapability()->setUiEditorTypeName( caf::PdmUiFilePathEditor::uiEditorTypeName() );
CAF_PDM_InitField(&showInteractiveDiffImages, "showInteractiveDiffImages", false, "Interactive Diff Images", "", "", "");
CAF_PDM_InitField(
&useOpenMPForGeometryCreation, "useOpenMPForGeometryCreation", true, "Use OpenMP For Geometry Creation", "", "", "");
CAF_PDM_InitField( &showInteractiveDiffImages, "showInteractiveDiffImages", false, "Interactive Diff Images", "", "", "" );
CAF_PDM_InitField( &useOpenMPForGeometryCreation,
"useOpenMPForGeometryCreation",
true,
"Use OpenMP For Geometry Creation",
"",
"",
"" );
CAF_PDM_InitField(&openReportInBrowser, "openReportInBrowser", false, "Open Generated Report in Browser", "", "", "");
CAF_PDM_InitField( &openReportInBrowser, "openReportInBrowser", false, "Open Generated Report in Browser", "", "", "" );
CAF_PDM_InitFieldNoDefault(
&testFilter,
"testFilter",
"Test Filter",
"",
"If empty, all tests are executed.\nTo execute a subset of tests, specify folder names separated by ;",
"");
testFilter.uiCapability()->setUiEditorTypeName(caf::PdmUiTextEditor::uiEditorTypeName());
CAF_PDM_InitFieldNoDefault( &testFilter,
"testFilter",
"Test Filter",
"",
"If empty, all tests are executed.\nTo execute a subset of tests, specify folder names "
"separated by ;",
"" );
testFilter.uiCapability()->setUiEditorTypeName( caf::PdmUiTextEditor::uiEditorTypeName() );
CAF_PDM_InitField(
&appendTestsAfterTestFilter, "appendTestsAfterTestFilter", false, "Append All Tests After Test Filter", "", "", "");
CAF_PDM_InitField( &appendTestsAfterTestFilter,
"appendTestsAfterTestFilter",
false,
"Append All Tests After Test Filter",
"",
"",
"" );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RiaRegressionTest::~RiaRegressionTest(void) {}
RiaRegressionTest::~RiaRegressionTest( void ) {}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaRegressionTest::writeSettingsToApplicationStore() const
{
caf::PdmSettings::writeFieldsToApplicationStore(this);
caf::PdmSettings::writeFieldsToApplicationStore( this );
}
//--------------------------------------------------------------------------------------------------
@@ -93,21 +103,21 @@ void RiaRegressionTest::writeSettingsToApplicationStore() const
//--------------------------------------------------------------------------------------------------
void RiaRegressionTest::readSettingsFromApplicationStore()
{
caf::PdmSettings::readFieldsFromApplicationStore(this);
caf::PdmSettings::readFieldsFromApplicationStore( this );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaRegressionTest::defineEditorAttribute(const caf::PdmFieldHandle* field,
QString uiConfigName,
caf::PdmUiEditorAttribute* attribute)
void RiaRegressionTest::defineEditorAttribute( const caf::PdmFieldHandle* field,
QString uiConfigName,
caf::PdmUiEditorAttribute* attribute )
{
if (field == &folderContainingDiffTool || field == &folderContainingCompareTool || field == &regressionTestFolder ||
field == &folderContainingGitTool)
if ( field == &folderContainingDiffTool || field == &folderContainingCompareTool ||
field == &regressionTestFolder || field == &folderContainingGitTool )
{
caf::PdmUiFilePathEditorAttribute* myAttr = dynamic_cast<caf::PdmUiFilePathEditorAttribute*>(attribute);
if (myAttr)
caf::PdmUiFilePathEditorAttribute* myAttr = dynamic_cast<caf::PdmUiFilePathEditorAttribute*>( attribute );
if ( myAttr )
{
myAttr->m_selectDirectory = true;
}

View File

@@ -27,8 +27,8 @@ class RiaRegressionTest : public caf::PdmObject
CAF_PDM_HEADER_INIT;
public:
RiaRegressionTest(void);
~RiaRegressionTest(void) override;
RiaRegressionTest( void );
~RiaRegressionTest( void ) override;
void writeSettingsToApplicationStore() const;
void readSettingsFromApplicationStore();
@@ -45,7 +45,7 @@ public:
caf::PdmField<bool> appendTestsAfterTestFilter;
protected:
void defineEditorAttribute(const caf::PdmFieldHandle* field,
QString uiConfigName,
caf::PdmUiEditorAttribute* attribute) override;
void defineEditorAttribute( const caf::PdmFieldHandle* field,
QString uiConfigName,
caf::PdmUiEditorAttribute* attribute ) override;
};

View File

@@ -69,21 +69,21 @@ const QString commandFileFilter = "commandfile-*";
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void logInfoTextWithTimeInSeconds(const QTime& time, const QString& msg)
void logInfoTextWithTimeInSeconds( const QTime& time, const QString& msg )
{
double timeRunning = time.elapsed() / 1000.0;
QString timeText = QString("(%1 s) ").arg(timeRunning, 0, 'f', 1);
QString timeText = QString( "(%1 s) " ).arg( timeRunning, 0, 'f', 1 );
RiaLogging::info(timeText + msg);
RiaLogging::info( timeText + msg );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RiaRegressionTestRunner::RiaRegressionTestRunner()
: m_runningRegressionTests(false)
, m_appendAllTestsAfterLastItemInFilter(false)
: m_runningRegressionTests( false )
, m_appendAllTestsAfterLastItemInFilter( false )
{
}
@@ -107,12 +107,12 @@ void RiaRegressionTestRunner::runRegressionTest()
RiaRegressionTest regressionTestConfig;
regressionTestConfig.readSettingsFromApplicationStore();
if (!regressionTestConfig.folderContainingCompareTool().isEmpty())
if ( !regressionTestConfig.folderContainingCompareTool().isEmpty() )
{
// Windows Only : The image compare tool requires current working directory to be at the folder
// containing the image compare tool
QDir::setCurrent(regressionTestConfig.folderContainingCompareTool());
QDir::setCurrent( regressionTestConfig.folderContainingCompareTool() );
}
QString generatedFolderName = RegTestNames::generatedFolderName;
@@ -121,78 +121,84 @@ void RiaRegressionTestRunner::runRegressionTest()
QString regTestProjectName = RegTestNames::testProjectName;
QString regTestFolderFilter = RegTestNames::testFolderFilter;
QDir testDir(m_rootPath); // If string is empty it will end up as cwd
testDir.setFilter(QDir::Dirs);
QDir testDir( m_rootPath ); // If string is empty it will end up as cwd
testDir.setFilter( QDir::Dirs );
QStringList dirNameFilter;
dirNameFilter.append(regTestFolderFilter);
testDir.setNameFilters(dirNameFilter);
dirNameFilter.append( regTestFolderFilter );
testDir.setNameFilters( dirNameFilter );
QFileInfoList folderList = subDirectoriesForTestExecution(testDir);
QFileInfoList folderList = subDirectoriesForTestExecution( testDir );
// delete diff and generated images
for (const QFileInfo& fi : folderList)
for ( const QFileInfo& fi : folderList )
{
QDir testCaseFolder(fi.filePath());
QDir testCaseFolder( fi.filePath() );
{
QDir genDir(testCaseFolder.filePath(generatedFolderName));
removeDirectoryWithContent(genDir);
QDir genDir( testCaseFolder.filePath( generatedFolderName ) );
removeDirectoryWithContent( genDir );
}
{
QDir diffDir(testCaseFolder.filePath(diffFolderName));
removeDirectoryWithContent(diffDir);
QDir diffDir( testCaseFolder.filePath( diffFolderName ) );
removeDirectoryWithContent( diffDir );
}
{
QDir generatedFiles(testCaseFolder.filePath(RegTestNames::generatedFilesFolderName));
removeDirectoryWithContent(generatedFiles);
QDir generatedFiles( testCaseFolder.filePath( RegTestNames::generatedFilesFolderName ) );
removeDirectoryWithContent( generatedFiles );
}
}
QString htmlReportFileName = generateHtmlReport(folderList, baseFolderName, generatedFolderName, diffFolderName, testDir);
QString htmlReportFileName = generateHtmlReport( folderList,
baseFolderName,
generatedFolderName,
diffFolderName,
testDir );
if (regressionTestConfig.openReportInBrowser())
if ( regressionTestConfig.openReportInBrowser() )
{
QDesktopServices::openUrl(htmlReportFileName);
QDesktopServices::openUrl( htmlReportFileName );
}
RiaLogging::info("--------------------------------------------------");
RiaLogging::info(QTime::currentTime().toString() + ": Launching regression tests");
RiaLogging::info("--------------------------------------------------");
RiaLogging::info( "--------------------------------------------------" );
RiaLogging::info( QTime::currentTime().toString() + ": Launching regression tests" );
RiaLogging::info( "--------------------------------------------------" );
QTime timeStamp;
timeStamp.start();
logInfoTextWithTimeInSeconds(timeStamp, "Starting regression tests\n");
logInfoTextWithTimeInSeconds( timeStamp, "Starting regression tests\n" );
for (const QFileInfo& folderFileInfo : folderList)
for ( const QFileInfo& folderFileInfo : folderList )
{
QDir testCaseFolder(folderFileInfo.filePath());
QDir testCaseFolder( folderFileInfo.filePath() );
bool anyCommandFilesExecuted = findAndExecuteCommandFiles(testCaseFolder, regressionTestConfig, htmlReportFileName);
bool anyCommandFilesExecuted = findAndExecuteCommandFiles( testCaseFolder,
regressionTestConfig,
htmlReportFileName );
if (!anyCommandFilesExecuted)
if ( !anyCommandFilesExecuted )
{
QString projectFileName;
if (testCaseFolder.exists(regTestProjectName + ".rip"))
if ( testCaseFolder.exists( regTestProjectName + ".rip" ) )
{
projectFileName = regTestProjectName + ".rip";
}
if (testCaseFolder.exists(regTestProjectName + ".rsp"))
if ( testCaseFolder.exists( regTestProjectName + ".rsp" ) )
{
projectFileName = regTestProjectName + ".rsp";
}
if (!projectFileName.isEmpty())
if ( !projectFileName.isEmpty() )
{
logInfoTextWithTimeInSeconds(timeStamp, "Initializing test :" + testCaseFolder.absolutePath());
logInfoTextWithTimeInSeconds( timeStamp, "Initializing test :" + testCaseFolder.absolutePath() );
RiaApplication* app = RiaApplication::instance();
app->loadProject(testCaseFolder.filePath(projectFileName));
app->loadProject( testCaseFolder.filePath( projectFileName ) );
// Wait until all command objects have completed
app->waitUntilCommandObjectsHasBeenProcessed();
@@ -201,56 +207,57 @@ void RiaRegressionTestRunner::runRegressionTest()
resizePlotWindows();
QString fullPathGeneratedFolder = testCaseFolder.absoluteFilePath(generatedFolderName);
RicSnapshotAllViewsToFileFeature::exportSnapshotOfAllViewsIntoFolder(fullPathGeneratedFolder);
QString fullPathGeneratedFolder = testCaseFolder.absoluteFilePath( generatedFolderName );
RicSnapshotAllViewsToFileFeature::exportSnapshotOfAllViewsIntoFolder( fullPathGeneratedFolder );
RicSnapshotAllPlotsToFileFeature::exportSnapshotOfAllPlotsIntoFolder(fullPathGeneratedFolder);
RicSnapshotAllPlotsToFileFeature::exportSnapshotOfAllPlotsIntoFolder( fullPathGeneratedFolder );
app->closeProject();
}
else
{
RiaLogging::error("Could not find a regression test file named : " + testCaseFolder.absolutePath() + "/" +
regTestProjectName + ".rsp");
RiaLogging::error( "Could not find a regression test file named : " + testCaseFolder.absolutePath() +
"/" + regTestProjectName + ".rsp" );
}
}
QDir baseDir(testCaseFolder.filePath(baseFolderName));
QDir genDir(testCaseFolder.filePath(generatedFolderName));
QDir diffDir(testCaseFolder.filePath(diffFolderName));
if (!diffDir.exists()) testCaseFolder.mkdir(diffFolderName);
baseDir.setFilter(QDir::Files);
QDir baseDir( testCaseFolder.filePath( baseFolderName ) );
QDir genDir( testCaseFolder.filePath( generatedFolderName ) );
QDir diffDir( testCaseFolder.filePath( diffFolderName ) );
if ( !diffDir.exists() ) testCaseFolder.mkdir( diffFolderName );
baseDir.setFilter( QDir::Files );
QStringList baseImageFileNames = baseDir.entryList();
for (int fIdx = 0; fIdx < baseImageFileNames.size(); ++fIdx)
for ( int fIdx = 0; fIdx < baseImageFileNames.size(); ++fIdx )
{
QString fileName = baseImageFileNames[fIdx];
RiaImageFileCompare imgComparator(RegTestNames::imageCompareExeName);
bool ok =
imgComparator.runComparison(genDir.filePath(fileName), baseDir.filePath(fileName), diffDir.filePath(fileName));
if (!ok)
RiaImageFileCompare imgComparator( RegTestNames::imageCompareExeName );
bool ok = imgComparator.runComparison( genDir.filePath( fileName ),
baseDir.filePath( fileName ),
diffDir.filePath( fileName ) );
if ( !ok )
{
qDebug() << "Error comparing :" << imgComparator.errorMessage() << "\n" << imgComparator.errorDetails();
}
}
logInfoTextWithTimeInSeconds(timeStamp, "Completed test :" + testCaseFolder.absolutePath());
logInfoTextWithTimeInSeconds( timeStamp, "Completed test :" + testCaseFolder.absolutePath() );
}
// Invoke git diff
{
QString folderContainingGit = regressionTestConfig.folderContainingGitTool();
RiaGitDiff gitDiff(folderContainingGit);
gitDiff.executeDiff(m_rootPath);
RiaGitDiff gitDiff( folderContainingGit );
gitDiff.executeDiff( m_rootPath );
QString diffText = gitDiff.diffOutput();
if (!diffText.isEmpty())
if ( !diffText.isEmpty() )
{
QFile file(htmlReportFileName);
if (file.open(QIODevice::Append | QIODevice::Text))
QFile file( htmlReportFileName );
if ( file.open( QIODevice::Append | QIODevice::Text ) )
{
QTextStream stream(&file);
QTextStream stream( &file );
QString divSectionForDiff = R"(
<div id = "destination-elem-id"[innerHtml] = "outputHtml">
@@ -292,10 +299,10 @@ document.getElementById("destination-elem-id").innerHTML = diffHtml;
}
}
RiaLogging::info("\n");
logInfoTextWithTimeInSeconds(timeStamp, "Completed regression tests");
RiaLogging::info( "\n" );
logInfoTextWithTimeInSeconds( timeStamp, "Completed regression tests" );
QDir::setCurrent(currentApplicationPath);
QDir::setCurrent( currentApplicationPath );
m_runningRegressionTests = false;
}
@@ -303,15 +310,15 @@ document.getElementById("destination-elem-id").innerHTML = diffHtml;
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool RiaRegressionTestRunner::findAndExecuteCommandFiles(const QDir& testCaseFolder,
const RiaRegressionTest& regressionTestConfig,
const QString& htmlReportFileName)
bool RiaRegressionTestRunner::findAndExecuteCommandFiles( const QDir& testCaseFolder,
const RiaRegressionTest& regressionTestConfig,
const QString& htmlReportFileName )
{
QStringList filterList;
filterList << RegTestNames::commandFileFilter;
QFileInfoList commandFileEntries = testCaseFolder.entryInfoList(filterList);
if (commandFileEntries.empty())
QFileInfoList commandFileEntries = testCaseFolder.entryInfoList( filterList );
if ( commandFileEntries.empty() )
{
return false;
}
@@ -320,53 +327,54 @@ bool RiaRegressionTestRunner::findAndExecuteCommandFiles(const QDir&
// Set current path to the folder containing the command file, as this is required when using file references
// in the command file
QDir::setCurrent(testCaseFolder.path());
QDir::setCurrent( testCaseFolder.path() );
for (const auto& fileInfo : commandFileEntries)
for ( const auto& fileInfo : commandFileEntries )
{
QString commandFile = fileInfo.absoluteFilePath();
QFile file(commandFile);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
QFile file( commandFile );
if ( !file.open( QIODevice::ReadOnly | QIODevice::Text ) )
{
RiaLogging::error("Failed to open command file : " + commandFile);
RiaLogging::error( "Failed to open command file : " + commandFile );
}
else
{
QTextStream in(&file);
RicfCommandFileExecutor::instance()->executeCommands(in);
QTextStream in( &file );
RicfCommandFileExecutor::instance()->executeCommands( in );
}
}
QDir::setCurrent(currentAbsolutePath);
QDir::setCurrent( currentAbsolutePath );
// Create diff based on generated folders
{
QString html;
RiaTextFileCompare textFileCompare(regressionTestConfig.folderContainingDiffTool());
RiaTextFileCompare textFileCompare( regressionTestConfig.folderContainingDiffTool() );
QString baseFilesFolderName = testCaseFolder.filePath(RegTestNames::baseFilesFolderName);
QString generatedFilesFolderName = testCaseFolder.filePath(RegTestNames::generatedFilesFolderName);
QString baseFilesFolderName = testCaseFolder.filePath( RegTestNames::baseFilesFolderName );
QString generatedFilesFolderName = testCaseFolder.filePath( RegTestNames::generatedFilesFolderName );
QFileInfo fib(baseFilesFolderName);
QFileInfo fig(generatedFilesFolderName);
QFileInfo fib( baseFilesFolderName );
QFileInfo fig( generatedFilesFolderName );
if (fib.exists() && fig.exists())
if ( fib.exists() && fig.exists() )
{
{
QString headerText = testCaseFolder.dirName();
html += "<table>\n";
html += " <tr>\n";
html += " <td colspan=\"3\" bgcolor=\"darkblue\" height=\"40\"> <b><font color=\"white\" size=\"3\"> " +
headerText + " </font></b> </td>\n";
html +=
" <td colspan=\"3\" bgcolor=\"darkblue\" height=\"40\"> <b><font color=\"white\" size=\"3\"> " +
headerText + " </font></b> </td>\n";
html += " </tr>\n";
textFileCompare.runComparison(baseFilesFolderName, generatedFilesFolderName);
textFileCompare.runComparison( baseFilesFolderName, generatedFilesFolderName );
QString diff = textFileCompare.diffOutput();
if (diff.isEmpty())
if ( diff.isEmpty() )
{
html += " <tr>\n";
html += " <td colspan=\"3\" bgcolor=\"lightgray\"> <font color=\"green\">No text diff "
@@ -384,16 +392,16 @@ bool RiaRegressionTestRunner::findAndExecuteCommandFiles(const QDir&
// Table end
html += "</table>\n";
if (!diff.isEmpty())
if ( !diff.isEmpty() )
{
html += QString("<code> %1 </code>").arg(diff);
html += QString( "<code> %1 </code>" ).arg( diff );
}
}
QFile file(htmlReportFileName);
if (file.open(QIODevice::Append | QIODevice::Text))
QFile file( htmlReportFileName );
if ( file.open( QIODevice::Append | QIODevice::Text ) )
{
QTextStream stream(&file);
QTextStream stream( &file );
stream << html;
}
@@ -406,11 +414,11 @@ bool RiaRegressionTestRunner::findAndExecuteCommandFiles(const QDir&
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString RiaRegressionTestRunner::generateHtmlReport(const QFileInfoList& folderList,
const QString& baseFolderName,
const QString& generatedFolderName,
const QString& diffFolderName,
const QDir& testDir)
QString RiaRegressionTestRunner::generateHtmlReport( const QFileInfoList& folderList,
const QString& baseFolderName,
const QString& generatedFolderName,
const QString& diffFolderName,
const QDir& testDir )
{
RiaImageCompareReporter imageCompareReporter;
@@ -420,32 +428,32 @@ QString RiaRegressionTestRunner::generateHtmlReport(const QFileInfoList& folderL
{
QSettings settings;
bool useInteractiveDiff = settings.value("showInteractiveDiffImages").toBool();
if (useInteractiveDiff)
bool useInteractiveDiff = settings.value( "showInteractiveDiffImages" ).toBool();
if ( useInteractiveDiff )
{
imageCompareReporter.showInteractiveOnly();
}
}
for (const QFileInfo& fi : folderList)
for ( const QFileInfo& fi : folderList )
{
QDir testCaseFolder(fi.filePath());
QDir testCaseFolder( fi.filePath() );
QString testFolderName = testCaseFolder.dirName();
QString reportBaseFolderName = testCaseFolder.filePath(baseFolderName);
QString reportGeneratedFolderName = testCaseFolder.filePath(generatedFolderName);
QString reportDiffFolderName = testCaseFolder.filePath(diffFolderName);
QString reportBaseFolderName = testCaseFolder.filePath( baseFolderName );
QString reportGeneratedFolderName = testCaseFolder.filePath( generatedFolderName );
QString reportDiffFolderName = testCaseFolder.filePath( diffFolderName );
imageCompareReporter.addImageDirectoryComparisonSet(testFolderName.toStdString(),
reportBaseFolderName.toStdString(),
reportGeneratedFolderName.toStdString(),
reportDiffFolderName.toStdString());
imageCompareReporter.addImageDirectoryComparisonSet( testFolderName.toStdString(),
reportBaseFolderName.toStdString(),
reportGeneratedFolderName.toStdString(),
reportDiffFolderName.toStdString() );
}
QString htmlReportFileName = testDir.filePath(RegTestNames::reportFileName);
QString htmlReportFileName = testDir.filePath( RegTestNames::reportFileName );
QString htmldiff2htmlText = diff2htmlHeaderText(m_rootPath);
imageCompareReporter.generateHTMLReport(htmlReportFileName.toStdString(), htmldiff2htmlText.toStdString());
QString htmldiff2htmlText = diff2htmlHeaderText( m_rootPath );
imageCompareReporter.generateHTMLReport( htmlReportFileName.toStdString(), htmldiff2htmlText.toStdString() );
return htmlReportFileName;
}
@@ -453,9 +461,9 @@ QString RiaRegressionTestRunner::generateHtmlReport(const QFileInfoList& folderL
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaRegressionTestRunner::removeDirectoryWithContent(QDir& dirToDelete)
void RiaRegressionTestRunner::removeDirectoryWithContent( QDir& dirToDelete )
{
caf::Utils::removeDirectoryAndFilesRecursively(dirToDelete.absolutePath());
caf::Utils::removeDirectoryAndFilesRecursively( dirToDelete.absolutePath() );
}
//--------------------------------------------------------------------------------------------------
@@ -464,33 +472,33 @@ void RiaRegressionTestRunner::removeDirectoryWithContent(QDir& dirToDelete)
void RiaRegressionTestRunner::regressionTestConfigureProject()
{
RiuMainWindow* mainWnd = RiuMainWindow::instance();
if (!mainWnd) return;
if ( !mainWnd ) return;
RimProject* proj = RiaApplication::instance()->project();
if (!proj) return;
if ( !proj ) return;
std::vector<RimCase*> projectCases;
proj->allCases(projectCases);
proj->allCases( projectCases );
for (RimCase* cas : projectCases)
for ( RimCase* cas : projectCases )
{
if (!cas) continue;
if ( !cas ) continue;
std::vector<Rim3dView*> views = cas->views();
for (Rim3dView* riv : views)
for ( Rim3dView* riv : views )
{
if (riv && riv->viewer())
if ( riv && riv->viewer() )
{
// Make sure all views are maximized for snapshotting
QMdiSubWindow* subWnd = mainWnd->findMdiSubWindow(riv->viewer()->layoutWidget());
if (subWnd)
QMdiSubWindow* subWnd = mainWnd->findMdiSubWindow( riv->viewer()->layoutWidget() );
if ( subWnd )
{
subWnd->showMaximized();
}
// This size is set to match the regression test reference images
riv->viewer()->setFixedSize(RiaRegressionTestRunner::regressionDefaultImageSize());
riv->viewer()->setFixedSize( RiaRegressionTestRunner::regressionDefaultImageSize() );
}
}
}
@@ -502,29 +510,29 @@ void RiaRegressionTestRunner::regressionTestConfigureProject()
void RiaRegressionTestRunner::resizePlotWindows()
{
RimProject* proj = RiaApplication::instance()->project();
if (!proj) return;
if ( !proj ) return;
RiuPlotMainWindow* plotMainWindow = RiaGuiApplication::instance()->mainPlotWindow();
if (!plotMainWindow) return;
if ( !plotMainWindow ) return;
std::vector<RimViewWindow*> viewWindows;
proj->mainPlotCollection()->descendantsIncludingThisOfType(viewWindows);
proj->mainPlotCollection()->descendantsIncludingThisOfType( viewWindows );
for (auto viewWindow : viewWindows)
for ( auto viewWindow : viewWindows )
{
if (viewWindow->isMdiWindow())
if ( viewWindow->isMdiWindow() )
{
QWidget* viewWidget = viewWindow->viewWidget();
if (viewWidget)
if ( viewWidget )
{
QMdiSubWindow* mdiWindow = plotMainWindow->findMdiSubWindow(viewWidget);
if (mdiWindow)
QMdiSubWindow* mdiWindow = plotMainWindow->findMdiSubWindow( viewWidget );
if ( mdiWindow )
{
mdiWindow->showNormal();
viewWidget->resize(RiaRegressionTestRunner::regressionDefaultImageSize());
viewWidget->resize( RiaRegressionTestRunner::regressionDefaultImageSize() );
}
}
}
@@ -536,23 +544,23 @@ void RiaRegressionTestRunner::resizePlotWindows()
//--------------------------------------------------------------------------------------------------
QSize RiaRegressionTestRunner::regressionDefaultImageSize()
{
return QSize(1000, 745);
return QSize( 1000, 745 );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QString RiaRegressionTestRunner::diff2htmlHeaderText(const QString& testRootPath)
QString RiaRegressionTestRunner::diff2htmlHeaderText( const QString& testRootPath )
{
QString html;
QString oldProjPath = QDir::fromNativeSeparators(testRootPath);
QStringList pathFolders = oldProjPath.split("/", QString::KeepEmptyParts);
QString oldProjPath = QDir::fromNativeSeparators( testRootPath );
QStringList pathFolders = oldProjPath.split( "/", QString::KeepEmptyParts );
QString path;
for (const auto& f : pathFolders)
for ( const auto& f : pathFolders )
{
if (f.compare("ProjectFiles", Qt::CaseInsensitive) == 0) break;
if ( f.compare( "ProjectFiles", Qt::CaseInsensitive ) == 0 ) break;
path += f;
path += "/";
}
@@ -568,7 +576,7 @@ QString RiaRegressionTestRunner::diff2htmlHeaderText(const QString& testRootPath
)";
QString pathToDiff2html = path + "diff2html/dist/";
html = html.replace("dist/", pathToDiff2html);
html = html.replace( "dist/", pathToDiff2html );
}
return html;
@@ -577,9 +585,9 @@ QString RiaRegressionTestRunner::diff2htmlHeaderText(const QString& testRootPath
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QFileInfoList RiaRegressionTestRunner::subDirectoriesForTestExecution(const QDir& directory)
QFileInfoList RiaRegressionTestRunner::subDirectoriesForTestExecution( const QDir& directory )
{
if (m_testFilter.isEmpty())
if ( m_testFilter.isEmpty() )
{
QFileInfoList folderList = directory.entryInfoList();
@@ -591,17 +599,18 @@ QFileInfoList RiaRegressionTestRunner::subDirectoriesForTestExecution(const QDir
QFileInfoList foldersMatchingTestFilter;
QFileInfoList folderList = directory.entryInfoList();
for (const auto& fi : folderList)
for ( const auto& fi : folderList )
{
QString path = fi.path();
QString baseName = fi.baseName();
for (const auto& s : m_testFilter)
for ( const auto& s : m_testFilter )
{
QString trimmed = s.trimmed();
if ((m_appendAllTestsAfterLastItemInFilter && anyMatchFound) || baseName.contains(trimmed, Qt::CaseInsensitive))
if ( ( m_appendAllTestsAfterLastItemInFilter && anyMatchFound ) ||
baseName.contains( trimmed, Qt::CaseInsensitive ) )
{
foldersMatchingTestFilter.push_back(fi);
foldersMatchingTestFilter.push_back( fi );
anyMatchFound = true;
}
}
@@ -619,23 +628,23 @@ void RiaRegressionTestRunner::executeRegressionTests()
testConfig.readSettingsFromApplicationStore();
QString testPath = testConfig.regressionTestFolder();
QStringList testFilter = testConfig.testFilter().split(";", QString::SkipEmptyParts);
QStringList testFilter = testConfig.testFilter().split( ";", QString::SkipEmptyParts );
if (testConfig.appendTestsAfterTestFilter)
if ( testConfig.appendTestsAfterTestFilter )
{
m_appendAllTestsAfterLastItemInFilter = true;
}
executeRegressionTests(testPath, testFilter);
executeRegressionTests( testPath, testFilter );
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaRegressionTestRunner::executeRegressionTests(const QString& regressionTestPath, const QStringList& testFilter)
void RiaRegressionTestRunner::executeRegressionTests( const QString& regressionTestPath, const QStringList& testFilter )
{
RiuMainWindow* mainWnd = RiuMainWindow::instance();
if (mainWnd)
if ( mainWnd )
{
mainWnd->hideAllDockWidgets();
mainWnd->statusBar()->close();
@@ -665,7 +674,7 @@ bool RiaRegressionTestRunner::isRunningRegressionTests() const
//--------------------------------------------------------------------------------------------------
bool RiaRegressionTestRunner::useOpenMPForGeometryCreation() const
{
if (!m_runningRegressionTests) return false;
if ( !m_runningRegressionTests ) return false;
return m_regressionTestSettings.useOpenMPForGeometryCreation;
}
@@ -673,34 +682,34 @@ bool RiaRegressionTestRunner::useOpenMPForGeometryCreation() const
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaRegressionTestRunner::updateRegressionTest(const QString& testRootPath)
void RiaRegressionTestRunner::updateRegressionTest( const QString& testRootPath )
{
// Find all sub folders
QDir testDir(testRootPath); // If string is empty it will end up as cwd
testDir.setFilter(QDir::Dirs);
QDir testDir( testRootPath ); // If string is empty it will end up as cwd
testDir.setFilter( QDir::Dirs );
QStringList dirNameFilter;
dirNameFilter.append(RegTestNames::testFolderFilter);
testDir.setNameFilters(dirNameFilter);
dirNameFilter.append( RegTestNames::testFolderFilter );
testDir.setNameFilters( dirNameFilter );
QFileInfoList folderList = testDir.entryInfoList();
for (const auto& fi : folderList)
for ( const auto& fi : folderList )
{
QDir testCaseFolder(fi.filePath());
QDir testCaseFolder( fi.filePath() );
QDir baseDir(testCaseFolder.filePath(RegTestNames::baseFolderName));
removeDirectoryWithContent(baseDir);
testCaseFolder.mkdir(RegTestNames::baseFolderName);
QDir baseDir( testCaseFolder.filePath( RegTestNames::baseFolderName ) );
removeDirectoryWithContent( baseDir );
testCaseFolder.mkdir( RegTestNames::baseFolderName );
QDir genDir(testCaseFolder.filePath(RegTestNames::generatedFolderName));
QDir genDir( testCaseFolder.filePath( RegTestNames::generatedFolderName ) );
QStringList imageFileNames = genDir.entryList();
for (int fIdx = 0; fIdx < imageFileNames.size(); ++fIdx)
for ( int fIdx = 0; fIdx < imageFileNames.size(); ++fIdx )
{
QString fileName = imageFileNames[fIdx];
QFile::copy(genDir.filePath(fileName), baseDir.filePath(fileName));
QFile::copy( genDir.filePath( fileName ), baseDir.filePath( fileName ) );
}
}
}

View File

@@ -35,13 +35,13 @@ class RiaRegressionTestRunner
public:
static RiaRegressionTestRunner* instance();
void executeRegressionTests(const QString& regressionTestPath, const QStringList& testFilter);
void executeRegressionTests( const QString& regressionTestPath, const QStringList& testFilter );
void executeRegressionTests();
bool isRunningRegressionTests() const;
bool useOpenMPForGeometryCreation() const;
static void updateRegressionTest(const QString& testRootPath);
static void updateRegressionTest( const QString& testRootPath );
static void regressionTestConfigureProject();
private:
@@ -49,21 +49,21 @@ private:
void runRegressionTest();
bool findAndExecuteCommandFiles(const QDir& testCaseFolder,
const RiaRegressionTest& regressionTestConfig,
const QString& htmlReportFileName);
bool findAndExecuteCommandFiles( const QDir& testCaseFolder,
const RiaRegressionTest& regressionTestConfig,
const QString& htmlReportFileName );
QString generateHtmlReport(const QFileInfoList& folderList,
const QString& baseFolderName,
const QString& generatedFolderName,
const QString& diffFolderName,
const QDir& testDir);
QString generateHtmlReport( const QFileInfoList& folderList,
const QString& baseFolderName,
const QString& generatedFolderName,
const QString& diffFolderName,
const QDir& testDir );
static void removeDirectoryWithContent(QDir& dirToDelete);
static void removeDirectoryWithContent( QDir& dirToDelete );
static void resizePlotWindows();
static QSize regressionDefaultImageSize();
static QString diff2htmlHeaderText(const QString& testRootPath);
QFileInfoList subDirectoriesForTestExecution(const QDir& directory);
static QString diff2htmlHeaderText( const QString& testRootPath );
QFileInfoList subDirectoriesForTestExecution( const QDir& directory );
private:
QString m_rootPath;

View File

@@ -29,44 +29,45 @@
#include "cafPdmUiOrdering.h"
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
std::vector<const RigWellPath*> RiaSimWellBranchTools::simulationWellBranches(const QString& simWellName, bool useAutoDetectionOfBranches)
std::vector<const RigWellPath*> RiaSimWellBranchTools::simulationWellBranches( const QString& simWellName,
bool useAutoDetectionOfBranches )
{
RiaApplication* app = RiaApplication::instance();
RimProject* proj = app->project();
RiaApplication* app = RiaApplication::instance();
RimProject* proj = app->project();
// Find first case containing the specified simulation well
auto simCases = proj->eclipseCases();
auto caseItr = std::find_if(simCases.begin(), simCases.end(), [&simWellName](const RimEclipseCase* eclCase) {
auto caseItr = std::find_if( simCases.begin(), simCases.end(), [&simWellName]( const RimEclipseCase* eclCase ) {
const auto& eclData = eclCase->eclipseCaseData();
return eclData != nullptr && eclData->hasSimulationWell(simWellName);
});
RimEclipseCase* eclipseCase = caseItr != simCases.end() ? *caseItr : nullptr;
return eclData != nullptr && eclData->hasSimulationWell( simWellName );
} );
RimEclipseCase* eclipseCase = caseItr != simCases.end() ? *caseItr : nullptr;
RigEclipseCaseData* eclCaseData = eclipseCase != nullptr ? eclipseCase->eclipseCaseData() : nullptr;
return eclCaseData != nullptr ?
eclCaseData->simulationWellBranches(simWellName, false, useAutoDetectionOfBranches) :
std::vector<const RigWellPath*>();
return eclCaseData != nullptr ? eclCaseData->simulationWellBranches( simWellName, false, useAutoDetectionOfBranches )
: std::vector<const RigWellPath*>();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
QList<caf::PdmOptionItemInfo>
RiaSimWellBranchTools::valueOptionsForBranchIndexField(const std::vector<const RigWellPath*>& simulationWellPaths)
RiaSimWellBranchTools::valueOptionsForBranchIndexField( const std::vector<const RigWellPath*>& simulationWellPaths )
{
QList<caf::PdmOptionItemInfo> options;
size_t branchCount = simulationWellPaths.size();
if (simulationWellPaths.size() == 0)
if ( simulationWellPaths.size() == 0 )
{
options.push_front(caf::PdmOptionItemInfo("None", -1));
options.push_front( caf::PdmOptionItemInfo( "None", -1 ) );
}
else
{
for (int bIdx = 0; bIdx < static_cast<int>(branchCount); ++bIdx)
for ( int bIdx = 0; bIdx < static_cast<int>( branchCount ); ++bIdx )
{
options.push_back(caf::PdmOptionItemInfo("Branch " + QString::number(bIdx + 1), QVariant::fromValue(bIdx)));
options.push_back(
caf::PdmOptionItemInfo( "Branch " + QString::number( bIdx + 1 ), QVariant::fromValue( bIdx ) ) );
}
}
@@ -76,35 +77,38 @@ QList<caf::PdmOptionItemInfo>
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaSimWellBranchTools::appendSimWellBranchFieldsIfRequiredFromWellName(caf::PdmUiOrdering* uiOrdering,
const QString& wellPathOrSimWellName,
const caf::PdmField<bool>& branchDetectionField,
const caf::PdmField<int>& branchIndexField)
void RiaSimWellBranchTools::appendSimWellBranchFieldsIfRequiredFromWellName( caf::PdmUiOrdering* uiOrdering,
const QString& wellPathOrSimWellName,
const caf::PdmField<bool>& branchDetectionField,
const caf::PdmField<int>& branchIndexField )
{
if (!RimWellPlotTools::hasAssociatedWellPath(wellPathOrSimWellName))
if ( !RimWellPlotTools::hasAssociatedWellPath( wellPathOrSimWellName ) )
{
const QString simWellName = RimWellPlotTools::simWellName(wellPathOrSimWellName);
const QString simWellName = RimWellPlotTools::simWellName( wellPathOrSimWellName );
RiaSimWellBranchTools::appendSimWellBranchFieldsIfRequiredFromSimWellName(uiOrdering, simWellName, branchDetectionField,
branchIndexField);
RiaSimWellBranchTools::appendSimWellBranchFieldsIfRequiredFromSimWellName( uiOrdering,
simWellName,
branchDetectionField,
branchIndexField );
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaSimWellBranchTools::appendSimWellBranchFieldsIfRequiredFromSimWellName(caf::PdmUiOrdering* uiOrdering,
const QString& simWellName,
const caf::PdmField<bool>& branchDetectionField,
const caf::PdmField<int>& branchIndexField)
void RiaSimWellBranchTools::appendSimWellBranchFieldsIfRequiredFromSimWellName(
caf::PdmUiOrdering* uiOrdering,
const QString& simWellName,
const caf::PdmField<bool>& branchDetectionField,
const caf::PdmField<int>& branchIndexField )
{
if (RiaSimWellBranchTools::simulationWellBranches(simWellName, true).size() > 1)
if ( RiaSimWellBranchTools::simulationWellBranches( simWellName, true ).size() > 1 )
{
uiOrdering->add(&branchDetectionField);
uiOrdering->add( &branchDetectionField );
if (RiaSimWellBranchTools::simulationWellBranches(simWellName, branchDetectionField).size() > 1)
if ( RiaSimWellBranchTools::simulationWellBranches( simWellName, branchDetectionField ).size() > 1 )
{
uiOrdering->add(&branchIndexField);
uiOrdering->add( &branchIndexField );
}
}
}
@@ -112,17 +116,17 @@ void RiaSimWellBranchTools::appendSimWellBranchFieldsIfRequiredFromSimWellName(c
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
int RiaSimWellBranchTools::clampBranchIndex(const QString& simWellName, int branchIndexValue, bool branchDetection)
int RiaSimWellBranchTools::clampBranchIndex( const QString& simWellName, int branchIndexValue, bool branchDetection )
{
auto branches = RiaSimWellBranchTools::simulationWellBranches(simWellName, branchDetection);
auto branches = RiaSimWellBranchTools::simulationWellBranches( simWellName, branchDetection );
if (branches.size() == 0)
if ( branches.size() == 0 )
{
return -1;
}
int maxIndexValue = static_cast<int>(branches.size()) - 1;
if (branchIndexValue > maxIndexValue)
int maxIndexValue = static_cast<int>( branches.size() ) - 1;
if ( branchIndexValue > maxIndexValue )
{
branchIndexValue = maxIndexValue;
}

View File

@@ -39,19 +39,21 @@ class PdmUiOrdering;
class RiaSimWellBranchTools
{
public:
static std::vector<const RigWellPath*> simulationWellBranches(const QString& simWellName, bool useAutoDetectionOfBranches);
static std::vector<const RigWellPath*> simulationWellBranches( const QString& simWellName,
bool useAutoDetectionOfBranches );
static QList<caf::PdmOptionItemInfo>
valueOptionsForBranchIndexField(const std::vector<const RigWellPath*>& simulationWellPaths);
valueOptionsForBranchIndexField( const std::vector<const RigWellPath*>& simulationWellPaths );
static void appendSimWellBranchFieldsIfRequiredFromWellName(caf::PdmUiOrdering* uiOrdering,
const QString& wellPathOrSimWellName,
const caf::PdmField<bool>& branchDetectionField,
const caf::PdmField<int>& branchIndexField);
static void appendSimWellBranchFieldsIfRequiredFromWellName( caf::PdmUiOrdering* uiOrdering,
const QString& wellPathOrSimWellName,
const caf::PdmField<bool>& branchDetectionField,
const caf::PdmField<int>& branchIndexField );
static void appendSimWellBranchFieldsIfRequiredFromSimWellName(caf::PdmUiOrdering* uiOrdering, const QString& simWellName,
const caf::PdmField<bool>& branchDetectionField,
const caf::PdmField<int>& branchIndexField);
static void appendSimWellBranchFieldsIfRequiredFromSimWellName( caf::PdmUiOrdering* uiOrdering,
const QString& simWellName,
const caf::PdmField<bool>& branchDetectionField,
const caf::PdmField<int>& branchIndexField );
static int clampBranchIndex(const QString& simWellName, int branchIndexValue, bool branchDetection);
static int clampBranchIndex( const QString& simWellName, int branchIndexValue, bool branchDetection );
};

View File

@@ -3,17 +3,17 @@
// Copyright (C) 2011- Statoil ASA
// Copyright (C) 2013- Ceetron Solutions AS
// Copyright (C) 2011-2012 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>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -25,27 +25,27 @@
#include <QString>
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const QString RiaStatisticsTools::replacePercentileByPValueText(const QString& percentile)
const QString RiaStatisticsTools::replacePercentileByPValueText( const QString& percentile )
{
QString result = percentile;
if (result == ENSEMBLE_STAT_P10_QUANTITY_NAME)
if ( result == ENSEMBLE_STAT_P10_QUANTITY_NAME )
{
result = ENSEMBLE_STAT_P90_QUANTITY_NAME;
}
else if (result == ENSEMBLE_STAT_P90_QUANTITY_NAME)
else if ( result == ENSEMBLE_STAT_P90_QUANTITY_NAME )
{
result = ENSEMBLE_STAT_P10_QUANTITY_NAME;
}
else if (percentile.contains(QString("%1:").arg(ENSEMBLE_STAT_P10_QUANTITY_NAME)))
else if ( percentile.contains( QString( "%1:" ).arg( ENSEMBLE_STAT_P10_QUANTITY_NAME ) ) )
{
result.replace(ENSEMBLE_STAT_P10_QUANTITY_NAME, ENSEMBLE_STAT_P90_QUANTITY_NAME);
result.replace( ENSEMBLE_STAT_P10_QUANTITY_NAME, ENSEMBLE_STAT_P90_QUANTITY_NAME );
}
else if (percentile.contains(QString("%1:").arg(ENSEMBLE_STAT_P90_QUANTITY_NAME)))
else if ( percentile.contains( QString( "%1:" ).arg( ENSEMBLE_STAT_P90_QUANTITY_NAME ) ) )
{
result.replace(ENSEMBLE_STAT_P90_QUANTITY_NAME, ENSEMBLE_STAT_P10_QUANTITY_NAME);
result.replace( ENSEMBLE_STAT_P90_QUANTITY_NAME, ENSEMBLE_STAT_P10_QUANTITY_NAME );
}
return result;
}

View File

@@ -3,17 +3,17 @@
// Copyright (C) 2011- Statoil ASA
// Copyright (C) 2013- Ceetron Solutions AS
// Copyright (C) 2011-2012 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>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -26,26 +26,26 @@ class QString;
//==================================================================================================
//
//
//
//
//==================================================================================================
class RiaStatisticsTools
{
public:
static const QString replacePercentileByPValueText(const QString& percentile);
static const QString replacePercentileByPValueText( const QString& percentile );
template<class NumberType> static bool isInvalidNumber(NumberType value)
template <class NumberType>
static bool isInvalidNumber( NumberType value )
{
return !isValidNumber<NumberType>(value);
return !isValidNumber<NumberType>( value );
}
template<class NumberType> static bool isValidNumber(NumberType value)
template <class NumberType>
static bool isValidNumber( NumberType value )
{
if (std::isinf(value)) return false;
if (std::isnan(value)) return false;
if ( std::isinf( value ) ) return false;
if ( std::isnan( value ) ) return false;
return true;
}
};

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017 Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE.
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -19,52 +19,52 @@
#include "RiaStdStringTools.h"
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
std::string RiaStdStringTools::trimString(const std::string& s)
std::string RiaStdStringTools::trimString( const std::string& s )
{
auto sCopy = s.substr(0, s.find_last_not_of(' ') + 1);
sCopy = sCopy.substr(sCopy.find_first_not_of(' '));
auto sCopy = s.substr( 0, s.find_last_not_of( ' ' ) + 1 );
sCopy = sCopy.substr( sCopy.find_first_not_of( ' ' ) );
return sCopy;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
bool RiaStdStringTools::isNumber(const std::string& s, char decimalPoint)
bool RiaStdStringTools::isNumber( const std::string& s, char decimalPoint )
{
if (s.size() == 0) return false;
if (findCharMatchCount(s, decimalPoint) > 1) return false;
if (findCharMatchCount(s, '-') > 1) return false;
if (findCharMatchCount(s, 'e') > 1) return false;
if (findCharMatchCount(s, 'E') > 1) return false;
if ( s.size() == 0 ) return false;
if ( findCharMatchCount( s, decimalPoint ) > 1 ) return false;
if ( findCharMatchCount( s, '-' ) > 1 ) return false;
if ( findCharMatchCount( s, 'e' ) > 1 ) return false;
if ( findCharMatchCount( s, 'E' ) > 1 ) return false;
std::string matchChars("0123456789eE-");
matchChars.append(1, decimalPoint);
return (s.find_first_not_of(matchChars) == std::string::npos);
std::string matchChars( "0123456789eE-" );
matchChars.append( 1, decimalPoint );
return ( s.find_first_not_of( matchChars ) == std::string::npos );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
int16_t RiaStdStringTools::toInt16(const std::string& s)
int16_t RiaStdStringTools::toInt16( const std::string& s )
{
return (int16_t)toInt(s);
return (int16_t)toInt( s );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
int RiaStdStringTools::toInt(const std::string& s)
int RiaStdStringTools::toInt( const std::string& s )
{
int intValue = -1;
try
{
intValue = std::stoi(s);
intValue = std::stoi( s );
}
catch (...)
catch ( ... )
{
}
@@ -72,70 +72,70 @@ int RiaStdStringTools::toInt(const std::string& s)
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
double RiaStdStringTools::toDouble(const std::string& s)
double RiaStdStringTools::toDouble( const std::string& s )
{
double doubleValue = -1.0;
char* end;
doubleValue = std::strtod(s.data(), &end);
doubleValue = std::strtod( s.data(), &end );
return doubleValue;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
bool RiaStdStringTools::containsAlphabetic(const std::string& s)
bool RiaStdStringTools::containsAlphabetic( const std::string& s )
{
return std::find_if(s.begin(), s.end(), [](char c) { return isalpha(c); }) != s.end();
return std::find_if( s.begin(), s.end(), []( char c ) { return isalpha( c ); } ) != s.end();
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
bool RiaStdStringTools::startsWithAlphabetic(const std::string& s)
bool RiaStdStringTools::startsWithAlphabetic( const std::string& s )
{
if (s.empty()) return false;
if ( s.empty() ) return false;
return isalpha(s[0]) != 0;
return isalpha( s[0] ) != 0;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
bool RiaStdStringTools::endsWith(const std::string& mainStr, const std::string& toMatch)
bool RiaStdStringTools::endsWith( const std::string& mainStr, const std::string& toMatch )
{
if (mainStr.size() >= toMatch.size() && mainStr.compare(mainStr.size() - toMatch.size(), toMatch.size(), toMatch) == 0)
if ( mainStr.size() >= toMatch.size() &&
mainStr.compare( mainStr.size() - toMatch.size(), toMatch.size(), toMatch ) == 0 )
return true;
else
return false;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
std::vector<std::string> RiaStdStringTools::splitStringBySpace(const std::string& s)
std::vector<std::string> RiaStdStringTools::splitStringBySpace( const std::string& s )
{
std::vector<std::string> words;
splitByDelimiter(s, words);
splitByDelimiter( s, words );
return words;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
size_t RiaStdStringTools::findCharMatchCount(const std::string& s, char c)
size_t RiaStdStringTools::findCharMatchCount( const std::string& s, char c )
{
size_t count = 0;
size_t pos = 0;
while ((pos = s.find_first_of(c, pos + 1)) != std::string::npos)
size_t pos = 0;
while ( ( pos = s.find_first_of( c, pos + 1 ) ) != std::string::npos )
{
count++;
}
return count;
}

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017 Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE.
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -30,39 +30,38 @@
class RiaStdStringTools
{
public:
static std::string trimString(const std::string& s);
static bool isNumber(const std::string& s, char decimalPoint);
static std::string trimString( const std::string& s );
static bool isNumber( const std::string& s, char decimalPoint );
static int16_t toInt16(const std::string& s);
static int toInt(const std::string& s);
static double toDouble(const std::string& s);
static bool containsAlphabetic(const std::string& s);
static bool startsWithAlphabetic(const std::string& s);
static int16_t toInt16( const std::string& s );
static int toInt( const std::string& s );
static double toDouble( const std::string& s );
static bool containsAlphabetic( const std::string& s );
static bool startsWithAlphabetic( const std::string& s );
static bool endsWith(const std::string& mainStr, const std::string& toMatch);
static bool endsWith( const std::string& mainStr, const std::string& toMatch );
static std::vector<std::string> splitStringBySpace(const std::string& s);
static std::vector<std::string> splitStringBySpace( const std::string& s );
private:
template <class Container>
static void splitByDelimiter(const std::string& str, Container& cont, char delimiter = ' ');
static size_t findCharMatchCount(const std::string& s, char c);
static void splitByDelimiter( const std::string& str, Container& cont, char delimiter = ' ' );
static size_t findCharMatchCount( const std::string& s, char c );
};
//==================================================================================================
//
//==================================================================================================
template <class Container>
void RiaStdStringTools::splitByDelimiter(const std::string& str, Container& cont, char delimiter)
void RiaStdStringTools::splitByDelimiter( const std::string& str, Container& cont, char delimiter )
{
std::stringstream ss(str);
std::string token;
while (std::getline(ss, token, delimiter))
std::stringstream ss( str );
std::string token;
while ( std::getline( ss, token, delimiter ) )
{
if (token.find_first_not_of(delimiter) != std::string::npos)
if ( token.find_first_not_of( delimiter ) != std::string::npos )
{
cont.push_back(token);
cont.push_back( token );
}
}
}

View File

@@ -3,41 +3,40 @@
// Copyright (C) 2011- Statoil ASA
// Copyright (C) 2013- Ceetron Solutions AS
// Copyright (C) 2011-2012 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>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
#include "RiaStringEncodingTools.h"
const std::string RiaStringEncodingTools::toNativeEncoded(const QString& qstring)
const std::string RiaStringEncodingTools::toNativeEncoded( const QString& qstring )
{
#ifdef WIN32
return std::string(qstring.toLatin1().data());
return std::string( qstring.toLatin1().data() );
#else
return std::string(qstring.toUtf8().data());
return std::string( qstring.toUtf8().data() );
#endif
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const QString RiaStringEncodingTools::fromNativeEncoded(const char* native)
const QString RiaStringEncodingTools::fromNativeEncoded( const char* native )
{
#ifdef WIN32
return QString::fromLatin1(native);
return QString::fromLatin1( native );
#else
return QString::fromUtf8(native);
return QString::fromUtf8( native );
#endif
}

View File

@@ -3,36 +3,36 @@
// Copyright (C) 2011- Statoil ASA
// Copyright (C) 2013- Ceetron Solutions AS
// Copyright (C) 2011-2012 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>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
#pragma once
#include <QString>
#include <QByteArray>
#include <QString>
#include <string>
//==================================================================================================
//
//
//
//
//==================================================================================================
class RiaStringEncodingTools
{
public:
static const std::string toNativeEncoded(const QString& qstring);
static const std::string toNativeEncoded( const QString& qstring );
static const QString fromNativeEncoded(const char* native);
static const QString fromNativeEncoded( const char* native );
};

View File

@@ -34,22 +34,22 @@ RiaSummaryCurveAnalyzer::RiaSummaryCurveAnalyzer() {}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaSummaryCurveAnalyzer::appendAdresses(const std::vector<RifEclipseSummaryAddress>& allAddresses)
void RiaSummaryCurveAnalyzer::appendAdresses( const std::vector<RifEclipseSummaryAddress>& allAddresses )
{
for (const auto& adr : allAddresses)
for ( const auto& adr : allAddresses )
{
analyzeSingleAddress(adr);
analyzeSingleAddress( adr );
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaSummaryCurveAnalyzer::appendAdresses(const std::set<RifEclipseSummaryAddress>& allAddresses)
void RiaSummaryCurveAnalyzer::appendAdresses( const std::set<RifEclipseSummaryAddress>& allAddresses )
{
for (const auto& adr : allAddresses)
for ( const auto& adr : allAddresses )
{
analyzeSingleAddress(adr);
analyzeSingleAddress( adr );
}
}
@@ -86,12 +86,12 @@ std::set<std::string> RiaSummaryCurveAnalyzer::quantityNamesNoHistory() const
//--------------------------------------------------------------------------------------------------
std::string RiaSummaryCurveAnalyzer::quantityNameForTitle() const
{
if (quantityNamesWithHistory().size() == 1 && quantityNamesNoHistory().empty())
if ( quantityNamesWithHistory().size() == 1 && quantityNamesNoHistory().empty() )
{
return *quantityNamesWithHistory().begin();
}
if (quantityNamesNoHistory().size() == 1 && quantityNamesWithHistory().empty())
if ( quantityNamesNoHistory().size() == 1 && quantityNamesWithHistory().empty() )
{
return *quantityNamesNoHistory().begin();
}
@@ -126,15 +126,15 @@ std::set<int> RiaSummaryCurveAnalyzer::regionNumbers() const
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
std::set<std::string> RiaSummaryCurveAnalyzer::wellCompletions(const std::string& wellName) const
std::set<std::string> RiaSummaryCurveAnalyzer::wellCompletions( const std::string& wellName ) const
{
std::set<std::string> connections;
for (const auto& conn : m_wellCompletions)
for ( const auto& conn : m_wellCompletions )
{
if (conn.first == wellName)
if ( conn.first == wellName )
{
connections.insert(conn.second);
connections.insert( conn.second );
}
}
@@ -144,15 +144,15 @@ std::set<std::string> RiaSummaryCurveAnalyzer::wellCompletions(const std::string
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
std::set<int> RiaSummaryCurveAnalyzer::wellSegmentNumbers(const std::string& wellName) const
std::set<int> RiaSummaryCurveAnalyzer::wellSegmentNumbers( const std::string& wellName ) const
{
std::set<int> segmentNumberForWell;
for (const auto& wellSegment : m_wellSegmentNumbers)
for ( const auto& wellSegment : m_wellSegmentNumbers )
{
if (wellName.empty() || std::get<0>(wellSegment) == wellName)
if ( wellName.empty() || std::get<0>( wellSegment ) == wellName )
{
segmentNumberForWell.insert(std::get<1>(wellSegment));
segmentNumberForWell.insert( std::get<1>( wellSegment ) );
}
}
@@ -178,53 +178,53 @@ std::set<RifEclipseSummaryAddress::SummaryVarCategory> RiaSummaryCurveAnalyzer::
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
std::vector<QString> RiaSummaryCurveAnalyzer::identifierTexts(RifEclipseSummaryAddress::SummaryVarCategory category,
const std::string& secondaryIdentifier) const
std::vector<QString> RiaSummaryCurveAnalyzer::identifierTexts( RifEclipseSummaryAddress::SummaryVarCategory category,
const std::string& secondaryIdentifier ) const
{
std::vector<QString> identifierStrings;
if (category == RifEclipseSummaryAddress::SUMMARY_REGION)
if ( category == RifEclipseSummaryAddress::SUMMARY_REGION )
{
for (const auto& regionNumber : m_regionNumbers)
for ( const auto& regionNumber : m_regionNumbers )
{
identifierStrings.push_back(QString::number(regionNumber));
identifierStrings.push_back( QString::number( regionNumber ) );
}
}
else if (category == RifEclipseSummaryAddress::SUMMARY_WELL)
else if ( category == RifEclipseSummaryAddress::SUMMARY_WELL )
{
for (const auto& wellName : m_wellNames)
for ( const auto& wellName : m_wellNames )
{
identifierStrings.push_back(QString::fromStdString(wellName));
identifierStrings.push_back( QString::fromStdString( wellName ) );
}
}
else if (category == RifEclipseSummaryAddress::SUMMARY_WELL_GROUP)
else if ( category == RifEclipseSummaryAddress::SUMMARY_WELL_GROUP )
{
for (const auto& wellGroupName : m_wellGroupNames)
for ( const auto& wellGroupName : m_wellGroupNames )
{
identifierStrings.push_back(QString::fromStdString(wellGroupName));
identifierStrings.push_back( QString::fromStdString( wellGroupName ) );
}
}
else if (category == RifEclipseSummaryAddress::SUMMARY_BLOCK)
else if ( category == RifEclipseSummaryAddress::SUMMARY_BLOCK )
{
for (const auto& ijkBlock : m_blocks)
for ( const auto& ijkBlock : m_blocks )
{
identifierStrings.push_back(QString::fromStdString(ijkBlock));
identifierStrings.push_back( QString::fromStdString( ijkBlock ) );
}
}
else if (category == RifEclipseSummaryAddress::SUMMARY_WELL_SEGMENT)
else if ( category == RifEclipseSummaryAddress::SUMMARY_WELL_SEGMENT )
{
auto segmentNumbers = wellSegmentNumbers(secondaryIdentifier);
for (const auto& segment : segmentNumbers)
auto segmentNumbers = wellSegmentNumbers( secondaryIdentifier );
for ( const auto& segment : segmentNumbers )
{
identifierStrings.push_back(QString::number(segment));
identifierStrings.push_back( QString::number( segment ) );
}
}
else if (category == RifEclipseSummaryAddress::SUMMARY_WELL_COMPLETION)
else if ( category == RifEclipseSummaryAddress::SUMMARY_WELL_COMPLETION )
{
auto connections = wellCompletions(secondaryIdentifier);
for (const auto& conn : connections)
auto connections = wellCompletions( secondaryIdentifier );
for ( const auto& conn : connections )
{
identifierStrings.push_back(QString::fromStdString(conn));
identifierStrings.push_back( QString::fromStdString( conn ) );
}
}
@@ -235,16 +235,16 @@ std::vector<QString> RiaSummaryCurveAnalyzer::identifierTexts(RifEclipseSummaryA
///
//--------------------------------------------------------------------------------------------------
std::vector<RifEclipseSummaryAddress>
RiaSummaryCurveAnalyzer::addressesForCategory(const std::set<RifEclipseSummaryAddress>& addresses,
RifEclipseSummaryAddress::SummaryVarCategory category)
RiaSummaryCurveAnalyzer::addressesForCategory( const std::set<RifEclipseSummaryAddress>& addresses,
RifEclipseSummaryAddress::SummaryVarCategory category )
{
std::vector<RifEclipseSummaryAddress> filteredAddresses;
for (const auto& adr : addresses)
for ( const auto& adr : addresses )
{
if (adr.category() == category)
if ( adr.category() == category )
{
filteredAddresses.push_back(adr);
filteredAddresses.push_back( adr );
}
}
@@ -254,13 +254,13 @@ std::vector<RifEclipseSummaryAddress>
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
std::string RiaSummaryCurveAnalyzer::correspondingHistorySummaryCurveName(const std::string& curveName)
std::string RiaSummaryCurveAnalyzer::correspondingHistorySummaryCurveName( const std::string& curveName )
{
static std::string historyIdentifier = "H";
if (RiaStdStringTools::endsWith(curveName, historyIdentifier))
if ( RiaStdStringTools::endsWith( curveName, historyIdentifier ) )
{
std::string candidate = curveName.substr(0, curveName.size() - 1);
std::string candidate = curveName.substr( 0, curveName.size() - 1 );
return candidate;
}
else
@@ -289,9 +289,9 @@ void RiaSummaryCurveAnalyzer::clear()
//--------------------------------------------------------------------------------------------------
void RiaSummaryCurveAnalyzer::assignCategoryToQuantities() const
{
if (!m_quantities.empty())
if ( !m_quantities.empty() )
{
if (m_quantitiesWithMatchingHistory.empty() && m_quantitiesNoMatchingHistory.empty())
if ( m_quantitiesWithMatchingHistory.empty() && m_quantitiesNoMatchingHistory.empty() )
{
computeQuantityNamesWithHistory();
}
@@ -306,27 +306,27 @@ void RiaSummaryCurveAnalyzer::computeQuantityNamesWithHistory() const
m_quantitiesNoMatchingHistory.clear();
m_quantitiesWithMatchingHistory.clear();
const std::string historyIdentifier("H");
const std::string historyIdentifier( "H" );
for (const auto& s : m_quantities)
for ( const auto& s : m_quantities )
{
std::string correspondingHistoryCurve = correspondingHistorySummaryCurveName(s);
std::string correspondingHistoryCurve = correspondingHistorySummaryCurveName( s );
if (m_quantities.find(correspondingHistoryCurve) != m_quantities.end())
if ( m_quantities.find( correspondingHistoryCurve ) != m_quantities.end() )
{
// Insert the curve name without H
if (RiaStdStringTools::endsWith(s, historyIdentifier))
if ( RiaStdStringTools::endsWith( s, historyIdentifier ) )
{
m_quantitiesWithMatchingHistory.insert(correspondingHistoryCurve);
m_quantitiesWithMatchingHistory.insert( correspondingHistoryCurve );
}
else
{
m_quantitiesWithMatchingHistory.insert(s);
m_quantitiesWithMatchingHistory.insert( s );
}
}
else
{
m_quantitiesNoMatchingHistory.insert(s);
m_quantitiesNoMatchingHistory.insert( s );
}
}
}
@@ -334,48 +334,48 @@ void RiaSummaryCurveAnalyzer::computeQuantityNamesWithHistory() const
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaSummaryCurveAnalyzer::analyzeSingleAddress(const RifEclipseSummaryAddress& address)
void RiaSummaryCurveAnalyzer::analyzeSingleAddress( const RifEclipseSummaryAddress& address )
{
const std::string& wellName = address.wellName();
if (!wellName.empty())
if ( !wellName.empty() )
{
m_wellNames.insert(wellName);
m_wellNames.insert( wellName );
}
if (!address.quantityName().empty())
if ( !address.quantityName().empty() )
{
m_quantities.insert(address.quantityName());
m_quantities.insert( address.quantityName() );
}
if (!address.wellGroupName().empty())
if ( !address.wellGroupName().empty() )
{
m_wellGroupNames.insert(address.wellGroupName());
m_wellGroupNames.insert( address.wellGroupName() );
}
if (address.regionNumber() != -1)
if ( address.regionNumber() != -1 )
{
m_regionNumbers.insert(address.regionNumber());
m_regionNumbers.insert( address.regionNumber() );
}
if (address.category() == RifEclipseSummaryAddress::SUMMARY_WELL_COMPLETION)
if ( address.category() == RifEclipseSummaryAddress::SUMMARY_WELL_COMPLETION )
{
auto wellNameAndCompletion = std::make_pair(wellName, address.blockAsString());
m_wellCompletions.insert(wellNameAndCompletion);
auto wellNameAndCompletion = std::make_pair( wellName, address.blockAsString() );
m_wellCompletions.insert( wellNameAndCompletion );
}
else if (address.category() == RifEclipseSummaryAddress::SUMMARY_WELL_SEGMENT)
else if ( address.category() == RifEclipseSummaryAddress::SUMMARY_WELL_SEGMENT )
{
auto wellNameAndSegment = std::make_pair(wellName, address.wellSegmentNumber());
m_wellSegmentNumbers.insert(wellNameAndSegment);
auto wellNameAndSegment = std::make_pair( wellName, address.wellSegmentNumber() );
m_wellSegmentNumbers.insert( wellNameAndSegment );
}
else if (address.category() == RifEclipseSummaryAddress::SUMMARY_BLOCK)
else if ( address.category() == RifEclipseSummaryAddress::SUMMARY_BLOCK )
{
auto text = address.blockAsString();
m_blocks.insert(text);
m_blocks.insert( text );
}
if (address.category() != RifEclipseSummaryAddress::SUMMARY_INVALID)
if ( address.category() != RifEclipseSummaryAddress::SUMMARY_INVALID )
{
m_categories.insert(address.category());
m_categories.insert( address.category() );
}
}

View File

@@ -37,8 +37,8 @@ class RiaSummaryCurveAnalyzer
public:
RiaSummaryCurveAnalyzer();
void appendAdresses(const std::set<RifEclipseSummaryAddress>& allAddresses);
void appendAdresses(const std::vector<RifEclipseSummaryAddress>& allAddresses);
void appendAdresses( const std::set<RifEclipseSummaryAddress>& allAddresses );
void appendAdresses( const std::vector<RifEclipseSummaryAddress>& allAddresses );
void clear();
@@ -52,25 +52,26 @@ public:
std::set<std::string> wellGroupNames() const;
std::set<int> regionNumbers() const;
std::set<std::string> wellCompletions(const std::string& wellName) const;
std::set<int> wellSegmentNumbers(const std::string& wellName) const;
std::set<std::string> wellCompletions( const std::string& wellName ) const;
std::set<int> wellSegmentNumbers( const std::string& wellName ) const;
std::set<std::string> blocks() const;
std::set<RifEclipseSummaryAddress::SummaryVarCategory> categories() const;
std::vector<QString> identifierTexts(RifEclipseSummaryAddress::SummaryVarCategory category,
const std::string& secondaryIdentifier) const;
std::vector<QString> identifierTexts( RifEclipseSummaryAddress::SummaryVarCategory category,
const std::string& secondaryIdentifier ) const;
static std::vector<RifEclipseSummaryAddress> addressesForCategory(const std::set<RifEclipseSummaryAddress>& addresses,
RifEclipseSummaryAddress::SummaryVarCategory category);
static std::vector<RifEclipseSummaryAddress>
addressesForCategory( const std::set<RifEclipseSummaryAddress>& addresses,
RifEclipseSummaryAddress::SummaryVarCategory category );
static std::string correspondingHistorySummaryCurveName(const std::string& curveName);
static std::string correspondingHistorySummaryCurveName( const std::string& curveName );
private:
void assignCategoryToQuantities() const;
void computeQuantityNamesWithHistory() const;
void analyzeSingleAddress(const RifEclipseSummaryAddress& address);
void analyzeSingleAddress( const RifEclipseSummaryAddress& address );
private:
std::set<std::string> m_quantities;

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017 Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE.
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -22,8 +22,8 @@
#include "RifEclipseSummaryAddress.h"
#include "RimOilField.h"
#include "RimMainPlotCollection.h"
#include "RimOilField.h"
#include "RimProject.h"
#include "RimSummaryCaseMainCollection.h"
#include "RimSummaryCrossPlot.h"
@@ -31,11 +31,11 @@
#include "RimSummaryPlot.h"
#include "RimSummaryPlotCollection.h"
#include "cafPdmObject.h"
#include "RimSummaryCrossPlotCollection.h"
#include "cafPdmObject.h"
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
RimSummaryPlotCollection* RiaSummaryTools::summaryPlotCollection()
{
@@ -49,30 +49,32 @@ RimSummaryPlotCollection* RiaSummaryTools::summaryPlotCollection()
//--------------------------------------------------------------------------------------------------
RimSummaryCaseMainCollection* RiaSummaryTools::summaryCaseMainCollection()
{
RimProject* project = RiaApplication::instance()->project();
RimProject* project = RiaApplication::instance()->project();
RimSummaryCaseMainCollection* summaryCaseMainCollection = project->activeOilField()->summaryCaseMainCollection();
CVF_ASSERT(summaryCaseMainCollection);
CVF_ASSERT( summaryCaseMainCollection );
return summaryCaseMainCollection;
}
//--------------------------------------------------------------------------------------------------
/// Update the summary curves referencing this curve, as the curve is identified by the name
//--------------------------------------------------------------------------------------------------
void RiaSummaryTools::notifyCalculatedCurveNameHasChanged(const QString& previousCurveName, const QString& currentCurveName)
void RiaSummaryTools::notifyCalculatedCurveNameHasChanged( const QString& previousCurveName,
const QString& currentCurveName )
{
RimSummaryPlotCollection* summaryPlotColl = RiaSummaryTools::summaryPlotCollection();
for (RimSummaryPlot* plot : summaryPlotColl->summaryPlots())
for ( RimSummaryPlot* plot : summaryPlotColl->summaryPlots() )
{
for (RimSummaryCurve* curve : plot->summaryCurves())
for ( RimSummaryCurve* curve : plot->summaryCurves() )
{
RifEclipseSummaryAddress adr = curve->summaryAddressY();
if (adr.category() == RifEclipseSummaryAddress::SUMMARY_CALCULATED)
if ( adr.category() == RifEclipseSummaryAddress::SUMMARY_CALCULATED )
{
if (adr.quantityName() == previousCurveName.toStdString())
if ( adr.quantityName() == previousCurveName.toStdString() )
{
RifEclipseSummaryAddress updatedAdr = RifEclipseSummaryAddress::calculatedAddress(currentCurveName.toStdString());
curve->setSummaryAddressYAndApplyInterpolation(updatedAdr);
RifEclipseSummaryAddress updatedAdr = RifEclipseSummaryAddress::calculatedAddress(
currentCurveName.toStdString() );
curve->setSummaryAddressYAndApplyInterpolation( updatedAdr );
}
}
}
@@ -80,74 +82,74 @@ void RiaSummaryTools::notifyCalculatedCurveNameHasChanged(const QString& previou
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
RimSummaryPlot* RiaSummaryTools::parentSummaryPlot(caf::PdmObject* object)
RimSummaryPlot* RiaSummaryTools::parentSummaryPlot( caf::PdmObject* object )
{
if (parentCrossPlot(object))
if ( parentCrossPlot( object ) )
{
return nullptr;
}
RimSummaryPlot* summaryPlot = nullptr;
if (object)
if ( object )
{
object->firstAncestorOrThisOfType(summaryPlot);
object->firstAncestorOrThisOfType( summaryPlot );
}
return summaryPlot;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
RimSummaryPlotCollection* RiaSummaryTools::parentSummaryPlotCollection(caf::PdmObject* object)
RimSummaryPlotCollection* RiaSummaryTools::parentSummaryPlotCollection( caf::PdmObject* object )
{
RimSummaryPlotCollection* summaryPlotColl = nullptr;
if (object)
if ( object )
{
object->firstAncestorOrThisOfType(summaryPlotColl);
object->firstAncestorOrThisOfType( summaryPlotColl );
}
return summaryPlotColl;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
RimSummaryCrossPlot* RiaSummaryTools::parentCrossPlot(caf::PdmObject* object)
RimSummaryCrossPlot* RiaSummaryTools::parentCrossPlot( caf::PdmObject* object )
{
RimSummaryCrossPlot* crossPlot = nullptr;
if (object)
if ( object )
{
object->firstAncestorOrThisOfType(crossPlot);
object->firstAncestorOrThisOfType( crossPlot );
}
return crossPlot;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
RimSummaryCrossPlotCollection* RiaSummaryTools::parentCrossPlotCollection(caf::PdmObject* object)
RimSummaryCrossPlotCollection* RiaSummaryTools::parentCrossPlotCollection( caf::PdmObject* object )
{
RimSummaryCrossPlotCollection* crossPlotColl = nullptr;
if (object)
if ( object )
{
object->firstAncestorOrThisOfType(crossPlotColl);
object->firstAncestorOrThisOfType( crossPlotColl );
}
return crossPlotColl;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
bool RiaSummaryTools::isSummaryCrossPlot(const RimSummaryPlot* plot)
bool RiaSummaryTools::isSummaryCrossPlot( const RimSummaryPlot* plot )
{
return dynamic_cast<const RimSummaryCrossPlot*>(plot);
return dynamic_cast<const RimSummaryCrossPlot*>( plot );
}

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017 Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE.
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -26,25 +26,25 @@ class RimSummaryCaseMainCollection;
class QString;
namespace caf {
class PdmObject;
namespace caf
{
class PdmObject;
}
//==================================================================================================
//
//
//==================================================================================================
class RiaSummaryTools
{
public:
static RimSummaryPlotCollection* summaryPlotCollection();
static RimSummaryCaseMainCollection* summaryCaseMainCollection();
static void notifyCalculatedCurveNameHasChanged(const QString& previousCurveName,
const QString& currentCurveName);
static RimSummaryPlotCollection* summaryPlotCollection();
static RimSummaryCaseMainCollection* summaryCaseMainCollection();
static void notifyCalculatedCurveNameHasChanged( const QString& previousCurveName, const QString& currentCurveName );
static RimSummaryPlot* parentSummaryPlot(caf::PdmObject* object);
static RimSummaryPlotCollection* parentSummaryPlotCollection(caf::PdmObject* object);
static RimSummaryPlot* parentSummaryPlot( caf::PdmObject* object );
static RimSummaryPlotCollection* parentSummaryPlotCollection( caf::PdmObject* object );
static RimSummaryCrossPlot* parentCrossPlot(caf::PdmObject* object);
static RimSummaryCrossPlotCollection* parentCrossPlotCollection(caf::PdmObject* object);
static bool isSummaryCrossPlot(const RimSummaryPlot* plot);
static RimSummaryCrossPlot* parentCrossPlot( caf::PdmObject* object );
static RimSummaryCrossPlotCollection* parentCrossPlotCollection( caf::PdmObject* object );
static bool isSummaryCrossPlot( const RimSummaryPlot* plot );
};

View File

@@ -25,8 +25,8 @@
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RiaTextFileCompare::RiaTextFileCompare(const QString& pathToDiffTool)
: m_pathToDiffTool(pathToDiffTool)
RiaTextFileCompare::RiaTextFileCompare( const QString& pathToDiffTool )
: m_pathToDiffTool( pathToDiffTool )
{
reset();
}
@@ -50,12 +50,12 @@ void RiaTextFileCompare::reset()
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
bool RiaTextFileCompare::runComparison(const QString& baseFolder, const QString& generatedFolder)
bool RiaTextFileCompare::runComparison( const QString& baseFolder, const QString& generatedFolder )
{
reset();
QString fullFilePath = "diff";
if (!m_pathToDiffTool.isEmpty())
if ( !m_pathToDiffTool.isEmpty() )
{
fullFilePath = m_pathToDiffTool + "/" + fullFilePath;
}
@@ -64,15 +64,16 @@ bool RiaTextFileCompare::runComparison(const QString& baseFolder, const QString&
// See https://docs.freebsd.org/info/diff/diff.info.diff_Options.html
QString args = "-r -u --strip-trailing-cr";
QString completeCommand = QString("\"%1\" %2 %3 %4").arg(fullFilePath).arg(baseFolder).arg(generatedFolder).arg(args);
QString completeCommand =
QString( "\"%1\" %2 %3 %4" ).arg( fullFilePath ).arg( baseFolder ).arg( generatedFolder ).arg( args );
// Launch process and wait
QProcess proc;
proc.start(completeCommand);
proc.waitForFinished(30000);
proc.start( completeCommand );
proc.waitForFinished( 30000 );
QProcess::ProcessError procError = proc.error();
if (procError != QProcess::UnknownError)
if ( procError != QProcess::UnknownError )
{
m_lastError = SEVERE_ERROR;
m_errorMsg = "Error running 'diff' tool process";
@@ -83,11 +84,11 @@ bool RiaTextFileCompare::runComparison(const QString& baseFolder, const QString&
QByteArray stdErr = proc.readAllStandardError();
int procExitCode = proc.exitCode();
if (procExitCode == 0)
if ( procExitCode == 0 )
{
return true;
}
else if (procExitCode == 1)
else if ( procExitCode == 1 )
{
QByteArray stdOut = proc.readAllStandardOutput();
m_diffOutput = stdOut;

View File

@@ -36,10 +36,10 @@ public:
};
public:
explicit RiaTextFileCompare(const QString& pathToDiffTool);
explicit RiaTextFileCompare( const QString& pathToDiffTool );
~RiaTextFileCompare();
bool runComparison(const QString& baseFolder, const QString& generatedFolder);
bool runComparison( const QString& baseFolder, const QString& generatedFolder );
ErrorType error() const;
QString errorMessage() const;
QString errorDetails() const;

View File

@@ -20,18 +20,17 @@
#include <QString>
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
bool RiaTextStringTools::compare(const QString& expected, const QString& actual)
bool RiaTextStringTools::compare( const QString& expected, const QString& actual )
{
// Suggestions for improvement
// 1. report line number for first change
// 2. report line numbers for all changes
// 3. add support for compare with content of a text file on disk
if (expected.compare(actual) == 0)
if ( expected.compare( actual ) == 0 )
{
return true;
}
@@ -40,19 +39,18 @@ bool RiaTextStringTools::compare(const QString& expected, const QString& actual)
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QString RiaTextStringTools::trimAndRemoveDoubleSpaces(const QString& s)
QString RiaTextStringTools::trimAndRemoveDoubleSpaces( const QString& s )
{
int length;
int length;
QString trimmed = s.trimmed();
do
do
{
length = trimmed.size();
trimmed = trimmed.replace(" ", " ");
} while (trimmed.size() < length);
length = trimmed.size();
trimmed = trimmed.replace( " ", " " );
} while ( trimmed.size() < length );
return trimmed;
}

View File

@@ -21,10 +21,10 @@
class QString;
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
namespace RiaTextStringTools
{
bool compare(const QString& expected, const QString& actual);
QString trimAndRemoveDoubleSpaces(const QString& s);
}
bool compare( const QString& expected, const QString& actual );
QString trimAndRemoveDoubleSpaces( const QString& s );
} // namespace RiaTextStringTools

View File

@@ -1,29 +1,29 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017 Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE.
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
#include <cvfConfigCore.h>
#include <cvfAssert.h>
#include <cvfConfigCore.h>
#include "RiaTimeHistoryCurveResampler.h"
#include <limits>
//QString tostring(const QDateTime& dt)
// QString tostring(const QDateTime& dt)
//{
// int y = dt.date().year();
// int m = dt.date().month();
@@ -39,45 +39,42 @@
//--------------------------------------------------------------------------------------------------
/// Internal constants
//--------------------------------------------------------------------------------------------------
#define DOUBLE_INF std::numeric_limits<double>::infinity()
#define DOUBLE_INF std::numeric_limits<double>::infinity()
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
RiaTimeHistoryCurveResampler::RiaTimeHistoryCurveResampler()
RiaTimeHistoryCurveResampler::RiaTimeHistoryCurveResampler() {}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaTimeHistoryCurveResampler::setCurveData( const std::vector<double>& values, const std::vector<time_t>& timeSteps )
{
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaTimeHistoryCurveResampler::setCurveData(const std::vector<double>& values, const std::vector<time_t>& timeSteps)
{
CVF_ASSERT(values.size() == timeSteps.size());
CVF_ASSERT( values.size() == timeSteps.size() );
clearData();
m_originalValues = std::make_pair(values, timeSteps);
m_originalValues = std::make_pair( values, timeSteps );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaTimeHistoryCurveResampler::resampleAndComputePeriodEndValues(DateTimePeriod period)
void RiaTimeHistoryCurveResampler::resampleAndComputePeriodEndValues( DateTimePeriod period )
{
computePeriodEndValues(period);
computePeriodEndValues( period );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaTimeHistoryCurveResampler::resampleAndComputeWeightedMeanValues(DateTimePeriod period)
void RiaTimeHistoryCurveResampler::resampleAndComputeWeightedMeanValues( DateTimePeriod period )
{
computeWeightedMeanValues(period);
computeWeightedMeanValues( period );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const std::vector<time_t>& RiaTimeHistoryCurveResampler::resampledTimeSteps() const
{
@@ -85,7 +82,7 @@ const std::vector<time_t>& RiaTimeHistoryCurveResampler::resampledTimeSteps() co
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
const std::vector<double>& RiaTimeHistoryCurveResampler::resampledValues() const
{
@@ -93,70 +90,71 @@ const std::vector<double>& RiaTimeHistoryCurveResampler::resampledValues() const
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
std::vector<time_t> RiaTimeHistoryCurveResampler::timeStepsFromTimeRange(DateTimePeriod period, time_t minTime, time_t maxTime)
std::vector<time_t>
RiaTimeHistoryCurveResampler::timeStepsFromTimeRange( DateTimePeriod period, time_t minTime, time_t maxTime )
{
if(minTime > maxTime) return std::vector<time_t>();
if ( minTime > maxTime ) return std::vector<time_t>();
auto firstOriginalTimeStep = QDT::fromTime_t(minTime);
auto lastOriginalTimeStep = QDT::fromTime_t(maxTime);
auto firstOriginalTimeStep = QDT::fromTime_t( minTime );
auto lastOriginalTimeStep = QDT::fromTime_t( maxTime );
auto currTimeStep = firstResampledTimeStep(firstOriginalTimeStep, period);
auto currTimeStep = firstResampledTimeStep( firstOriginalTimeStep, period );
std::vector<time_t> timeSteps;
while (QDT::lessThan(currTimeStep, lastOriginalTimeStep))
while ( QDT::lessThan( currTimeStep, lastOriginalTimeStep ) )
{
timeSteps.push_back(currTimeStep.toTime_t());
currTimeStep = QDT::addPeriod(currTimeStep, period);
timeSteps.push_back( currTimeStep.toTime_t() );
currTimeStep = QDT::addPeriod( currTimeStep, period );
}
timeSteps.push_back(currTimeStep.toTime_t());
timeSteps.push_back( currTimeStep.toTime_t() );
return timeSteps;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaTimeHistoryCurveResampler::computeWeightedMeanValues(DateTimePeriod period)
void RiaTimeHistoryCurveResampler::computeWeightedMeanValues( DateTimePeriod period )
{
size_t origDataSize = m_originalValues.second.size();
size_t oi = 0;
auto& origTimeSteps = m_originalValues.second;
auto& origValues = m_originalValues.first;
size_t origDataSize = m_originalValues.second.size();
size_t oi = 0;
auto& origTimeSteps = m_originalValues.second;
auto& origValues = m_originalValues.first;
computeResampledTimeSteps(period);
computeResampledTimeSteps( period );
m_values.reserve(m_timeSteps.size());
for (size_t i = 0; i < m_timeSteps.size(); i++)
m_values.reserve( m_timeSteps.size() );
for ( size_t i = 0; i < m_timeSteps.size(); i++ )
{
double wMean = 0.0;
time_t periodStart = i > 0 ? m_timeSteps[i - 1] :
QDT::subtractPeriod(QDT::fromTime_t(m_timeSteps[0]), period).toTime_t();
time_t periodEnd = m_timeSteps[i];
double wMean = 0.0;
time_t periodStart = i > 0 ? m_timeSteps[i - 1]
: QDT::subtractPeriod( QDT::fromTime_t( m_timeSteps[0] ), period ).toTime_t();
time_t periodEnd = m_timeSteps[i];
time_t periodLength = periodEnd - periodStart;
while(true)
while ( true )
{
time_t origTimeStep = 0;
double origValue = 0.0;
double origValue = 0.0;
if (oi > origDataSize) break;
if ( oi > origDataSize ) break;
if (oi < origDataSize)
if ( oi < origDataSize )
{
origTimeStep = origTimeSteps[oi];
origValue = origValues[oi] != DOUBLE_INF ? origValues[oi] : 0.0;
origValue = origValues[oi] != DOUBLE_INF ? origValues[oi] : 0.0;
}
else
{
origTimeStep = periodEnd;
origValue = 0.0;
origValue = 0.0;
}
if (oi == 0)
if ( oi == 0 )
{
if (origTimeStep == m_timeSteps[i])
if ( origTimeStep == m_timeSteps[i] )
{
wMean += origValue;
oi++;
@@ -165,13 +163,13 @@ void RiaTimeHistoryCurveResampler::computeWeightedMeanValues(DateTimePeriod peri
origValue = 0.0;
}
time_t startTime = oi > 0 ? std::max(origTimeSteps[oi - 1], periodStart) : periodStart;
time_t endTime = std::min(origTimeStep, periodEnd);
wMean += origValue * (endTime - startTime) / periodLength;
time_t startTime = oi > 0 ? std::max( origTimeSteps[oi - 1], periodStart ) : periodStart;
time_t endTime = std::min( origTimeStep, periodEnd );
if (origTimeStep > m_timeSteps[i]) break;
if (origTimeStep == m_timeSteps[i])
wMean += origValue * ( endTime - startTime ) / periodLength;
if ( origTimeStep > m_timeSteps[i] ) break;
if ( origTimeStep == m_timeSteps[i] )
{
oi++;
break;
@@ -179,46 +177,47 @@ void RiaTimeHistoryCurveResampler::computeWeightedMeanValues(DateTimePeriod peri
oi++;
}
m_values.push_back(wMean);
m_values.push_back( wMean );
}
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaTimeHistoryCurveResampler::computePeriodEndValues(DateTimePeriod period)
void RiaTimeHistoryCurveResampler::computePeriodEndValues( DateTimePeriod period )
{
size_t origDataSize = m_originalValues.second.size();
size_t oi = 0;
auto& origTimeSteps = m_originalValues.second;
auto& origValues = m_originalValues.first;
size_t origDataSize = m_originalValues.second.size();
size_t oi = 0;
auto& origTimeSteps = m_originalValues.second;
auto& origValues = m_originalValues.first;
computeResampledTimeSteps(period);
computeResampledTimeSteps( period );
m_values.reserve(m_timeSteps.size());
for (size_t i = 0; i < m_timeSteps.size(); i++)
m_values.reserve( m_timeSteps.size() );
for ( size_t i = 0; i < m_timeSteps.size(); i++ )
{
while (oi < origDataSize && origTimeSteps[oi] < m_timeSteps[i]) oi++;
while ( oi < origDataSize && origTimeSteps[oi] < m_timeSteps[i] )
oi++;
time_t origTimeStep = oi < origDataSize ? origTimeSteps[oi] : m_timeSteps[i];
double origValue = oi < origDataSize ? origValues[oi] : origValues[oi - 1];
double origValue = oi < origDataSize ? origValues[oi] : origValues[oi - 1];
double value;
if (oi > 0 && origTimeStep >= m_timeSteps[i])
if ( oi > 0 && origTimeStep >= m_timeSteps[i] )
{
value = interpolatedValue(m_timeSteps[i], origTimeSteps[oi - 1], origValues[oi - 1], origTimeStep, origValue);
value = interpolatedValue( m_timeSteps[i], origTimeSteps[oi - 1], origValues[oi - 1], origTimeStep, origValue );
}
else
{
value = origValue;
}
m_values.push_back(value);
m_values.push_back( value );
}
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaTimeHistoryCurveResampler::clearData()
{
@@ -227,48 +226,48 @@ void RiaTimeHistoryCurveResampler::clearData()
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaTimeHistoryCurveResampler::computeResampledTimeSteps(DateTimePeriod period)
void RiaTimeHistoryCurveResampler::computeResampledTimeSteps( DateTimePeriod period )
{
CVF_ASSERT(period != DateTimePeriod::NONE && m_originalValues.second.size() > 0);
CVF_ASSERT( period != DateTimePeriod::NONE && m_originalValues.second.size() > 0 );
auto firstOriginalTimeStep = QDT::fromTime_t(m_originalValues.second.front());
auto lastOriginalTimeStep = QDT::fromTime_t(m_originalValues.second.back());
auto firstOriginalTimeStep = QDT::fromTime_t( m_originalValues.second.front() );
auto lastOriginalTimeStep = QDT::fromTime_t( m_originalValues.second.back() );
clearData();
auto currTimeStep = firstResampledTimeStep(firstOriginalTimeStep, period);
auto currTimeStep = firstResampledTimeStep( firstOriginalTimeStep, period );
while (QDT::lessThan(currTimeStep, lastOriginalTimeStep))
while ( QDT::lessThan( currTimeStep, lastOriginalTimeStep ) )
{
m_timeSteps.push_back(currTimeStep.toTime_t());
currTimeStep = QDT::addPeriod(currTimeStep, period);
m_timeSteps.push_back( currTimeStep.toTime_t() );
currTimeStep = QDT::addPeriod( currTimeStep, period );
}
// Add last time step
m_timeSteps.push_back(currTimeStep.toTime_t());
m_timeSteps.push_back( currTimeStep.toTime_t() );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QDateTime RiaTimeHistoryCurveResampler::firstResampledTimeStep(const QDateTime& firstTimeStep, DateTimePeriod period)
QDateTime RiaTimeHistoryCurveResampler::firstResampledTimeStep( const QDateTime& firstTimeStep, DateTimePeriod period )
{
QDateTime truncatedTime = QDT::truncateTime(firstTimeStep, period);
QDateTime truncatedTime = QDT::truncateTime( firstTimeStep, period );
if (QDT::lessThan(truncatedTime, firstTimeStep)) return QDT::addPeriod(truncatedTime, period);
if ( QDT::lessThan( truncatedTime, firstTimeStep ) ) return QDT::addPeriod( truncatedTime, period );
return truncatedTime;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
double RiaTimeHistoryCurveResampler::interpolatedValue(time_t t, time_t t1, double v1, time_t t2, double v2)
double RiaTimeHistoryCurveResampler::interpolatedValue( time_t t, time_t t1, double v1, time_t t2, double v2 )
{
CVF_ASSERT(t2 >= t1);
CVF_ASSERT( t2 >= t1 );
if (t <= t1) return v1;
if (t >= t2) return v2;
if ( t <= t1 ) return v1;
if ( t >= t2 ) return v2;
return (v2 - v1) * (double)(t - t1) / (double)(t2 - t1) + v1;
return ( v2 - v1 ) * (double)( t - t1 ) / (double)( t2 - t1 ) + v1;
}

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017 Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE.
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -26,36 +26,35 @@
using QDT = RiaQDateTimeTools;
//==================================================================================================
///
///
//==================================================================================================
class RiaTimeHistoryCurveResampler
{
public:
RiaTimeHistoryCurveResampler();
void setCurveData(const std::vector<double>& values,
const std::vector<time_t>& timeSteps);
void setCurveData( const std::vector<double>& values, const std::vector<time_t>& timeSteps );
void resampleAndComputePeriodEndValues(DateTimePeriod period);
void resampleAndComputeWeightedMeanValues(DateTimePeriod period);
void resampleAndComputePeriodEndValues( DateTimePeriod period );
void resampleAndComputeWeightedMeanValues( DateTimePeriod period );
const std::vector<time_t>& resampledTimeSteps() const;
const std::vector<double>& resampledValues() const;
const std::vector<time_t>& resampledTimeSteps() const;
const std::vector<double>& resampledValues() const;
static std::vector<time_t> timeStepsFromTimeRange(DateTimePeriod period, time_t minTime, time_t maxTime);
static std::vector<time_t> timeStepsFromTimeRange( DateTimePeriod period, time_t minTime, time_t maxTime );
private:
void computeWeightedMeanValues(DateTimePeriod period);
void computePeriodEndValues(DateTimePeriod period);
void computeWeightedMeanValues( DateTimePeriod period );
void computePeriodEndValues( DateTimePeriod period );
void clearData();
void computeResampledTimeSteps(DateTimePeriod period);
static QDateTime firstResampledTimeStep(const QDateTime& firstTimestep, DateTimePeriod period);
inline double interpolatedValue(time_t t, time_t t1, double v1, time_t t2, double v2);
void clearData();
void computeResampledTimeSteps( DateTimePeriod period );
static QDateTime firstResampledTimeStep( const QDateTime& firstTimestep, DateTimePeriod period );
inline double interpolatedValue( time_t t, time_t t1, double v1, time_t t2, double v2 );
private:
std::pair<std::vector<double>, std::vector<time_t>> m_originalValues;
std::vector<time_t> m_timeSteps;
std::vector<double> m_values;
std::vector<time_t> m_timeSteps;
std::vector<double> m_values;
};

View File

@@ -26,20 +26,20 @@
///
//--------------------------------------------------------------------------------------------------
RiaWeightedGeometricMeanCalculator::RiaWeightedGeometricMeanCalculator()
: m_aggregatedWeightedValue(0.0)
, m_aggregatedWeight(0.0)
: m_aggregatedWeightedValue( 0.0 )
, m_aggregatedWeight( 0.0 )
{
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaWeightedGeometricMeanCalculator::addValueAndWeight(double value, double weight)
void RiaWeightedGeometricMeanCalculator::addValueAndWeight( double value, double weight )
{
CVF_ASSERT(weight >= 0.0);
CVF_ASSERT( weight >= 0.0 );
// This can be a very big number, consider other algorithms if that becomes a problem
m_aggregatedWeightedValue += (std::log(value) * weight);
m_aggregatedWeightedValue += ( std::log( value ) * weight );
m_aggregatedWeight += weight;
}
@@ -48,9 +48,9 @@ void RiaWeightedGeometricMeanCalculator::addValueAndWeight(double value, double
//--------------------------------------------------------------------------------------------------
double RiaWeightedGeometricMeanCalculator::weightedMean() const
{
if (m_aggregatedWeight > 1e-7)
if ( m_aggregatedWeight > 1e-7 )
{
return std::exp(m_aggregatedWeightedValue / m_aggregatedWeight);
return std::exp( m_aggregatedWeightedValue / m_aggregatedWeight );
}
return 0.0;
@@ -65,7 +65,7 @@ double RiaWeightedGeometricMeanCalculator::aggregatedWeight() const
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
bool RiaWeightedGeometricMeanCalculator::validAggregatedWeight() const
{

View File

@@ -26,11 +26,11 @@ class RiaWeightedGeometricMeanCalculator
public:
RiaWeightedGeometricMeanCalculator();
void addValueAndWeight(double value, double weight);
void addValueAndWeight( double value, double weight );
double weightedMean() const;
double aggregatedWeight() const;
bool validAggregatedWeight() const;
bool validAggregatedWeight() const;
private:
double m_aggregatedWeightedValue;

View File

@@ -26,17 +26,17 @@
///
//--------------------------------------------------------------------------------------------------
RiaWeightedHarmonicMeanCalculator::RiaWeightedHarmonicMeanCalculator()
: m_aggregatedWeightedValue(0.0)
, m_aggregatedWeight(0.0)
: m_aggregatedWeightedValue( 0.0 )
, m_aggregatedWeight( 0.0 )
{
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaWeightedHarmonicMeanCalculator::addValueAndWeight(double value, double weight)
void RiaWeightedHarmonicMeanCalculator::addValueAndWeight( double value, double weight )
{
CVF_ASSERT(weight > 1.0e-12 && std::abs(value) > 1.0e-12);
CVF_ASSERT( weight > 1.0e-12 && std::abs( value ) > 1.0e-12 );
m_aggregatedWeightedValue += weight / value;
m_aggregatedWeight += weight;
@@ -46,12 +46,12 @@ void RiaWeightedHarmonicMeanCalculator::addValueAndWeight(double value, double w
///
//--------------------------------------------------------------------------------------------------
double RiaWeightedHarmonicMeanCalculator::weightedMean() const
{
if (validAggregatedWeight())
{
if ( validAggregatedWeight() )
{
return m_aggregatedWeight / m_aggregatedWeightedValue;
}
CVF_ASSERT(false);
CVF_ASSERT( false );
return 0.0;
}

View File

@@ -26,7 +26,7 @@ class RiaWeightedHarmonicMeanCalculator
public:
RiaWeightedHarmonicMeanCalculator();
void addValueAndWeight(double value, double weight);
void addValueAndWeight( double value, double weight );
double weightedMean() const;
double aggregatedWeight() const;

View File

@@ -21,17 +21,18 @@
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
template<class T>
template <class T>
class RiaWeightedMeanCalculator
{
public:
RiaWeightedMeanCalculator();
void addValueAndWeight(T value, double weight);
void addValueAndWeight( T value, double weight );
T weightedMean() const;
double aggregatedWeight() const;
bool validAggregatedWeight() const;
private:
T m_aggregatedValue;
double m_aggregatedWeight;

View File

@@ -1,107 +1,103 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017 Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE.
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
#include "../RiaApplication.h"
#include "RiaWellNameComparer.h"
#include "../../ProjectDataModel/RimProject.h"
#include "../../ProjectDataModel/RimWellPath.h"
#include "../RiaApplication.h"
#include <regex>
//==================================================================================================
//
//==================================================================================================
QString RiaWellNameComparer::tryFindMatchingSimWellName(QString searchName)
QString RiaWellNameComparer::tryFindMatchingSimWellName( QString searchName )
{
RimProject* proj = RiaApplication::instance()->project();
RimProject* proj = RiaApplication::instance()->project();
const std::vector<QString>& simWellNames = proj->simulationWellNames();
if (searchName.isEmpty() || simWellNames.empty()) return QString();
if ( searchName.isEmpty() || simWellNames.empty() ) return QString();
searchName = removeWellNamePrefix(searchName);
return tryMatchNameInList(searchName, simWellNames);
searchName = removeWellNamePrefix( searchName );
return tryMatchNameInList( searchName, simWellNames );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QString RiaWellNameComparer::tryFindMatchingWellPath(QString wellName)
QString RiaWellNameComparer::tryFindMatchingWellPath( QString wellName )
{
RimProject* proj = RiaApplication::instance()->project();
RimProject* proj = RiaApplication::instance()->project();
const std::vector<RimWellPath*>& wellPaths = proj->allWellPaths();
if (wellName.isEmpty() || wellPaths.empty()) return QString();
if ( wellName.isEmpty() || wellPaths.empty() ) return QString();
std::vector<QString> wellPathNames;
for (const RimWellPath* wellPath : wellPaths)
for ( const RimWellPath* wellPath : wellPaths )
{
wellPathNames.push_back(wellPath->name());
wellPathNames.push_back( wellPath->name() );
}
wellName = removeWellNamePrefix(wellName);
return tryMatchNameInList(wellName, wellPathNames);
wellName = removeWellNamePrefix( wellName );
return tryMatchNameInList( wellName, wellPathNames );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QString RiaWellNameComparer::tryMatchNameInList(QString searchName, const std::vector<QString>& nameList)
QString RiaWellNameComparer::tryMatchNameInList( QString searchName, const std::vector<QString>& nameList )
{
// Try exact name match
QString matchedName = tryMatchName(searchName, nameList);
if (!matchedName.isEmpty())
QString matchedName = tryMatchName( searchName, nameList );
if ( !matchedName.isEmpty() )
{
return matchedName;
}
// Try matching ignoring spaces, dashes and underscores
return tryMatchName(searchName,
nameList,
[](const QString& str)
{
QString s = str;
s = removeWellNamePrefix(s);
return s.remove(' ').remove('-').remove('_');
}
);
return tryMatchName( searchName, nameList, []( const QString& str ) {
QString s = str;
s = removeWellNamePrefix( s );
return s.remove( ' ' ).remove( '-' ).remove( '_' );
} );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QString RiaWellNameComparer::tryMatchName(QString searchName,
const std::vector<QString>& simWellNames,
std::function<QString(QString)> stringFormatter)
QString RiaWellNameComparer::tryMatchName( QString searchName,
const std::vector<QString>& simWellNames,
std::function<QString( QString )> stringFormatter )
{
if (searchName.isEmpty()) return QString();
if ( searchName.isEmpty() ) return QString();
if (stringFormatter != nullptr)
if ( stringFormatter != nullptr )
{
searchName = stringFormatter(searchName);
searchName = stringFormatter( searchName );
}
for (const auto& simWellName : simWellNames)
for ( const auto& simWellName : simWellNames )
{
QString simWn = simWellName;
if (stringFormatter != nullptr)
if ( stringFormatter != nullptr )
{
simWn = stringFormatter(simWn);
simWn = stringFormatter( simWn );
}
if (QString::compare(simWn, searchName, Qt::CaseInsensitive) == 0)
if ( QString::compare( simWn, searchName, Qt::CaseInsensitive ) == 0 )
{
return simWellName;
}
@@ -110,12 +106,12 @@ QString RiaWellNameComparer::tryMatchName(QString searchName,
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
QString RiaWellNameComparer::removeWellNamePrefix(const QString& name)
QString RiaWellNameComparer::removeWellNamePrefix( const QString& name )
{
// Try to remove prefix on the format 'xx xxxx/xx-'
std::regex pattern("^.*\\d*[/]\\d*[-_]");
std::regex pattern( "^.*\\d*[/]\\d*[-_]" );
return QString::fromStdString(std::regex_replace(name.toStdString(), pattern, ""));
return QString::fromStdString( std::regex_replace( name.toStdString(), pattern, "" ) );
}

View File

@@ -1,17 +1,17 @@
/////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2017 Statoil ASA
//
//
// ResInsight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
//
// ResInsight is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE.
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
//
// See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
// for more details.
//
/////////////////////////////////////////////////////////////////////////////////
@@ -19,28 +19,26 @@
#pragma once
#include <QString>
#include <vector>
#include <functional>
#include <vector>
//==================================================================================================
//
//
//
//
//==================================================================================================
class RiaWellNameComparer
{
public:
static QString tryFindMatchingSimWellName(QString searchName);
static QString tryFindMatchingWellPath(QString wellName);
static QString tryFindMatchingSimWellName( QString searchName );
static QString tryFindMatchingWellPath( QString wellName );
static QString tryMatchNameInList(QString searchName,
const std::vector<QString>& nameList);
static QString tryMatchNameInList( QString searchName, const std::vector<QString>& nameList );
private:
static QString tryMatchName(QString searchName,
const std::vector<QString>& nameList,
std::function<QString(QString)> stringFormatter = nullptr);
static QString tryMatchName( QString searchName,
const std::vector<QString>& nameList,
std::function<QString( QString )> stringFormatter = nullptr );
static QString removeWellNamePrefix(const QString& name);
static QString removeWellNamePrefix( const QString& name );
};

View File

@@ -22,21 +22,21 @@
#include "cvfGeometryTools.h"
//--------------------------------------------------------------------------------------------------
/// + p1
/// t1 //
/// | + C
/// + p1
/// t1 //
/// | + C
/// \
/// + p2
//--------------------------------------------------------------------------------------------------
RiaArcCurveCalculator::RiaArcCurveCalculator(cvf::Vec3d p1, cvf::Vec3d t1, cvf::Vec3d p2)
: m_radius(std::numeric_limits<double>::infinity())
, m_arcCS(cvf::Mat4d::ZERO)
, m_endAzi(0)
, m_endInc(0)
, m_curveStatus(OK)
RiaArcCurveCalculator::RiaArcCurveCalculator( cvf::Vec3d p1, cvf::Vec3d t1, cvf::Vec3d p2 )
: m_radius( std::numeric_limits<double>::infinity() )
, m_arcCS( cvf::Mat4d::ZERO )
, m_endAzi( 0 )
, m_endInc( 0 )
, m_curveStatus( OK )
{
bool isOk = t1.normalize();
if (!isOk)
if ( !isOk )
{
// No tangent. Bail out
m_curveStatus = FAILED_INPUT_OVERLAP;
@@ -44,8 +44,8 @@ RiaArcCurveCalculator::RiaArcCurveCalculator(cvf::Vec3d p1, cvf::Vec3d t1, cvf::
}
cvf::Vec3d p1p2 = p2 - p1;
cvf::Vec3d t12 = p1p2.getNormalized(&isOk);
if (!isOk)
cvf::Vec3d t12 = p1p2.getNormalized( &isOk );
if ( !isOk )
{
// p1 and p2 in the same place.
m_curveStatus = FAILED_INPUT_OVERLAP;
@@ -53,52 +53,50 @@ RiaArcCurveCalculator::RiaArcCurveCalculator(cvf::Vec3d p1, cvf::Vec3d t1, cvf::
return;
}
cvf::Vec3d N = (t1 ^ t12).getNormalized(&isOk);
if (!isOk)
cvf::Vec3d N = ( t1 ^ t12 ).getNormalized( &isOk );
if ( !isOk )
{
// P2 is on the p1 + k*t1 line. We have a straight line
m_curveStatus = OK_STRAIGHT_LINE;
RiaOffshoreSphericalCoords endTangent(t1);
RiaOffshoreSphericalCoords endTangent( t1 );
m_endTangent = t1;
m_endAzi = endTangent.azi();
m_endInc = endTangent.inc();
m_radius = std::numeric_limits<double>::infinity();
m_arcAngle = 0;
m_arcLength = p1p2.length();
m_endAzi = endTangent.azi();
m_endInc = endTangent.inc();
m_radius = std::numeric_limits<double>::infinity();
m_arcAngle = 0;
m_arcLength = p1p2.length();
return;
}
cvf::Vec3d tr1 = (N ^ t1).getNormalized();
cvf::Vec3d tr1 = ( N ^ t1 ).getNormalized();
m_radius = 0.5 * p1p2.length() / ( tr1.dot( t12 ) );
m_radius = 0.5 * p1p2.length() / (tr1.dot(t12));
cvf::Vec3d C = p1 + m_radius * tr1;
cvf::Vec3d nTr1 = -tr1;
m_arcCS = cvf::Mat4d::fromCoordSystemAxes( &nTr1, &t1, &N );
m_arcCS = cvf::Mat4d::fromCoordSystemAxes( &nTr1, &t1, &N );
m_arcCS.setTranslation(C);
m_arcCS.setTranslation( C );
m_arcAngle = cvf::GeometryTools::getAngle(N, p1 - C, p2 - C);
m_arcAngle = cvf::GeometryTools::getAngle( N, p1 - C, p2 - C );
m_arcLength = m_radius*m_arcAngle;
m_arcLength = m_radius * m_arcAngle;
m_endTangent = N ^ (p2 - C).getNormalized();
m_endTangent = N ^ ( p2 - C ).getNormalized();
RiaOffshoreSphericalCoords endTangent(m_endTangent);
RiaOffshoreSphericalCoords endTangent( m_endTangent );
m_endAzi = endTangent.azi();
m_endInc = endTangent.inc();
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
RiaArcCurveCalculator::RiaArcCurveCalculator(cvf::Vec3d p1, double azi1, double inc1, cvf::Vec3d p2)
RiaArcCurveCalculator::RiaArcCurveCalculator( cvf::Vec3d p1, double azi1, double inc1, cvf::Vec3d p2 )
{
cvf::Vec3d t1( RiaOffshoreSphericalCoords::unitVectorFromAziInc(azi1,inc1));
cvf::Vec3d t1( RiaOffshoreSphericalCoords::unitVectorFromAziInc( azi1, inc1 ) );
(*this) = RiaArcCurveCalculator(p1, t1, p2);
( *this ) = RiaArcCurveCalculator( p1, t1, p2 );
}

View File

@@ -18,22 +18,21 @@
#pragma once
#include "cvfVector3.h"
#include "cvfMatrix4.h"
#include "cvfVector3.h"
//--------------------------------------------------------------------------------------------------
/// + p1
/// t1 //
/// | + C
/// + p1
/// t1 //
/// | + C
/// \
/// + p2
//--------------------------------------------------------------------------------------------------
class RiaArcCurveCalculator
{
public:
RiaArcCurveCalculator(cvf::Vec3d p1, cvf::Vec3d t1, cvf::Vec3d p2);
RiaArcCurveCalculator(cvf::Vec3d p1, double azi1, double inc1, cvf::Vec3d p2);
RiaArcCurveCalculator( cvf::Vec3d p1, cvf::Vec3d t1, cvf::Vec3d p2 );
RiaArcCurveCalculator( cvf::Vec3d p1, double azi1, double inc1, cvf::Vec3d p2 );
enum CurveStatus
{
@@ -41,30 +40,59 @@ public:
OK_STRAIGHT_LINE,
FAILED_INPUT_OVERLAP
};
CurveStatus curveStatus() const { return m_curveStatus;}
cvf::Mat4d arcCS() const { return m_arcCS; }
double radius() const { return m_radius;}
double arcAngle() const { return m_arcAngle; }
double arcLength() const { return m_arcLength; }
cvf::Vec3d center() const { return m_arcCS.translation();}
cvf::Vec3d normal() const { return cvf::Vec3d(m_arcCS.col(2));}
double endAzimuth() const { return m_endAzi; }
double endInclination() const { return m_endInc; }
cvf::Vec3d endTangent() const { return m_endTangent; }
CurveStatus curveStatus() const
{
return m_curveStatus;
}
cvf::Mat4d arcCS() const
{
return m_arcCS;
}
double radius() const
{
return m_radius;
}
double arcAngle() const
{
return m_arcAngle;
}
double arcLength() const
{
return m_arcLength;
}
cvf::Vec3d center() const
{
return m_arcCS.translation();
}
cvf::Vec3d normal() const
{
return cvf::Vec3d( m_arcCS.col( 2 ) );
}
double endAzimuth() const
{
return m_endAzi;
}
double endInclination() const
{
return m_endInc;
}
cvf::Vec3d endTangent() const
{
return m_endTangent;
}
private:
CurveStatus m_curveStatus;
double m_radius;
double m_arcLength;
double m_arcAngle;
cvf::Mat4d m_arcCS;
double m_radius;
double m_arcLength;
double m_arcAngle;
cvf::Mat4d m_arcCS;
double m_endAzi;
double m_endInc;
cvf::Vec3d m_endTangent;
double m_endAzi;
double m_endInc;
cvf::Vec3d m_endTangent;
};

View File

@@ -17,84 +17,80 @@
/////////////////////////////////////////////////////////////////////////////////
#include "RiaJCurveCalculator.h"
#include "RiaArcCurveCalculator.h"
#include "RiaOffshoreSphericalCoords.h"
#include "cvfMatrix3.h"
#include "RiaArcCurveCalculator.h"
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
RiaJCurveCalculator::RiaJCurveCalculator(cvf::Vec3d p1, double azi1, double inc1, double r1,
cvf::Vec3d p2)
: m_c1( cvf::Vec3d::UNDEFINED)
, m_n1( cvf::Vec3d::UNDEFINED)
, m_radius( std::numeric_limits<double>::infinity())
, m_curveStatus(OK)
RiaJCurveCalculator::RiaJCurveCalculator( cvf::Vec3d p1, double azi1, double inc1, double r1, cvf::Vec3d p2 )
: m_c1( cvf::Vec3d::UNDEFINED )
, m_n1( cvf::Vec3d::UNDEFINED )
, m_radius( std::numeric_limits<double>::infinity() )
, m_curveStatus( OK )
{
cvf::Vec3d t1 (RiaOffshoreSphericalCoords::unitVectorFromAziInc(azi1, inc1));
cvf::Vec3d t1( RiaOffshoreSphericalCoords::unitVectorFromAziInc( azi1, inc1 ) );
cvf::Vec3d p1p2 = p2 - p1;
cvf::Vec3d tr1 = p1p2 - (p1p2.dot(t1)) * t1;
double tr1Length = tr1.length();
if (tr1Length < 1e-9)
cvf::Vec3d tr1 = p1p2 - ( p1p2.dot( t1 ) ) * t1;
double tr1Length = tr1.length();
if ( tr1Length < 1e-9 )
{
// p2 is on the p1 + t12 line. Degenerates to a line.
m_curveStatus = OK_STRAIGHT_LINE;
m_curveStatus = OK_STRAIGHT_LINE;
m_firstArcEndpoint = p2;
m_endAzi = azi1;
m_endInc = inc1;
m_endAzi = azi1;
m_endInc = inc1;
return;
}
tr1 /= tr1Length;
cvf::Vec3d c1 = p1 + r1 * tr1;
cvf::Vec3d c1 = p1 + r1 * tr1;
cvf::Vec3d p2c1 = c1 - p2;
double p2c1Length = p2c1.length();
if (p2c1Length < r1 || r1 == std::numeric_limits<double>::infinity())
if ( p2c1Length < r1 || r1 == std::numeric_limits<double>::infinity() )
{
// Radius is too big. We can not get to point 2 using the requested radius.
m_curveStatus = FAILED_RADIUS_TOO_LARGE;
m_curveStatus = FAILED_RADIUS_TOO_LARGE;
RiaArcCurveCalculator arc(p1, t1, p2);
if ( arc.curveStatus() == RiaArcCurveCalculator::OK
|| arc.curveStatus() == RiaArcCurveCalculator::OK_STRAIGHT_LINE )
RiaArcCurveCalculator arc( p1, t1, p2 );
if ( arc.curveStatus() == RiaArcCurveCalculator::OK ||
arc.curveStatus() == RiaArcCurveCalculator::OK_STRAIGHT_LINE )
{
m_c1 = arc.center();
m_n1 = arc.normal();
m_c1 = arc.center();
m_n1 = arc.normal();
m_firstArcEndpoint = p2;
m_endAzi = arc.endAzimuth();
m_endInc = arc.endInclination();
m_radius = arc.radius();
m_endAzi = arc.endAzimuth();
m_endInc = arc.endInclination();
m_radius = arc.radius();
}
else
{
m_firstArcEndpoint = p2;
m_endAzi = azi1;
m_endInc = inc1;
m_endAzi = azi1;
m_endInc = inc1;
}
return;
}
double d = sqrt( p2c1Length * p2c1Length - r1 * r1);
double betha = asin( r1/p2c1Length );
cvf::Vec3d tp2c1 = p2c1/p2c1Length;
cvf::Vec3d nc1 = t1 ^ tr1;
double d = sqrt( p2c1Length * p2c1Length - r1 * r1 );
cvf::Vec3d tp11p2 = -tp2c1.getTransformedVector(cvf::Mat3d::fromRotation(nc1, betha));
m_firstArcEndpoint = p2 - d*tp11p2;
m_c1 = c1;
m_n1 = nc1;
double betha = asin( r1 / p2c1Length );
cvf::Vec3d tp2c1 = p2c1 / p2c1Length;
cvf::Vec3d nc1 = t1 ^ tr1;
RiaOffshoreSphericalCoords endTangent(tp11p2);
cvf::Vec3d tp11p2 = -tp2c1.getTransformedVector( cvf::Mat3d::fromRotation( nc1, betha ) );
m_firstArcEndpoint = p2 - d * tp11p2;
m_c1 = c1;
m_n1 = nc1;
RiaOffshoreSphericalCoords endTangent( tp11p2 );
m_endAzi = endTangent.azi();
m_endInc = endTangent.inc();
}

View File

@@ -18,13 +18,12 @@
#pragma once
#include "cvfVector3.h"
//--------------------------------------------------------------------------------------------------
/// + p1
/// t1 //
/// | r1 + C
/// + p1
/// t1 //
/// | r1 + C
/// \
/// + firstArcEndpoint
/// \
@@ -34,8 +33,7 @@
class RiaJCurveCalculator
{
public:
RiaJCurveCalculator(cvf::Vec3d p1, double azi1, double inc1, double r1,
cvf::Vec3d p2);
RiaJCurveCalculator( cvf::Vec3d p1, double azi1, double inc1, double r1, cvf::Vec3d p2 );
enum CurveStatus
{
OK,
@@ -44,27 +42,47 @@ public:
FAILED_RADIUS_TOO_LARGE
};
CurveStatus curveStatus() const { return m_curveStatus;}
CurveStatus curveStatus() const
{
return m_curveStatus;
}
cvf::Vec3d firstArcEndpoint() const { return m_firstArcEndpoint; }
cvf::Vec3d firstArcEndpoint() const
{
return m_firstArcEndpoint;
}
double radius() const { return m_radius; }
cvf::Vec3d firstCenter() const { return m_c1; }
cvf::Vec3d firstNormal() const { return m_n1; }
double endAzimuth() const { return m_endAzi; }
double endInclination() const { return m_endInc; }
private:
double radius() const
{
return m_radius;
}
cvf::Vec3d firstCenter() const
{
return m_c1;
}
cvf::Vec3d firstNormal() const
{
return m_n1;
}
double endAzimuth() const
{
return m_endAzi;
}
double endInclination() const
{
return m_endInc;
}
private:
CurveStatus m_curveStatus;
cvf::Vec3d m_firstArcEndpoint;
double m_radius;
cvf::Vec3d m_c1;
cvf::Vec3d m_n1;
cvf::Vec3d m_firstArcEndpoint;
double m_endAzi;
double m_endInc;
double m_radius;
cvf::Vec3d m_c1;
cvf::Vec3d m_n1;
double m_endAzi;
double m_endInc;
};

View File

@@ -18,42 +18,51 @@
#include "RiaLineArcWellPathCalculator.h"
#include "cvfAssert.h"
#include "RiaOffshoreSphericalCoords.h"
#include "RiaJCurveCalculator.h"
#include "RiaOffshoreSphericalCoords.h"
#include "RiaSCurveCalculator.h"
#include "cvfAssert.h"
#define M_PI 3.14159265358979323846 // pi
#define M_PI 3.14159265358979323846 // pi
cvf::Vec3d smootheningTargetTangent(const cvf::Vec3d& p1, const cvf::Vec3d& p2, const cvf::Vec3d& p3);
cvf::Vec3d smootheningTargetTangent( const cvf::Vec3d& p1, const cvf::Vec3d& p2, const cvf::Vec3d& p3 );
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
RiaLineArcWellPathCalculator::RiaLineArcWellPathCalculator(const cvf::Vec3d& referencePointXyz,
const std::vector<WellTarget>& activeWellPathTargets)
RiaLineArcWellPathCalculator::RiaLineArcWellPathCalculator( const cvf::Vec3d& referencePointXyz,
const std::vector<WellTarget>& activeWellPathTargets )
{
// Handle incomplete input
if (activeWellPathTargets.size() < 2)
if ( activeWellPathTargets.size() < 2 )
{
m_startTangent = cvf::Vec3d::ZERO;
if (activeWellPathTargets.size() == 1)
if ( activeWellPathTargets.size() == 1 )
{
m_lineArcEndpoints.push_back( activeWellPathTargets[0].targetPointXYZ + referencePointXyz );
m_targetStatuses.resize(activeWellPathTargets.size(),
{ !activeWellPathTargets[0].isTangentConstrained, 0.0, 0.0,
true, std::numeric_limits<double>::infinity(),
true, std::numeric_limits<double>::infinity() });
m_lineArcEndpoints.push_back( activeWellPathTargets[0].targetPointXYZ + referencePointXyz );
m_targetStatuses.resize( activeWellPathTargets.size(),
{!activeWellPathTargets[0].isTangentConstrained,
0.0,
0.0,
true,
std::numeric_limits<double>::infinity(),
true,
std::numeric_limits<double>::infinity()} );
}
return;
}
m_targetStatuses.resize(activeWellPathTargets.size(), { false, 0.0, 0.0,
false, std::numeric_limits<double>::infinity(),
false, std::numeric_limits<double>::infinity() });
m_targetStatuses.resize( activeWellPathTargets.size(),
{false,
0.0,
0.0,
false,
std::numeric_limits<double>::infinity(),
false,
std::numeric_limits<double>::infinity()} );
std::vector<WellTarget> adjustedWellPathTargets = activeWellPathTargets;
@@ -63,90 +72,90 @@ RiaLineArcWellPathCalculator::RiaLineArcWellPathCalculator(const cvf::Vec3d& ref
{
for ( size_t tIdx = 0; tIdx < activeWellPathTargets.size() - 2; ++tIdx )
{
if ( !activeWellPathTargets[tIdx+1].isTangentConstrained )
if ( !activeWellPathTargets[tIdx + 1].isTangentConstrained )
{
cvf::Vec3d tangent = smootheningTargetTangent(activeWellPathTargets[tIdx ].targetPointXYZ,
activeWellPathTargets[tIdx+1].targetPointXYZ,
activeWellPathTargets[tIdx+2].targetPointXYZ);
RiaOffshoreSphericalCoords tangentSphCS(tangent);
adjustedWellPathTargets[tIdx+1].azimuth = tangentSphCS.azi();
adjustedWellPathTargets[tIdx+1].inclination = tangentSphCS.inc();
adjustedWellPathTargets[tIdx+1].isTangentConstrained = true;
m_targetStatuses[tIdx+1].hasDerivedTangent = true;
m_targetStatuses[tIdx+1].resultAzimuth = tangentSphCS.azi();
m_targetStatuses[tIdx+1].resultInclination = tangentSphCS.inc();
cvf::Vec3d tangent = smootheningTargetTangent( activeWellPathTargets[tIdx].targetPointXYZ,
activeWellPathTargets[tIdx + 1].targetPointXYZ,
activeWellPathTargets[tIdx + 2].targetPointXYZ );
RiaOffshoreSphericalCoords tangentSphCS( tangent );
adjustedWellPathTargets[tIdx + 1].azimuth = tangentSphCS.azi();
adjustedWellPathTargets[tIdx + 1].inclination = tangentSphCS.inc();
adjustedWellPathTargets[tIdx + 1].isTangentConstrained = true;
m_targetStatuses[tIdx + 1].hasDerivedTangent = true;
m_targetStatuses[tIdx + 1].resultAzimuth = tangentSphCS.azi();
m_targetStatuses[tIdx + 1].resultInclination = tangentSphCS.inc();
}
}
}
m_lineArcEndpoints.push_back( activeWellPathTargets[0].targetPointXYZ + referencePointXyz );
m_lineArcEndpoints.push_back( activeWellPathTargets[0].targetPointXYZ + referencePointXyz );
// Handle first segment if it is not an S-Curve
size_t startSSegmentIdx = 0;
size_t endSSegementIdx = activeWellPathTargets.size() - 1;
size_t endSSegementIdx = activeWellPathTargets.size() - 1;
if (!adjustedWellPathTargets[0].isTangentConstrained)
if ( !adjustedWellPathTargets[0].isTangentConstrained )
{
startSSegmentIdx = 1;
startSSegmentIdx = 1;
const WellTarget& target1 = adjustedWellPathTargets[0];
const WellTarget& target2 = adjustedWellPathTargets[1];
const WellTarget& target1 = adjustedWellPathTargets[0];
const WellTarget& target2 = adjustedWellPathTargets[1];
WellTargetStatus& target1Status = m_targetStatuses[0];
WellTargetStatus& target2Status = m_targetStatuses[1];
if (adjustedWellPathTargets[1].isTangentConstrained)
if ( adjustedWellPathTargets[1].isTangentConstrained )
{
// Create an upside down J curve from target 2 back to 1
RiaJCurveCalculator jCurve(target2.targetPointXYZ,
target2.azimuth + M_PI,
M_PI - target2.inclination,
target2.radius1,
target1.targetPointXYZ);
RiaJCurveCalculator jCurve( target2.targetPointXYZ,
target2.azimuth + M_PI,
M_PI - target2.inclination,
target2.radius1,
target1.targetPointXYZ );
if ( jCurve.curveStatus() == RiaJCurveCalculator::OK )
{
m_lineArcEndpoints.push_back(jCurve.firstArcEndpoint() + referencePointXyz);
m_lineArcEndpoints.push_back( jCurve.firstArcEndpoint() + referencePointXyz );
}
else if ( jCurve.curveStatus() == RiaJCurveCalculator::FAILED_RADIUS_TOO_LARGE )
{
target2Status.hasOverriddenRadius1 = true;
target2Status.resultRadius1 = jCurve.radius();
target2Status.resultRadius1 = jCurve.radius();
}
m_lineArcEndpoints.push_back(target2.targetPointXYZ + referencePointXyz);
m_lineArcEndpoints.push_back( target2.targetPointXYZ + referencePointXyz );
target1Status.hasDerivedTangent = true;
target1Status.resultAzimuth = jCurve.endAzimuth() + M_PI;
target1Status.resultAzimuth = jCurve.endAzimuth() + M_PI;
target1Status.resultInclination = M_PI - jCurve.endInclination();
}
else // The complete wellpath is a straight line from target 1 to 2
{
m_lineArcEndpoints.push_back(target2.targetPointXYZ + referencePointXyz );
cvf::Vec3d t12 = target2.targetPointXYZ - target1.targetPointXYZ;
RiaOffshoreSphericalCoords t12Sph(t12);
m_lineArcEndpoints.push_back( target2.targetPointXYZ + referencePointXyz );
cvf::Vec3d t12 = target2.targetPointXYZ - target1.targetPointXYZ;
RiaOffshoreSphericalCoords t12Sph( t12 );
target1Status.hasDerivedTangent = true;
target1Status.resultAzimuth = t12Sph.azi();
target1Status.resultAzimuth = t12Sph.azi();
target1Status.resultInclination = t12Sph.inc();
target2Status.hasDerivedTangent = true;
target2Status.resultAzimuth = t12Sph.azi();
target2Status.resultAzimuth = t12Sph.azi();
target2Status.resultInclination = t12Sph.inc();
}
m_startTangent = RiaOffshoreSphericalCoords::unitVectorFromAziInc( target1Status.resultAzimuth, target1Status.resultInclination);
m_startTangent = RiaOffshoreSphericalCoords::unitVectorFromAziInc( target1Status.resultAzimuth,
target1Status.resultInclination );
}
else
{
m_startTangent = RiaOffshoreSphericalCoords::unitVectorFromAziInc( activeWellPathTargets[0].azimuth, activeWellPathTargets[0].inclination);
m_startTangent = RiaOffshoreSphericalCoords::unitVectorFromAziInc( activeWellPathTargets[0].azimuth,
activeWellPathTargets[0].inclination );
}
if (!adjustedWellPathTargets.back().isTangentConstrained)
if ( !adjustedWellPathTargets.back().isTangentConstrained )
{
endSSegementIdx -= 1;
}
@@ -157,94 +166,91 @@ RiaLineArcWellPathCalculator::RiaLineArcWellPathCalculator(const cvf::Vec3d& ref
{
for ( size_t tIdx = startSSegmentIdx; tIdx < endSSegementIdx; ++tIdx )
{
const WellTarget& target1 = adjustedWellPathTargets[tIdx];
const WellTarget& target2 = adjustedWellPathTargets[tIdx+1];
const WellTarget& target1 = adjustedWellPathTargets[tIdx];
const WellTarget& target2 = adjustedWellPathTargets[tIdx + 1];
WellTargetStatus& target1Status = m_targetStatuses[tIdx];
WellTargetStatus& target2Status = m_targetStatuses[tIdx+1];
WellTargetStatus& target2Status = m_targetStatuses[tIdx + 1];
// Ignore targets in the same place
if ( (target1.targetPointXYZ - target2.targetPointXYZ).length() < 1e-6 ) continue;
if ( ( target1.targetPointXYZ - target2.targetPointXYZ ).length() < 1e-6 ) continue;
if ( target1.isTangentConstrained
&& target2.isTangentConstrained )
if ( target1.isTangentConstrained && target2.isTangentConstrained )
{
RiaSCurveCalculator sCurveCalc(target1.targetPointXYZ,
target1.azimuth,
target1.inclination,
target1.radius2,
target2.targetPointXYZ,
target2.azimuth,
target2.inclination,
target2.radius1);
RiaSCurveCalculator sCurveCalc( target1.targetPointXYZ,
target1.azimuth,
target1.inclination,
target1.radius2,
target2.targetPointXYZ,
target2.azimuth,
target2.inclination,
target2.radius1 );
if ( sCurveCalc.solveStatus() != RiaSCurveCalculator::CONVERGED )
{
double p1p2Length = (target2.targetPointXYZ - target1.targetPointXYZ).length();
sCurveCalc = RiaSCurveCalculator::fromTangentsAndLength(target1.targetPointXYZ,
target1.azimuth,
target1.inclination,
0.2*p1p2Length,
target2.targetPointXYZ,
target2.azimuth,
target2.inclination,
0.2*p1p2Length);
double p1p2Length = ( target2.targetPointXYZ - target1.targetPointXYZ ).length();
sCurveCalc = RiaSCurveCalculator::fromTangentsAndLength( target1.targetPointXYZ,
target1.azimuth,
target1.inclination,
0.2 * p1p2Length,
target2.targetPointXYZ,
target2.azimuth,
target2.inclination,
0.2 * p1p2Length );
//RiaLogging::warning("Using fall-back calculation of well path geometry between active target number: " + QString::number(tIdx+1) + " and " + QString::number(tIdx+2));
// RiaLogging::warning("Using fall-back calculation of well path geometry between active target
// number: " + QString::number(tIdx+1) + " and " + QString::number(tIdx+2));
target1Status.hasOverriddenRadius2 = true;
target1Status.resultRadius2 = sCurveCalc.firstRadius();
target1Status.resultRadius2 = sCurveCalc.firstRadius();
target2Status.hasOverriddenRadius1 = true;
target2Status.resultRadius1 = sCurveCalc.secondRadius();
target2Status.resultRadius1 = sCurveCalc.secondRadius();
}
m_lineArcEndpoints.push_back(sCurveCalc.firstArcEndpoint() + referencePointXyz);
m_lineArcEndpoints.push_back(sCurveCalc.secondArcStartpoint() + referencePointXyz);
m_lineArcEndpoints.push_back(target2.targetPointXYZ + referencePointXyz);
m_lineArcEndpoints.push_back( sCurveCalc.firstArcEndpoint() + referencePointXyz );
m_lineArcEndpoints.push_back( sCurveCalc.secondArcStartpoint() + referencePointXyz );
m_lineArcEndpoints.push_back( target2.targetPointXYZ + referencePointXyz );
}
}
}
// Handle last segment if (its not the same as the first) and it has not been handled as an S-Curve
if ( adjustedWellPathTargets.size() > 2 && endSSegementIdx < (adjustedWellPathTargets.size() - 1) )
if ( adjustedWellPathTargets.size() > 2 && endSSegementIdx < ( adjustedWellPathTargets.size() - 1 ) )
{
size_t targetCount = adjustedWellPathTargets.size();
const WellTarget& target1 = adjustedWellPathTargets[targetCount-2];
const WellTarget& target2 = adjustedWellPathTargets[targetCount-1];
WellTargetStatus& target1Status = m_targetStatuses[targetCount-2];
WellTargetStatus& target2Status = m_targetStatuses[targetCount-1];
size_t targetCount = adjustedWellPathTargets.size();
const WellTarget& target1 = adjustedWellPathTargets[targetCount - 2];
const WellTarget& target2 = adjustedWellPathTargets[targetCount - 1];
WellTargetStatus& target1Status = m_targetStatuses[targetCount - 2];
WellTargetStatus& target2Status = m_targetStatuses[targetCount - 1];
// Create an ordinary J curve
RiaJCurveCalculator jCurve(target1.targetPointXYZ,
target1.azimuth,
target1.inclination,
target1.radius2,
target2.targetPointXYZ);
RiaJCurveCalculator jCurve( target1.targetPointXYZ,
target1.azimuth,
target1.inclination,
target1.radius2,
target2.targetPointXYZ );
if ( jCurve.curveStatus() == RiaJCurveCalculator::OK )
{
m_lineArcEndpoints.push_back(jCurve.firstArcEndpoint() + referencePointXyz);
m_lineArcEndpoints.push_back( jCurve.firstArcEndpoint() + referencePointXyz );
}
else if ( jCurve.curveStatus() == RiaJCurveCalculator::FAILED_RADIUS_TOO_LARGE )
{
target1Status.hasOverriddenRadius2 = true;
target1Status.resultRadius2 = jCurve.radius();
target1Status.resultRadius2 = jCurve.radius();
}
m_lineArcEndpoints.push_back(target2.targetPointXYZ + referencePointXyz);
m_lineArcEndpoints.push_back( target2.targetPointXYZ + referencePointXyz );
target2Status.hasDerivedTangent = true;
target2Status.resultAzimuth = jCurve.endAzimuth();
target2Status.resultAzimuth = jCurve.endAzimuth();
target2Status.resultInclination = jCurve.endInclination();
}
}
cvf::Vec3d smootheningTargetTangent(const cvf::Vec3d& p1, const cvf::Vec3d& p2, const cvf::Vec3d& p3)
cvf::Vec3d smootheningTargetTangent( const cvf::Vec3d& p1, const cvf::Vec3d& p2, const cvf::Vec3d& p3 )
{
cvf::Vec3d t12 = p2 - p1;
cvf::Vec3d t23 = p3 - p2;
@@ -255,27 +261,26 @@ cvf::Vec3d smootheningTargetTangent(const cvf::Vec3d& p1, const cvf::Vec3d& p2,
t12 /= length12; // Normalize
t23 /= length23; // Normalize
cvf::Vec3d t1t2Hor(t12);
t1t2Hor.z() = 0.0;
cvf::Vec3d t1t2Hor( t12 );
t1t2Hor.z() = 0.0;
double t12HorLength = t1t2Hor.length();
cvf::Vec3d t23Hor(t23);
t23Hor.z() = 0.0;
cvf::Vec3d t23Hor( t23 );
t23Hor.z() = 0.0;
double t23HorLength = t23Hor.length();
// Calculate weights as combo of inverse distance and horizontal component
double w12 = t12HorLength * 1.0/length12;
double w23 = t23HorLength * 1.0/length23;
double w12 = t12HorLength * 1.0 / length12;
double w23 = t23HorLength * 1.0 / length23;
// Weight the tangents
// Weight the tangents
t12 *= w12; // Weight
t23 *= w23; // Weight
// Sum and normalization of weights
cvf::Vec3d averageTangent = 1.0/(w12 + w23) * (t12 + t23);
// Sum and normalization of weights
cvf::Vec3d averageTangent = 1.0 / ( w12 + w23 ) * ( t12 + t23 );
return averageTangent;
}

View File

@@ -18,7 +18,6 @@
#pragma once
#include "cvfVector3.h"
#include <vector>
@@ -29,36 +28,44 @@ public:
struct WellTarget
{
cvf::Vec3d targetPointXYZ;
bool isTangentConstrained;
double azimuth;
double inclination;
bool isTangentConstrained;
double azimuth;
double inclination;
double radius1;
double radius2;
};
RiaLineArcWellPathCalculator(const cvf::Vec3d& referencePointXyz,
const std::vector<RiaLineArcWellPathCalculator::WellTarget>& targets);
RiaLineArcWellPathCalculator( const cvf::Vec3d& referencePointXyz,
const std::vector<RiaLineArcWellPathCalculator::WellTarget>& targets );
struct WellTargetStatus
{
bool hasDerivedTangent;
bool hasDerivedTangent;
double resultAzimuth;
double resultInclination;
bool hasOverriddenRadius1;
bool hasOverriddenRadius1;
double resultRadius1;
bool hasOverriddenRadius2;
bool hasOverriddenRadius2;
double resultRadius2;
};
cvf::Vec3d startTangent() const { return m_startTangent; }
const std::vector<cvf::Vec3d>& lineArcEndpoints() const { return m_lineArcEndpoints;}
const std::vector<WellTargetStatus>& targetStatuses() const { return m_targetStatuses;}
cvf::Vec3d startTangent() const
{
return m_startTangent;
}
const std::vector<cvf::Vec3d>& lineArcEndpoints() const
{
return m_lineArcEndpoints;
}
const std::vector<WellTargetStatus>& targetStatuses() const
{
return m_targetStatuses;
}
private:
cvf::Vec3d m_startTangent;
std::vector<cvf::Vec3d> m_lineArcEndpoints;
std::vector<WellTargetStatus> m_targetStatuses;
};

View File

@@ -25,14 +25,15 @@
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
RiaPolyArcLineSampler::RiaPolyArcLineSampler(const cvf::Vec3d& startTangent, const std::vector<cvf::Vec3d>& lineArcEndPoints)
: m_startTangent(startTangent)
, m_lineArcEndPoints(lineArcEndPoints)
, m_samplingsInterval(0.15)
, m_isResamplingLines(true)
, m_totalMD(0.0)
, m_points(nullptr)
, m_meshDs(nullptr)
RiaPolyArcLineSampler::RiaPolyArcLineSampler( const cvf::Vec3d& startTangent,
const std::vector<cvf::Vec3d>& lineArcEndPoints )
: m_startTangent( startTangent )
, m_lineArcEndPoints( lineArcEndPoints )
, m_samplingsInterval( 0.15 )
, m_isResamplingLines( true )
, m_totalMD( 0.0 )
, m_points( nullptr )
, m_meshDs( nullptr )
{
}
@@ -40,12 +41,12 @@ RiaPolyArcLineSampler::RiaPolyArcLineSampler(const cvf::Vec3d& startTangent, con
///
//--------------------------------------------------------------------------------------------------
void RiaPolyArcLineSampler::sampledPointsAndMDs(double sampleInterval,
bool isResamplingLines,
std::vector<cvf::Vec3d>* points,
std::vector<double>* mds)
void RiaPolyArcLineSampler::sampledPointsAndMDs( double sampleInterval,
bool isResamplingLines,
std::vector<cvf::Vec3d>* points,
std::vector<double>* mds )
{
CVF_ASSERT(sampleInterval > 0.0);
CVF_ASSERT( sampleInterval > 0.0 );
m_samplingsInterval = sampleInterval;
m_isResamplingLines = isResamplingLines;
@@ -54,9 +55,9 @@ void RiaPolyArcLineSampler::sampledPointsAndMDs(double sampleI
points->clear();
mds->clear();
std::vector<cvf::Vec3d> pointsNoDuplicates = RiaPolyArcLineSampler::pointsWithoutDuplicates(m_lineArcEndPoints);
std::vector<cvf::Vec3d> pointsNoDuplicates = RiaPolyArcLineSampler::pointsWithoutDuplicates( m_lineArcEndPoints );
if (pointsNoDuplicates.size() < 2) return;
if ( pointsNoDuplicates.size() < 2 ) return;
m_points = points;
m_meshDs = mds;
@@ -65,14 +66,14 @@ void RiaPolyArcLineSampler::sampledPointsAndMDs(double sampleI
cvf::Vec3d p1 = pointsNoDuplicates[0];
cvf::Vec3d p2 = pointsNoDuplicates[1];
m_points->push_back(p1);
m_meshDs->push_back(m_totalMD);
m_points->push_back( p1 );
m_meshDs->push_back( m_totalMD );
cvf::Vec3d t2 = m_startTangent;
for (size_t pIdx = 0; pIdx < pointsNoDuplicates.size() - 1; ++pIdx)
for ( size_t pIdx = 0; pIdx < pointsNoDuplicates.size() - 1; ++pIdx )
{
sampleSegment(t2, pointsNoDuplicates[pIdx], pointsNoDuplicates[pIdx + 1], &t2);
sampleSegment( t2, pointsNoDuplicates[pIdx], pointsNoDuplicates[pIdx + 1], &t2 );
}
return;
@@ -81,36 +82,36 @@ void RiaPolyArcLineSampler::sampledPointsAndMDs(double sampleI
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaPolyArcLineSampler::sampleSegment(cvf::Vec3d t1, cvf::Vec3d p1, cvf::Vec3d p2, cvf::Vec3d* endTangent)
void RiaPolyArcLineSampler::sampleSegment( cvf::Vec3d t1, cvf::Vec3d p1, cvf::Vec3d p2, cvf::Vec3d* endTangent )
{
cvf::Vec3d p1p2 = p2 - p1;
CVF_ASSERT(p1p2.lengthSquared() > 1e-20);
CVF_ASSERT( p1p2.lengthSquared() > 1e-20 );
if (cvf::GeometryTools::getAngle(t1, p1p2) < 1e-5)
if ( cvf::GeometryTools::getAngle( t1, p1p2 ) < 1e-5 )
{
sampleLine(p1, p2, endTangent);
sampleLine( p1, p2, endTangent );
}
else // resample arc
{
sampleArc(t1, p1, p2, endTangent);
sampleArc( t1, p1, p2, endTangent );
}
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
std::vector<cvf::Vec3d> RiaPolyArcLineSampler::pointsWithoutDuplicates(const std::vector<cvf::Vec3d>& points)
std::vector<cvf::Vec3d> RiaPolyArcLineSampler::pointsWithoutDuplicates( const std::vector<cvf::Vec3d>& points )
{
std::vector<cvf::Vec3d> outputPoints;
cvf::Vec3d previousPoint = cvf::Vec3d::UNDEFINED;
const double threshold = 1e-6;
for (const auto& p : points)
for ( const auto& p : points )
{
if (previousPoint.isUndefined() || ((previousPoint - p).lengthSquared()) > threshold)
if ( previousPoint.isUndefined() || ( ( previousPoint - p ).lengthSquared() ) > threshold )
{
outputPoints.push_back(p);
outputPoints.push_back( p );
previousPoint = p;
}
}
@@ -121,37 +122,37 @@ std::vector<cvf::Vec3d> RiaPolyArcLineSampler::pointsWithoutDuplicates(const std
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaPolyArcLineSampler::sampleLine(cvf::Vec3d p1, cvf::Vec3d p2, cvf::Vec3d* endTangent)
void RiaPolyArcLineSampler::sampleLine( cvf::Vec3d p1, cvf::Vec3d p2, cvf::Vec3d* endTangent )
{
cvf::Vec3d p1p2 = p2 - p1;
double p1p2Length = p1p2.length();
if (p1p2Length > m_samplingsInterval && m_isResamplingLines)
if ( p1p2Length > m_samplingsInterval && m_isResamplingLines )
{
cvf::Vec3d tp1p2 = p1p2 / p1p2Length;
double mdInc = m_samplingsInterval;
while (mdInc < p1p2Length)
while ( mdInc < p1p2Length )
{
cvf::Vec3d ps = p1 + mdInc * tp1p2;
m_points->push_back(ps);
m_meshDs->push_back(m_totalMD + mdInc);
m_points->push_back( ps );
m_meshDs->push_back( m_totalMD + mdInc );
mdInc += m_samplingsInterval;
}
}
m_totalMD += p1p2Length;
m_points->push_back(p2);
m_meshDs->push_back(m_totalMD);
m_points->push_back( p2 );
m_meshDs->push_back( m_totalMD );
(*endTangent) = p1p2.getNormalized();
( *endTangent ) = p1p2.getNormalized();
}
//--------------------------------------------------------------------------------------------------
///
//--------------------------------------------------------------------------------------------------
void RiaPolyArcLineSampler::sampleArc(cvf::Vec3d t1, cvf::Vec3d p1, cvf::Vec3d p2, cvf::Vec3d* endTangent)
void RiaPolyArcLineSampler::sampleArc( cvf::Vec3d t1, cvf::Vec3d p1, cvf::Vec3d p2, cvf::Vec3d* endTangent )
{
// Find arc CS
RiaArcCurveCalculator CS_rad(p1, t1, p2);
RiaArcCurveCalculator CS_rad( p1, t1, p2 );
double radius = CS_rad.radius();
cvf::Mat4d arcCS = CS_rad.arcCS();
@@ -164,26 +165,26 @@ void RiaPolyArcLineSampler::sampleArc(cvf::Vec3d t1, cvf::Vec3d p1, cvf::Vec3d p
// Sample arc by
// Rotate vector an increment, and transform to arc CS
double arcAngle = cvf::GeometryTools::getAngle(N, p1 - C, p2 - C);
if (arcAngle / angleInc > 5000)
double arcAngle = cvf::GeometryTools::getAngle( N, p1 - C, p2 - C );
if ( arcAngle / angleInc > 5000 )
{
angleInc = arcAngle / 5000;
}
for (double angle = angleInc; angle < arcAngle; angle += angleInc)
for ( double angle = angleInc; angle < arcAngle; angle += angleInc )
{
cvf::Vec3d C_to_incP = cvf::Vec3d::X_AXIS;
C_to_incP *= radius;
C_to_incP.transformVector(cvf::Mat3d::fromRotation(cvf::Vec3d::Z_AXIS, angle));
C_to_incP.transformVector( cvf::Mat3d::fromRotation( cvf::Vec3d::Z_AXIS, angle ) );
C_to_incP.transformPoint(arcCS);
C_to_incP.transformPoint( arcCS );
m_points->push_back(C_to_incP);
m_meshDs->push_back(m_totalMD + angle * radius);
m_points->push_back( C_to_incP );
m_meshDs->push_back( m_totalMD + angle * radius );
}
m_totalMD += arcAngle * radius;
m_points->push_back(p2);
m_meshDs->push_back(m_totalMD);
m_points->push_back( p2 );
m_meshDs->push_back( m_totalMD );
(*endTangent) = CS_rad.endTangent();
( *endTangent ) = CS_rad.endTangent();
}

View File

@@ -18,7 +18,6 @@
#pragma once
#include "cvfVector3.h"
#include <vector>
@@ -26,19 +25,19 @@
class RiaPolyArcLineSampler
{
public:
RiaPolyArcLineSampler(const cvf::Vec3d& startTangent, const std::vector<cvf::Vec3d>& lineArcEndPoints);
RiaPolyArcLineSampler( const cvf::Vec3d& startTangent, const std::vector<cvf::Vec3d>& lineArcEndPoints );
void sampledPointsAndMDs(double sampleInterval,
bool isResamplingLines,
std::vector<cvf::Vec3d>* points,
std::vector<double>* mds);
void sampledPointsAndMDs( double sampleInterval,
bool isResamplingLines,
std::vector<cvf::Vec3d>* points,
std::vector<double>* mds );
static std::vector<cvf::Vec3d> pointsWithoutDuplicates(const std::vector<cvf::Vec3d>& points);
static std::vector<cvf::Vec3d> pointsWithoutDuplicates( const std::vector<cvf::Vec3d>& points );
private:
void sampleLine(cvf::Vec3d p1, cvf::Vec3d p2, cvf::Vec3d* endTangent);
void sampleArc(cvf::Vec3d t1, cvf::Vec3d p1, cvf::Vec3d p2, cvf::Vec3d* endTangent);
void sampleSegment(cvf::Vec3d t1, cvf::Vec3d p1, cvf::Vec3d p2, cvf::Vec3d* endTangent);
void sampleLine( cvf::Vec3d p1, cvf::Vec3d p2, cvf::Vec3d* endTangent );
void sampleArc( cvf::Vec3d t1, cvf::Vec3d p1, cvf::Vec3d p2, cvf::Vec3d* endTangent );
void sampleSegment( cvf::Vec3d t1, cvf::Vec3d p1, cvf::Vec3d p2, cvf::Vec3d* endTangent );
std::vector<cvf::Vec3d>* m_points; // Internal temporary pointers to collections beeing filled.
std::vector<double>* m_meshDs;

View File

@@ -26,66 +26,69 @@
#include <iostream>
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
RiaSCurveCalculator::RiaSCurveCalculator(cvf::Vec3d p1, double azi1, double inc1, double rad1,
cvf::Vec3d p2, double azi2, double inc2, double rad2)
: m_isCalculationOK(false)
, m_p1(p1)
, m_p2(p2)
, m_firstArcEndpoint(p1 + 0.3*(p2-p1))
, m_secondArcStartpoint(p1 + 0.6*(p2-p1))
, m_r1(rad1)
, m_r2(rad2)
, m_ctrlPpointCurveStatus(NOT_SET)
, m_solveStatus(NOT_SOLVED)
RiaSCurveCalculator::RiaSCurveCalculator(
cvf::Vec3d p1, double azi1, double inc1, double rad1, cvf::Vec3d p2, double azi2, double inc2, double rad2 )
: m_isCalculationOK( false )
, m_p1( p1 )
, m_p2( p2 )
, m_firstArcEndpoint( p1 + 0.3 * ( p2 - p1 ) )
, m_secondArcStartpoint( p1 + 0.6 * ( p2 - p1 ) )
, m_r1( rad1 )
, m_r2( rad2 )
, m_ctrlPpointCurveStatus( NOT_SET )
, m_solveStatus( NOT_SOLVED )
{
initializeByFinding_q1q2(p1, azi1, inc1, rad1, p2, azi2, inc2, rad2);
initializeByFinding_q1q2( p1, azi1, inc1, rad1, p2, azi2, inc2, rad2 );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
RiaSCurveCalculator::RiaSCurveCalculator(cvf::Vec3d p1, cvf::Vec3d q1,
cvf::Vec3d p2, cvf::Vec3d q2)
: m_isCalculationOK(true)
, m_p1(p1)
, m_p2(p2)
, m_ctrlPpointCurveStatus(NOT_SET)
, m_solveStatus(NOT_SOLVED)
RiaSCurveCalculator::RiaSCurveCalculator( cvf::Vec3d p1, cvf::Vec3d q1, cvf::Vec3d p2, cvf::Vec3d q2 )
: m_isCalculationOK( true )
, m_p1( p1 )
, m_p2( p2 )
, m_ctrlPpointCurveStatus( NOT_SET )
, m_solveStatus( NOT_SOLVED )
{
using Vec3d = cvf::Vec3d;
bool isOk = true;
using Vec3d = cvf::Vec3d;
bool isOk = true;
m_isCalculationOK = true;
Vec3d tq1q2 = (q2 - q1).getNormalized(&isOk); // !ok means the control points are in the same place. Could fallback to use only one circle segment + one line.
Vec3d tq1q2 = ( q2 - q1 ).getNormalized(
&isOk ); // !ok means the control points are in the same place. Could fallback to use only one circle segment + one line.
m_isCalculationOK = m_isCalculationOK && isOk;
Vec3d t1 = (q1 - p1).getNormalized(&isOk); // !ok means no tangent specified. Could fallback to use only one circle segment + one line.
Vec3d t1 = ( q1 - p1 ).getNormalized(
&isOk ); // !ok means no tangent specified. Could fallback to use only one circle segment + one line.
m_isCalculationOK = m_isCalculationOK && isOk;
Vec3d t2 = (p2 - q2).getNormalized(&isOk); // !ok means no tangent specified. Could fallback to use only one circle segment + one line or only one straight line if both tangents are missing
Vec3d t2 = ( p2 - q2 ).getNormalized(
&isOk ); // !ok means no tangent specified. Could fallback to use only one circle segment + one line or only one
// straight line if both tangents are missing
m_isCalculationOK = m_isCalculationOK && isOk;
if (!m_isCalculationOK)
if ( !m_isCalculationOK )
{
m_ctrlPpointCurveStatus = FAILED_INPUT_OVERLAP;
}
{
Vec3d td1 = (tq1q2 - t1);
Vec3d td1 = ( tq1q2 - t1 );
double td1Length = td1.length();
if ( td1Length > 1e-10 )
{
td1 /= td1Length;
m_c1 = q1 + ((q1 - p1).length() / (td1 * (-t1))) * td1;
m_r1 = (m_c1 - p1).length();
m_c1 = q1 + ( ( q1 - p1 ).length() / ( td1 * ( -t1 ) ) ) * td1;
m_r1 = ( m_c1 - p1 ).length();
}
else // both control points are along t1. First curve has infinite radius
{
m_c1 = cvf::Vec3d::UNDEFINED;
m_r1 = std::numeric_limits<double>::infinity();
if (m_ctrlPpointCurveStatus == NOT_SET)
if ( m_ctrlPpointCurveStatus == NOT_SET )
{
m_ctrlPpointCurveStatus = OK_INFINITE_RADIUS1;
}
@@ -93,107 +96,109 @@ RiaSCurveCalculator::RiaSCurveCalculator(cvf::Vec3d p1, cvf::Vec3d q1,
}
{
Vec3d td2 = (-tq1q2 + t2);
Vec3d td2 = ( -tq1q2 + t2 );
double td2Length = td2.length();
if ( td2Length > 1e-10 )
{
td2 /= td2Length;
m_c2 = q2 + ((q2 - p2).length() / (td2 * (t2))) * td2;
m_r2 = (m_c2 - p2).length();
m_c2 = q2 + ( ( q2 - p2 ).length() / ( td2 * ( t2 ) ) ) * td2;
m_r2 = ( m_c2 - p2 ).length();
}
else // both control points are along t2. Second curve has infinite radius
{
m_c2 = cvf::Vec3d::UNDEFINED;
m_r2 = std::numeric_limits<double>::infinity();
if (m_ctrlPpointCurveStatus == NOT_SET)
if ( m_ctrlPpointCurveStatus == NOT_SET )
{
m_ctrlPpointCurveStatus = OK_INFINITE_RADIUS2;
}
else if (m_ctrlPpointCurveStatus == OK_INFINITE_RADIUS1)
else if ( m_ctrlPpointCurveStatus == OK_INFINITE_RADIUS1 )
{
m_ctrlPpointCurveStatus = OK_INFINITE_RADIUS12;
}
}
}
m_firstArcEndpoint = q1 + (q1 - p1).length() * tq1q2;
m_secondArcStartpoint = q2 - (q2 - p2).length() * tq1q2;
m_firstArcEndpoint = q1 + ( q1 - p1 ).length() * tq1q2;
m_secondArcStartpoint = q2 - ( q2 - p2 ).length() * tq1q2;
if (((q1 - p1).length() + (q2 - p2).length()) > (q2 - q1).length()) // first arc end and second arc start is overlapping
if ( ( ( q1 - p1 ).length() + ( q2 - p2 ).length() ) >
( q2 - q1 ).length() ) // first arc end and second arc start is overlapping
{
m_ctrlPpointCurveStatus = FAILED_ARC_OVERLAP;
m_isCalculationOK = false;
m_isCalculationOK = false;
}
if (m_ctrlPpointCurveStatus == NOT_SET)
if ( m_ctrlPpointCurveStatus == NOT_SET )
{
m_ctrlPpointCurveStatus = OK;
}
// The Circle normals. Will be set to cvf::Vec3d::ZERO if undefined.
m_n1 = (t1 ^ tq1q2).getNormalized();
m_n2 = (tq1q2 ^ t2).getNormalized();
m_n1 = ( t1 ^ tq1q2 ).getNormalized();
m_n2 = ( tq1q2 ^ t2 ).getNormalized();
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
RiaSCurveCalculator RiaSCurveCalculator::fromTangentsAndLength(cvf::Vec3d p1, double azi1, double inc1, double lengthToQ1,
cvf::Vec3d p2, double azi2, double inc2, double lengthToQ2)
RiaSCurveCalculator RiaSCurveCalculator::fromTangentsAndLength(
cvf::Vec3d p1, double azi1, double inc1, double lengthToQ1, cvf::Vec3d p2, double azi2, double inc2, double lengthToQ2 )
{
cvf::Vec3d t1(RiaOffshoreSphericalCoords::unitVectorFromAziInc(azi1,inc1));
cvf::Vec3d t2(RiaOffshoreSphericalCoords::unitVectorFromAziInc(azi2,inc2));
cvf::Vec3d t1( RiaOffshoreSphericalCoords::unitVectorFromAziInc( azi1, inc1 ) );
cvf::Vec3d t2( RiaOffshoreSphericalCoords::unitVectorFromAziInc( azi2, inc2 ) );
cvf::Vec3d Q1 = p1 + lengthToQ1 * t1;
cvf::Vec3d Q2 = p2 - lengthToQ2 * t2;
RiaSCurveCalculator curveFromControlPoints(p1, Q1,
p2, Q2);
RiaSCurveCalculator curveFromControlPoints( p1, Q1, p2, Q2 );
return curveFromControlPoints;
}
//--------------------------------------------------------------------------------------------------
///
///
/// Needs to calculate J^-1 * [R1_error, R2_error]
/// | dR1_dq1 dR1_dq2 | 1 | dR2_dq2 -dR1_dq2 |
/// J = | | J^-1 = ---------------------------------- | |
/// | dR2_dq1 dR2_dq2 | dR1_dq1*dR2_dq2 - dR1_dq2*dR2_dq1 | -dR2_dq1 dR1_dq1 |
/// | dR1_dq1 dR1_dq2 | 1 | dR2_dq2 -dR1_dq2 |
/// J = | | J^-1 = ---------------------------------- | |
/// | dR2_dq1 dR2_dq2 | dR1_dq1*dR2_dq2 - dR1_dq2*dR2_dq1 | -dR2_dq1 dR1_dq1 |
///
/// | q1_step | | R1_Error |
/// | | = - J^-1 | |
/// | q2_step | | R2_Error |
///
//--------------------------------------------------------------------------------------------------
void calculateNewStepsFromJacobi(double dR1_dq1, double dR1_dq2,
double dR2_dq1, double dR2_dq2,
double R1_error,
double R2_error,
double * newStepq1,
double * newStepq2)
void calculateNewStepsFromJacobi( double dR1_dq1,
double dR1_dq2,
double dR2_dq1,
double dR2_dq2,
double R1_error,
double R2_error,
double* newStepq1,
double* newStepq2 )
{
double invJacobiScale = 1.0/ (dR1_dq1*dR2_dq2 - dR2_dq1*dR1_dq2);
double invJacobi_R1q1 = invJacobiScale * dR2_dq2;
double invJacobi_R1q2 = invJacobiScale * -dR1_dq2;
double invJacobi_R2q1 = invJacobiScale * -dR2_dq1;
double invJacobi_R2q2 = invJacobiScale * dR1_dq1;
double invJacobiScale = 1.0 / ( dR1_dq1 * dR2_dq2 - dR2_dq1 * dR1_dq2 );
double invJacobi_R1q1 = invJacobiScale * dR2_dq2;
double invJacobi_R1q2 = invJacobiScale * -dR1_dq2;
double invJacobi_R2q1 = invJacobiScale * -dR2_dq1;
double invJacobi_R2q2 = invJacobiScale * dR1_dq1;
(*newStepq1) = - (invJacobi_R1q1 * R1_error + invJacobi_R1q2 * R2_error);
(*newStepq2) = - (invJacobi_R2q1 * R1_error + invJacobi_R2q2 * R2_error) ;
( *newStepq1 ) = -( invJacobi_R1q1 * R1_error + invJacobi_R1q2 * R2_error );
( *newStepq2 ) = -( invJacobi_R2q1 * R1_error + invJacobi_R2q2 * R2_error );
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
bool isZeroCrossing(double newError, double oldError, double maxError)
bool isZeroCrossing( double newError, double oldError, double maxError )
{
if ( (newError < -maxError && maxError < oldError) || (newError > maxError && -maxError > oldError) )
if ( ( newError < -maxError && maxError < oldError ) || ( newError > maxError && -maxError > oldError ) )
{
return true;
}
}
return false;
}
@@ -204,87 +209,81 @@ bool isZeroCrossing(double newError, double oldError, double maxError)
/// R1(q1, q2), R2(q1, q2)
///
//--------------------------------------------------------------------------------------------------
void RiaSCurveCalculator::initializeByFinding_q1q2(cvf::Vec3d p1, double azi1, double inc1, double r1,
cvf::Vec3d p2, double azi2, double inc2, double r2)
void RiaSCurveCalculator::initializeByFinding_q1q2(
cvf::Vec3d p1, double azi1, double inc1, double r1, cvf::Vec3d p2, double azi2, double inc2, double r2 )
{
// Algorithm options
const int maxIterations = 40;
const double maxError = 0.01;
const double maxStepSize = 1.0e9;
const double maxLengthToQ = 1.0e10;
bool enableBackstepping = false;
const int maxIterations = 40;
const double maxError = 0.01;
const double maxStepSize = 1.0e9;
const double maxLengthToQ = 1.0e10;
bool enableBackstepping = false;
//#define USE_JACOBI_UPDATE
//#define DEBUG_OUTPUT_ON
// Needs the initial partial derivatives to see the direction of change
// dR1/dq1, dR1/dq2, dR2/dq1, dR2/dq2
// Selects a sensible point in the domain for the evaluation
double p1p2Length = (p2 - p1).length();
double delta = 0.01 * p1p2Length;
double p1p2Length = ( p2 - p1 ).length();
double delta = 0.01 * p1p2Length;
double initialq1q2 = 0.2 * p1p2Length;
double deltaPos = initialq1q2 + delta;
double deltaPos = initialq1q2 + delta;
RiaSCurveCalculator ev_0 = RiaSCurveCalculator::fromTangentsAndLength(p1, azi1, inc1, initialq1q2,
p2, azi2, inc2, initialq1q2);
RiaSCurveCalculator ev_0 =
RiaSCurveCalculator::fromTangentsAndLength( p1, azi1, inc1, initialq1q2, p2, azi2, inc2, initialq1q2 );
if ( ev_0.curveStatus() == RiaSCurveCalculator::OK_INFINITE_RADIUS12 )
{
*this = ev_0;
*this = ev_0;
this->m_solveStatus = CONVERGED;
return;
} // Todo: Handle infinite radius in one place
RiaSCurveCalculator ev_dq1 = RiaSCurveCalculator::fromTangentsAndLength(p1, azi1, inc1, deltaPos,
p2, azi2, inc2, initialq1q2);
RiaSCurveCalculator ev_dq2 = RiaSCurveCalculator::fromTangentsAndLength(p1, azi1, inc1, initialq1q2,
p2, azi2, inc2, deltaPos);
RiaSCurveCalculator ev_dq1 =
RiaSCurveCalculator::fromTangentsAndLength( p1, azi1, inc1, deltaPos, p2, azi2, inc2, initialq1q2 );
RiaSCurveCalculator ev_dq2 =
RiaSCurveCalculator::fromTangentsAndLength( p1, azi1, inc1, initialq1q2, p2, azi2, inc2, deltaPos );
// Initial Jacobi
double dR1_dq1 = ((r1 - ev_dq1.firstRadius()) - (r1 - ev_0.firstRadius()))/delta;
double dR2_dq2 = ((r2 - ev_dq2.secondRadius()) - (r2 - ev_0.secondRadius()))/delta;
double dR1_dq1 = ( ( r1 - ev_dq1.firstRadius() ) - ( r1 - ev_0.firstRadius() ) ) / delta;
double dR2_dq2 = ( ( r2 - ev_dq2.secondRadius() ) - ( r2 - ev_0.secondRadius() ) ) / delta;
// Initial function value (error)
double R1_error = r1 - ev_0.firstRadius();
double R2_error = r2 - ev_0.secondRadius();
// First steps
double q1Step = -R1_error/dR1_dq1;
double q2Step = -R2_error/dR2_dq2;
double q1Step = -R1_error / dR1_dq1;
double q2Step = -R2_error / dR2_dq2;
#ifdef USE_JACOBI_UPDATE
double dR1_dq2 = ((r1 - ev_dq2.firstRadius()) - (r1 - ev_0.firstRadius()))/delta;
double dR2_dq1 = ((r2 - ev_dq1.secondRadius()) - (r2 - ev_0.secondRadius()))/delta;
#ifdef USE_JACOBI_UPDATE
double dR1_dq2 = ( ( r1 - ev_dq2.firstRadius() ) - ( r1 - ev_0.firstRadius() ) ) / delta;
double dR2_dq1 = ( ( r2 - ev_dq1.secondRadius() ) - ( r2 - ev_0.secondRadius() ) ) / delta;
calculateNewStepsFromJacobi(dR1_dq1, dR1_dq2,
dR2_dq1, dR2_dq2,
R1_error, R2_error,
&q1Step, &q2Step);
#endif
calculateNewStepsFromJacobi( dR1_dq1, dR1_dq2, dR2_dq1, dR2_dq2, R1_error, R2_error, &q1Step, &q2Step );
#endif
double q1 = initialq1q2;
double q2 = initialq1q2;
#ifdef DEBUG_OUTPUT_ON
#ifdef DEBUG_OUTPUT_ON
std::cout << std::endl;
std::cout << "Targets: R1, R2: " << r1 << " , " << r2 << std::endl;
std::cout << 0 << ": " << q1Step << " , " << q2Step
<< " : " << q1 << " , " << q2 << " | "
<< ev_0.isOk() << " : " << ev_0.firstRadius() << " , " << ev_0.secondRadius()
<< " : " << R1_error << " , " << R2_error << std::endl;
#endif
std::cout << 0 << ": " << q1Step << " , " << q2Step << " : " << q1 << " , " << q2 << " | " << ev_0.isOk() << " : "
<< ev_0.firstRadius() << " , " << ev_0.secondRadius() << " : " << R1_error << " , " << R2_error
<< std::endl;
#endif
SolveStatus solveResultStatus = NOT_SOLVED;
int backstepLevel = 0;
int iteration = 1;
for ( iteration = 1; iteration < maxIterations; ++iteration)
int iteration = 1;
for ( iteration = 1; iteration < maxIterations; ++iteration )
{
if ( fabs(q1Step) > maxStepSize || fabs(q2Step) > maxStepSize )
if ( fabs( q1Step ) > maxStepSize || fabs( q2Step ) > maxStepSize )
{
solveResultStatus = FAILED_MAX_TANGENT_STEP_REACHED;
@@ -294,68 +293,74 @@ void RiaSCurveCalculator::initializeByFinding_q1q2(cvf::Vec3d p1, double azi1, d
std::string q1R1StepCorrMarker;
std::string q2R2StepCorrMarker;
if (q1 + q1Step < 0) { q1Step = -0.9*q1; q1R1StepCorrMarker = "*";}
if (q2 + q2Step < 0) { q2Step = -0.9*q2; q2R2StepCorrMarker = "*"; }
if ( q1 + q1Step < 0 )
{
q1Step = -0.9 * q1;
q1R1StepCorrMarker = "*";
}
if ( q2 + q2Step < 0 )
{
q2Step = -0.9 * q2;
q2R2StepCorrMarker = "*";
}
q1 += q1Step;
q2 += q2Step;
if (fabs(q1) > maxLengthToQ || fabs(q2) > maxLengthToQ)
if ( fabs( q1 ) > maxLengthToQ || fabs( q2 ) > maxLengthToQ )
{
/// Max length along tangent reached
solveResultStatus = FAILED_MAX_LENGTH_ALONG_TANGENT_REACHED;
break;
}
RiaSCurveCalculator ev_1 = RiaSCurveCalculator::fromTangentsAndLength(p1, azi1, inc1, q1,
p2, azi2, inc2, q2);
RiaSCurveCalculator ev_1 = RiaSCurveCalculator::fromTangentsAndLength( p1, azi1, inc1, q1, p2, azi2, inc2, q2 );
double R1_error_new = r1 - ev_1.firstRadius();
double R2_error_new = r2 - ev_1.secondRadius();
#ifdef DEBUG_OUTPUT_ON
std::cout << iteration << ": " << q1Step << q1R1StepCorrMarker << " , " << q2Step<< q2R2StepCorrMarker
<< " : " << q1 << " , " << q2 << " | "
<< ev_1.isOk() << " : " << ev_1.firstRadius() << " , " << ev_1.secondRadius()
<< " : " << R1_error_new << " , " << R2_error_new ;
#endif
#ifdef DEBUG_OUTPUT_ON
std::cout << iteration << ": " << q1Step << q1R1StepCorrMarker << " , " << q2Step << q2R2StepCorrMarker << " : "
<< q1 << " , " << q2 << " | " << ev_1.isOk() << " : " << ev_1.firstRadius() << " , "
<< ev_1.secondRadius() << " : " << R1_error_new << " , " << R2_error_new;
#endif
if ( ( fabs(R1_error_new) < maxError || ev_1.curveStatus() == OK_INFINITE_RADIUS1 )
&& ( fabs(R2_error_new) < maxError || ev_1.curveStatus() == OK_INFINITE_RADIUS2 ) )
if ( ( fabs( R1_error_new ) < maxError || ev_1.curveStatus() == OK_INFINITE_RADIUS1 ) &&
( fabs( R2_error_new ) < maxError || ev_1.curveStatus() == OK_INFINITE_RADIUS2 ) )
{
ev_0 = ev_1;
// Result ok !
solveResultStatus = CONVERGED;
#ifdef DEBUG_OUTPUT_ON
#ifdef DEBUG_OUTPUT_ON
std::cout << std::endl;
#endif
#endif
break;
}
if (enableBackstepping) // Experimental back-stepping
if ( enableBackstepping ) // Experimental back-stepping
{
bool isZeroCrossingR1 = isZeroCrossing(R1_error_new, R1_error, maxError);
bool isZeroCrossingR2 = isZeroCrossing(R2_error_new, R2_error, maxError);
bool isZeroCrossingR1 = isZeroCrossing( R1_error_new, R1_error, maxError );
bool isZeroCrossingR2 = isZeroCrossing( R2_error_new, R2_error, maxError );
if ( isZeroCrossingR2 || isZeroCrossingR1 )
{
q1 -= q1Step;
q2 -= q2Step;
//if (isZeroCrossingR1)
q1Step = 0.9* q1Step * fabs(R1_error) /(fabs(R1_error_new) + fabs(R1_error));
//if (isZeroCrossingR2)
q2Step = 0.9* q2Step * fabs(R2_error) /(fabs(R2_error_new) + fabs(R2_error));
// if (isZeroCrossingR1)
q1Step = 0.9 * q1Step * fabs( R1_error ) / ( fabs( R1_error_new ) + fabs( R1_error ) );
// if (isZeroCrossingR2)
q2Step = 0.9 * q2Step * fabs( R2_error ) / ( fabs( R2_error_new ) + fabs( R2_error ) );
++backstepLevel;
#ifdef DEBUG_OUTPUT_ON
std::cout << " Backstep needed. "<< std::endl;
#endif
#ifdef DEBUG_OUTPUT_ON
std::cout << " Backstep needed. " << std::endl;
#endif
continue;
}
@@ -365,52 +370,48 @@ void RiaSCurveCalculator::initializeByFinding_q1q2(cvf::Vec3d p1, double azi1, d
}
}
#ifdef DEBUG_OUTPUT_ON
#ifdef DEBUG_OUTPUT_ON
std::cout << std::endl;
#endif
#ifdef USE_JACOBI_UPDATE
#endif
#ifdef USE_JACOBI_UPDATE
/// Update Jacobi using Broyden
// (R_error_n-Rerror_n-1) - Jn-1*dq
// J_n = Jn-1 + --------------------------------- (dq)T
// | dqn |^2
//
//
double dR1_error = R1_error_new - R1_error;
double dR2_error = R2_error_new - R2_error;
R1_error = R1_error_new;
R2_error = R2_error_new;
double dR1_error = R1_error_new - R1_error;
double dR2_error = R2_error_new - R2_error;
R1_error = R1_error_new;
R2_error = R2_error_new;
double stepNormScale = 1.0/(q1Step*q1Step + q2Step*q2Step);
double stepNormScale = 1.0 / ( q1Step * q1Step + q2Step * q2Step );
dR1_dq1 = dR1_dq1 + stepNormScale * (q1Step * (dR1_error - q1Step * dR1_dq1 + q2Step * dR1_dq2) );
dR1_dq2 = dR1_dq2 + stepNormScale * (q2Step * (dR1_error - q1Step * dR1_dq1 + q2Step * dR1_dq2) );
dR2_dq1 = dR2_dq1 + stepNormScale * (q1Step * (dR2_error - q1Step * dR2_dq1 + q2Step * dR2_dq2) );
dR2_dq2 = dR2_dq2 + stepNormScale * (q2Step * (dR2_error - q1Step * dR2_dq1 + q2Step * dR2_dq2) );
dR1_dq1 = dR1_dq1 + stepNormScale * ( q1Step * ( dR1_error - q1Step * dR1_dq1 + q2Step * dR1_dq2 ) );
dR1_dq2 = dR1_dq2 + stepNormScale * ( q2Step * ( dR1_error - q1Step * dR1_dq1 + q2Step * dR1_dq2 ) );
dR2_dq1 = dR2_dq1 + stepNormScale * ( q1Step * ( dR2_error - q1Step * dR2_dq1 + q2Step * dR2_dq2 ) );
dR2_dq2 = dR2_dq2 + stepNormScale * ( q2Step * ( dR2_error - q1Step * dR2_dq1 + q2Step * dR2_dq2 ) );
calculateNewStepsFromJacobi(dR1_dq1, dR1_dq2,
dR2_dq1, dR2_dq2,
R1_error, R2_error,
&q1Step, &q2Step);
calculateNewStepsFromJacobi( dR1_dq1, dR1_dq2, dR2_dq1, dR2_dq2, R1_error, R2_error, &q1Step, &q2Step );
#else
#else
dR1_dq1 = ((r1 - ev_1.firstRadius()) - (r1 - ev_0.firstRadius()))/q1Step;
dR2_dq2 = ((r2 - ev_1.secondRadius()) - (r2 - ev_0.secondRadius()))/q2Step;
dR1_dq1 = ( ( r1 - ev_1.firstRadius() ) - ( r1 - ev_0.firstRadius() ) ) / q1Step;
dR2_dq2 = ( ( r2 - ev_1.secondRadius() ) - ( r2 - ev_0.secondRadius() ) ) / q2Step;
R1_error = R1_error_new;
R2_error = R2_error_new;
q1Step = -R1_error/dR1_dq1;
q2Step = -R2_error/dR2_dq2;
q1Step = -R1_error / dR1_dq1;
q2Step = -R2_error / dR2_dq2;
#endif
#endif
ev_0 = ev_1;
}
*this = ev_0;
if ( iteration >= maxIterations )
{
@@ -421,33 +422,39 @@ void RiaSCurveCalculator::initializeByFinding_q1q2(cvf::Vec3d p1, double azi1, d
{
m_solveStatus = solveResultStatus;
}
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaSCurveCalculator::dump() const
{
cvf::Vec3d v_C1 = firstCenter();
cvf::Vec3d v_C2 = secondCenter();
cvf::Vec3d v_N1 = firstNormal();
cvf::Vec3d v_N2 = secondNormal();
cvf::Vec3d v_C1 = firstCenter();
cvf::Vec3d v_C2 = secondCenter();
cvf::Vec3d v_N1 = firstNormal();
cvf::Vec3d v_N2 = secondNormal();
cvf::Vec3d v_P11 = firstArcEndpoint();
cvf::Vec3d v_P22 = secondArcStartpoint();
std::cout << " P1: " << "[ " << m_p1[0] << " " << m_p1[1] << " " << m_p1[2] << " " << std::endl;
std::cout << " P11: " << "[ " << v_P11[0] << " " << v_P11[1] << " " << v_P11[2] << " " << std::endl;
std::cout << " P22: " << "[ " << v_P22[0] << " " << v_P22[1] << " " << v_P22[2] << " " << std::endl;
std::cout << " P2: " << "[ " << m_p2[0] << " " << m_p2[1] << " " << m_p2[2] << " " << std::endl;
std::cout << " C1: " << "[ " << v_C1[0] << " " << v_C1[1] << " " << v_C1[2] << " " << std::endl;
std::cout << " C2: " << "[ " << v_C2[0] << " " << v_C2[1] << " " << v_C2[2] << " " << std::endl;
std::cout << " N1: " << "[ " << v_N1[0] << " " << v_N1[1] << " " << v_N1[2] << " " << std::endl;
std::cout << " N2: " << "[ " << v_N2[0] << " " << v_N2[1] << " " << v_N2[2] << " " << std::endl;
std::cout << " R1: " << "[ " << firstRadius() << " ]" << std::endl;
std::cout << " R2: " << "[ " << secondRadius() << " ]" << std::endl;
std::cout << " CtrPointStatus: " << m_ctrlPpointCurveStatus << " SolveStatus: " << m_solveStatus << std::endl;
std::cout << " P1: "
<< "[ " << m_p1[0] << " " << m_p1[1] << " " << m_p1[2] << " " << std::endl;
std::cout << " P11: "
<< "[ " << v_P11[0] << " " << v_P11[1] << " " << v_P11[2] << " " << std::endl;
std::cout << " P22: "
<< "[ " << v_P22[0] << " " << v_P22[1] << " " << v_P22[2] << " " << std::endl;
std::cout << " P2: "
<< "[ " << m_p2[0] << " " << m_p2[1] << " " << m_p2[2] << " " << std::endl;
std::cout << " C1: "
<< "[ " << v_C1[0] << " " << v_C1[1] << " " << v_C1[2] << " " << std::endl;
std::cout << " C2: "
<< "[ " << v_C2[0] << " " << v_C2[1] << " " << v_C2[2] << " " << std::endl;
std::cout << " N1: "
<< "[ " << v_N1[0] << " " << v_N1[1] << " " << v_N1[2] << " " << std::endl;
std::cout << " N2: "
<< "[ " << v_N2[0] << " " << v_N2[1] << " " << v_N2[2] << " " << std::endl;
std::cout << " R1: "
<< "[ " << firstRadius() << " ]" << std::endl;
std::cout << " R2: "
<< "[ " << secondRadius() << " ]" << std::endl;
std::cout << " CtrPointStatus: " << m_ctrlPpointCurveStatus << " SolveStatus: " << m_solveStatus << std::endl;
}

View File

@@ -18,17 +18,15 @@
#pragma once
#include "cvfVector3.h"
class RiaSCurveCalculator
{
public:
RiaSCurveCalculator( cvf::Vec3d p1, double azi1, double inc1, double r1,
cvf::Vec3d p2, double azi2, double inc2, double r2 );
RiaSCurveCalculator(
cvf::Vec3d p1, double azi1, double inc1, double r1, cvf::Vec3d p2, double azi2, double inc2, double r2 );
RiaSCurveCalculator( cvf::Vec3d p1, cvf::Vec3d q1,
cvf::Vec3d p2, cvf::Vec3d q2 );
RiaSCurveCalculator( cvf::Vec3d p1, cvf::Vec3d q1, cvf::Vec3d p2, cvf::Vec3d q2 );
enum CurveStatus
{
@@ -40,38 +38,75 @@ public:
FAILED_INPUT_OVERLAP,
FAILED_ARC_OVERLAP
};
enum SolveStatus
enum SolveStatus
{
NOT_SOLVED,
CONVERGED,
CONVERGED,
FAILED_MAX_LENGTH_ALONG_TANGENT_REACHED,
FAILED_MAX_TANGENT_STEP_REACHED,
FAILED_MAX_ITERATIONS_REACHED
};
bool isOk() const { return m_isCalculationOK; }
CurveStatus curveStatus() const { return m_ctrlPpointCurveStatus;}
SolveStatus solveStatus() const { return m_solveStatus;}
bool isOk() const
{
return m_isCalculationOK;
}
CurveStatus curveStatus() const
{
return m_ctrlPpointCurveStatus;
}
SolveStatus solveStatus() const
{
return m_solveStatus;
}
cvf::Vec3d firstArcEndpoint() const { return m_firstArcEndpoint; }
cvf::Vec3d secondArcStartpoint() const { return m_secondArcStartpoint; }
cvf::Vec3d firstCenter() const { return m_c1; }
cvf::Vec3d secondCenter() const { return m_c2; }
cvf::Vec3d firstNormal() const { return m_n1; }
cvf::Vec3d secondNormal() const { return m_n2; }
double firstRadius() const { return m_r1; }
double secondRadius() const { return m_r2; }
cvf::Vec3d firstArcEndpoint() const
{
return m_firstArcEndpoint;
}
cvf::Vec3d secondArcStartpoint() const
{
return m_secondArcStartpoint;
}
cvf::Vec3d firstCenter() const
{
return m_c1;
}
cvf::Vec3d secondCenter() const
{
return m_c2;
}
cvf::Vec3d firstNormal() const
{
return m_n1;
}
cvf::Vec3d secondNormal() const
{
return m_n2;
}
double firstRadius() const
{
return m_r1;
}
double secondRadius() const
{
return m_r2;
}
void dump() const;
static RiaSCurveCalculator fromTangentsAndLength(cvf::Vec3d p1, double azi1, double inc1, double lengthToQ1,
cvf::Vec3d p2, double azi2, double inc2, double lengthToQ2 );
static RiaSCurveCalculator fromTangentsAndLength( cvf::Vec3d p1,
double azi1,
double inc1,
double lengthToQ1,
cvf::Vec3d p2,
double azi2,
double inc2,
double lengthToQ2 );
private:
void initializeByFinding_q1q2( cvf::Vec3d p1, double azi1, double inc1, double r1,
cvf::Vec3d p2, double azi2, double inc2, double r2 );
void initializeByFinding_q1q2(
cvf::Vec3d p1, double azi1, double inc1, double r1, cvf::Vec3d p2, double azi2, double inc2, double r2 );
bool m_isCalculationOK;
@@ -86,6 +121,6 @@ private:
cvf::Vec3d m_c2;
cvf::Vec3d m_n1;
cvf::Vec3d m_n2;
double m_r1;
double m_r1;
double m_r2;
};

View File

@@ -17,118 +17,117 @@
/////////////////////////////////////////////////////////////////////////////////
#include "RiaWellPlanCalculator.h"
#include "cvfGeometryTools.h"
#include "cvfMatrix4.h"
#include "RiaArcCurveCalculator.h"
#include "RiaOffshoreSphericalCoords.h"
#include "cvfGeometryTools.h"
#include "cvfMatrix4.h"
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
RiaWellPlanCalculator::RiaWellPlanCalculator(const cvf::Vec3d& startTangent,
const std::vector<cvf::Vec3d>& lineArcEndPoints)
: m_startTangent(startTangent)
, m_lineArcEndPoints(lineArcEndPoints)
RiaWellPlanCalculator::RiaWellPlanCalculator( const cvf::Vec3d& startTangent,
const std::vector<cvf::Vec3d>& lineArcEndPoints )
: m_startTangent( startTangent )
, m_lineArcEndPoints( lineArcEndPoints )
{
if (m_lineArcEndPoints.size() < 2) return ;
if ( m_lineArcEndPoints.size() < 2 ) return;
WellPlanSegment segment = {0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0};
WellPlanSegment segment = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
RiaOffshoreSphericalCoords startAziIncRad(m_startTangent);
segment.inc = cvf::Math::toDegrees(startAziIncRad.inc());
segment.azi = cvf::Math::toDegrees(startAziIncRad.azi());
RiaOffshoreSphericalCoords startAziIncRad( m_startTangent );
segment.inc = cvf::Math::toDegrees( startAziIncRad.inc() );
segment.azi = cvf::Math::toDegrees( startAziIncRad.azi() );
segment.TVD = -lineArcEndPoints[0].z();
segment.NS = lineArcEndPoints[0].y();
segment.EW = lineArcEndPoints[0].x();
segment.NS = lineArcEndPoints[0].y();
segment.EW = lineArcEndPoints[0].x();
m_wpResult.push_back(segment);
m_wpResult.push_back( segment );
cvf::Vec3d p1 = m_lineArcEndPoints[0];
cvf::Vec3d p2 = m_lineArcEndPoints[1];
cvf::Vec3d t2 = m_startTangent;
cvf::Vec3d t2 = m_startTangent;
for (size_t pIdx = 0; pIdx < m_lineArcEndPoints.size() - 1 ; ++pIdx)
for ( size_t pIdx = 0; pIdx < m_lineArcEndPoints.size() - 1; ++pIdx )
{
addSegment(t2, m_lineArcEndPoints[pIdx], m_lineArcEndPoints[pIdx + 1] , &t2);
addSegment( t2, m_lineArcEndPoints[pIdx], m_lineArcEndPoints[pIdx + 1], &t2 );
}
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaWellPlanCalculator::addSegment(cvf::Vec3d t1, cvf::Vec3d p1, cvf::Vec3d p2, cvf::Vec3d* endTangent)
void RiaWellPlanCalculator::addSegment( cvf::Vec3d t1, cvf::Vec3d p1, cvf::Vec3d p2, cvf::Vec3d* endTangent )
{
cvf::Vec3d p1p2 = p2 - p1;
CVF_ASSERT (p1p2.lengthSquared() > 1e-20);
CVF_ASSERT( p1p2.lengthSquared() > 1e-20 );
if (cvf::GeometryTools::getAngle(t1, p1p2) < 1e-5)
if ( cvf::GeometryTools::getAngle( t1, p1p2 ) < 1e-5 )
{
addLineSegment(p1, p2, endTangent);
}
addLineSegment( p1, p2, endTangent );
}
else // resample arc
{
addArcSegment(t1, p1, p2, endTangent);
addArcSegment( t1, p1, p2, endTangent );
}
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaWellPlanCalculator::addLineSegment(cvf::Vec3d p1, cvf::Vec3d p2, cvf::Vec3d* endTangent)
void RiaWellPlanCalculator::addLineSegment( cvf::Vec3d p1, cvf::Vec3d p2, cvf::Vec3d* endTangent )
{
WellPlanSegment segment = {0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0};
WellPlanSegment segment = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
cvf::Vec3d p1p2 = p2 - p1;
double length = p1p2.length();
cvf::Vec3d p1p2 = p2 - p1;
double length = p1p2.length();
segment.CL = length;
segment.MD = m_wpResult.back().MD + length;
cvf::Vec3d tangent = p1p2 / length;
RiaOffshoreSphericalCoords aziIncRad(p1p2);
segment.inc = cvf::Math::toDegrees(aziIncRad.inc());
segment.azi = cvf::Math::toDegrees(aziIncRad.azi());
segment.TVD = -p2.z();
segment.NS = p2.y();
segment.EW = p2.x();
segment.dogleg = 0.0;
segment.build = 0.0;
segment.turn = 0.0;
RiaOffshoreSphericalCoords aziIncRad( p1p2 );
segment.inc = cvf::Math::toDegrees( aziIncRad.inc() );
segment.azi = cvf::Math::toDegrees( aziIncRad.azi() );
m_wpResult.push_back(segment);
segment.TVD = -p2.z();
segment.NS = p2.y();
segment.EW = p2.x();
segment.dogleg = 0.0;
segment.build = 0.0;
segment.turn = 0.0;
m_wpResult.push_back( segment );
*endTangent = tangent;
}
//--------------------------------------------------------------------------------------------------
///
///
//--------------------------------------------------------------------------------------------------
void RiaWellPlanCalculator::addArcSegment(cvf::Vec3d t1, cvf::Vec3d p1, cvf::Vec3d p2, cvf::Vec3d* endTangent)
void RiaWellPlanCalculator::addArcSegment( cvf::Vec3d t1, cvf::Vec3d p1, cvf::Vec3d p2, cvf::Vec3d* endTangent )
{
WellPlanSegment segment = {0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0};
WellPlanSegment segment = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};
RiaArcCurveCalculator arcCalc(p1, t1, p2);
RiaArcCurveCalculator arcCalc( p1, t1, p2 );
segment.CL = arcCalc.arcLength();
segment.MD = m_wpResult.back().MD + segment.CL;
segment.inc = cvf::Math::toDegrees(arcCalc.endInclination());
segment.azi = cvf::Math::toDegrees(arcCalc.endAzimuth());
segment.TVD = -p2.z();
segment.NS = p2.y();
segment.EW = p2.x();
segment.dogleg = cvf::Math::toDegrees(30.0/arcCalc.radius());
RiaOffshoreSphericalCoords startAziIncRad(t1);
double buildInRadsPrLength = (arcCalc.endInclination() - startAziIncRad.inc())/arcCalc.arcLength();
double turnInRadsPrLength = (arcCalc.endAzimuth() - startAziIncRad.azi())/arcCalc.arcLength();
segment.build = 30*cvf::Math::toDegrees(buildInRadsPrLength) ;
segment.turn = 30*cvf::Math::toDegrees(turnInRadsPrLength) ;
segment.CL = arcCalc.arcLength();
segment.MD = m_wpResult.back().MD + segment.CL;
segment.inc = cvf::Math::toDegrees( arcCalc.endInclination() );
segment.azi = cvf::Math::toDegrees( arcCalc.endAzimuth() );
segment.TVD = -p2.z();
segment.NS = p2.y();
segment.EW = p2.x();
segment.dogleg = cvf::Math::toDegrees( 30.0 / arcCalc.radius() );
RiaOffshoreSphericalCoords startAziIncRad( t1 );
double buildInRadsPrLength = ( arcCalc.endInclination() - startAziIncRad.inc() ) / arcCalc.arcLength();
double turnInRadsPrLength = ( arcCalc.endAzimuth() - startAziIncRad.azi() ) / arcCalc.arcLength();
segment.build = 30 * cvf::Math::toDegrees( buildInRadsPrLength );
segment.turn = 30 * cvf::Math::toDegrees( turnInRadsPrLength );
m_wpResult.push_back(segment);
m_wpResult.push_back( segment );
(*endTangent) = arcCalc.endTangent();
( *endTangent ) = arcCalc.endTangent();
}

View File

@@ -18,7 +18,6 @@
#pragma once
#include "cvfVector3.h"
#include <vector>
@@ -26,34 +25,34 @@
class RiaWellPlanCalculator
{
public:
RiaWellPlanCalculator(const cvf::Vec3d& startTangent,
const std::vector<cvf::Vec3d>& lineArcEndPoints);
RiaWellPlanCalculator( const cvf::Vec3d& startTangent, const std::vector<cvf::Vec3d>& lineArcEndPoints );
struct WellPlanSegment
{
double MD;
double CL;
double MD;
double CL;
double inc;
double azi;
double TVD;
double NS;
double EW;
double dogleg;
double build;
double TVD;
double NS;
double EW;
double dogleg;
double build;
double turn;
};
const std::vector<WellPlanSegment>& wellPlan() const { return m_wpResult; }
const std::vector<WellPlanSegment>& wellPlan() const
{
return m_wpResult;
}
private:
void addSegment(cvf::Vec3d t1, cvf::Vec3d p1, cvf::Vec3d p2, cvf::Vec3d* endTangent);
void addLineSegment(cvf::Vec3d p1, cvf::Vec3d p2, cvf::Vec3d* endTangent);
void addArcSegment(cvf::Vec3d t1, cvf::Vec3d p1, cvf::Vec3d p2, cvf::Vec3d* endTangent);
void addSegment( cvf::Vec3d t1, cvf::Vec3d p1, cvf::Vec3d p2, cvf::Vec3d* endTangent );
void addLineSegment( cvf::Vec3d p1, cvf::Vec3d p2, cvf::Vec3d* endTangent );
void addArcSegment( cvf::Vec3d t1, cvf::Vec3d p1, cvf::Vec3d p2, cvf::Vec3d* endTangent );
cvf::Vec3d m_startTangent;
std::vector<cvf::Vec3d> m_lineArcEndPoints;
cvf::Vec3d m_startTangent;
std::vector<cvf::Vec3d> m_lineArcEndPoints;
std::vector<WellPlanSegment> m_wpResult;
};