diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000000..75e127a2a7 --- /dev/null +++ b/.clang-format @@ -0,0 +1,59 @@ +AccessModifierOffset: '-4' +AlignOperands: 'AlignAfterOperator' +BreakBeforeBinaryOperators: None +AlignTrailingComments: 'true' +AllowAllArgumentsOnNextLine: 'true' +AllowAllParametersOfDeclarationOnNextLine: 'false' +AllowShortBlocksOnASingleLine: 'Empty' +AllowShortCaseLabelsOnASingleLine: 'false' +AllowShortEnumsOnASingleLine: 'false' +AllowShortFunctionsOnASingleLine: 'false' +AllowShortIfStatementsOnASingleLine: 'Never' +AllowShortLoopsOnASingleLine: 'false' +AlwaysBreakAfterReturnType: 'None' +BinPackArguments: 'false' +BinPackParameters: 'false' +BreakConstructorInitializers: BeforeComma +BreakInheritanceList: BeforeComma +BreakBeforeBraces: Custom +BraceWrapping: + AfterCaseLabel: 'true' + AfterClass: 'true' + AfterControlStatement: 'true' + AfterEnum: 'false' + AfterFunction: 'true' + AfterStruct: 'true' + BeforeCatch: 'true' + BeforeElse: 'true' + BeforeWhile: 'true' +BreakInheritanceList: 'BeforeComma' +ColumnLimit: '100' +CompactNamespaces: 'false' +ConstructorInitializerAllOnOneLineOrOnePerLine: 'false' +ConstructorInitializerIndentWidth: '4' +EmptyLineBeforeAccessModifier: 'Always' +FixNamespaceComments: 'true' +IncludeBlocks: Regroup +IndentCaseLabels: 'false' +IndentWidth: '4' +KeepEmptyLinesAtTheStartOfBlocks: 'false' +Language: Cpp +PointerAlignment: Right +ReflowComments: 'true' +PenaltyBreakComment: '20' +SortIncludes: 'true' +SortUsingDeclarations: 'true' +SpaceAfterLogicalNot: 'false' +SpaceBeforeAssignmentOperators: 'true' +SpaceBeforeParens: ControlStatements +SpaceBeforeRangeBasedForLoopColon: 'true' +SpaceInEmptyParentheses: 'false' +SpacesInContainerLiterals: 'false' +SpacesInParentheses: 'true' +SpacesInSquareBrackets: 'false' +SpacesInCStyleCastParentheses: 'false' +Standard: Cpp11 +TabWidth: '4' +UseTab: Never +Cpp11BracedListStyle: 'false' +MaxEmptyLinesToKeep: 2 \ No newline at end of file diff --git a/src/basis_factorization/BasisFactorizationError.h b/src/basis_factorization/BasisFactorizationError.h index 71ca77465d..68de4cc40b 100644 --- a/src/basis_factorization/BasisFactorizationError.h +++ b/src/basis_factorization/BasisFactorizationError.h @@ -22,7 +22,7 @@ class BasisFactorizationError : public Error { public: - enum Code { + enum Code { ALLOCATION_FAILED = 0, CANT_INVERT_BASIS_BECAUSE_OF_ETAS = 1, UNKNOWN_BASIS_FACTORIZATION_TYPE = 2, @@ -32,13 +32,13 @@ class BasisFactorizationError : public Error FEATURE_NOT_YET_SUPPORTED = 6, }; - BasisFactorizationError( BasisFactorizationError::Code code ) : - Error( "BasisFactorizationError", (int)code ) - { - } + BasisFactorizationError( BasisFactorizationError::Code code ) + : Error( "BasisFactorizationError", (int)code ) + { + } - BasisFactorizationError( BasisFactorizationError::Code code, const char *userMessage ) : - Error( "BasisFactorizationError", (int)code, userMessage ) + BasisFactorizationError( BasisFactorizationError::Code code, const char *userMessage ) + : Error( "BasisFactorizationError", (int)code, userMessage ) { } }; diff --git a/src/basis_factorization/BasisFactorizationFactory.cpp b/src/basis_factorization/BasisFactorizationFactory.cpp index 8eb822bf18..4fa96167b5 100644 --- a/src/basis_factorization/BasisFactorizationFactory.cpp +++ b/src/basis_factorization/BasisFactorizationFactory.cpp @@ -13,19 +13,21 @@ **/ -#include "BasisFactorizationError.h" #include "BasisFactorizationFactory.h" + +#include "BasisFactorizationError.h" #include "ForrestTomlinFactorization.h" #include "GlobalConfiguration.h" #include "LUFactorization.h" #include "SparseFTFactorization.h" #include "SparseLUFactorization.h" -IBasisFactorization *BasisFactorizationFactory::createBasisFactorization( unsigned basisSize, const IBasisFactorization::BasisColumnOracle &basisColumnOracle ) +IBasisFactorization *BasisFactorizationFactory::createBasisFactorization( + unsigned basisSize, + const IBasisFactorization::BasisColumnOracle &basisColumnOracle ) { // LU - if ( GlobalConfiguration::BASIS_FACTORIZATION_TYPE == - GlobalConfiguration::LU_FACTORIZATION ) + if ( GlobalConfiguration::BASIS_FACTORIZATION_TYPE == GlobalConfiguration::LU_FACTORIZATION ) return new LUFactorization( basisSize, basisColumnOracle ); // Sparse LU diff --git a/src/basis_factorization/BasisFactorizationFactory.h b/src/basis_factorization/BasisFactorizationFactory.h index 92fa28752d..6e9903887c 100644 --- a/src/basis_factorization/BasisFactorizationFactory.h +++ b/src/basis_factorization/BasisFactorizationFactory.h @@ -21,7 +21,9 @@ class BasisFactorizationFactory { public: - static IBasisFactorization *createBasisFactorization( unsigned basisSize, const IBasisFactorization::BasisColumnOracle &basisColumnOracle ); + static IBasisFactorization * + createBasisFactorization( unsigned basisSize, + const IBasisFactorization::BasisColumnOracle &basisColumnOracle ); }; #endif // __BasisFactorizationFactory_h__ diff --git a/src/basis_factorization/CSRMatrix.cpp b/src/basis_factorization/CSRMatrix.cpp index 1ff6c7c385..e168c3a2b4 100644 --- a/src/basis_factorization/CSRMatrix.cpp +++ b/src/basis_factorization/CSRMatrix.cpp @@ -13,8 +13,9 @@ **/ -#include "BasisFactorizationError.h" #include "CSRMatrix.h" + +#include "BasisFactorizationError.h" #include "Debug.h" #include "FloatUtils.h" #include "MString.h" @@ -61,13 +62,13 @@ void CSRMatrix::initialize( const double *M, unsigned m, unsigned n ) for ( unsigned j = 0; j < _n; ++j ) { // Ignore zero entries - if ( FloatUtils::isZero( M[i*_n + j] ) ) + if ( FloatUtils::isZero( M[i * _n + j] ) ) continue; if ( _nnz >= _estimatedNnz ) increaseCapacity(); - _A[_nnz] = M[i*_n + j]; + _A[_nnz] = M[i * _n + j]; ++_IA[i + 1]; _JA[_nnz] = j; @@ -92,11 +93,13 @@ void CSRMatrix::initializeToEmpty( unsigned m, unsigned n ) _IA = new unsigned[_m + 1]; if ( !_IA ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "CSRMatrix::IA" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "CSRMatrix::IA" ); _JA = new unsigned[_estimatedNnz]; if ( !_JA ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "CSRMatrix::JA" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "CSRMatrix::JA" ); std::fill_n( _IA, _m + 1, 0.0 ); _nnz = 0; @@ -109,14 +112,16 @@ void CSRMatrix::increaseCapacity() double *newA = new double[newEstimatedNnz]; if ( !newA ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "CSRMatrix::newA" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "CSRMatrix::newA" ); unsigned *newJA = new unsigned[newEstimatedNnz]; if ( !newJA ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "CSRMatrix::newJA" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "CSRMatrix::newJA" ); - memcpy( newA, _A, _estimatedNnz * sizeof(double) ); - memcpy( newJA, _JA, _estimatedNnz * sizeof(unsigned) ); + memcpy( newA, _A, _estimatedNnz * sizeof( double ) ); + memcpy( newJA, _JA, _estimatedNnz * sizeof( unsigned ) ); delete[] _A; delete[] _JA; @@ -138,7 +143,7 @@ void CSRMatrix::addLastRow( const double *row ) { // Array _IA needs to increase by one unsigned *newIA = new unsigned[_m + 2]; - memcpy( newIA, _IA, sizeof(unsigned) * ( _m + 1 ) ); + memcpy( newIA, _IA, sizeof( unsigned ) * ( _m + 1 ) ); delete[] _IA; _IA = newIA; @@ -188,7 +193,7 @@ void CSRMatrix::addLastColumn( const double *column ) continue; // Ignore all rows greater than i - while ( arrayIndex > _IA[i+1] - 1 ) + while ( arrayIndex > _IA[i + 1] - 1 ) { _A[arrayIndex + offset] = _A[arrayIndex]; _JA[arrayIndex + offset] = _JA[arrayIndex]; @@ -207,7 +212,7 @@ void CSRMatrix::addLastColumn( const double *column ) { if ( !FloatUtils::isZero( column[i] ) ) ++increase; - _IA[i+1] += increase; + _IA[i + 1] += increase; } ++_n; @@ -248,18 +253,21 @@ void CSRMatrix::storeIntoOther( SparseMatrix *other ) const otherCsr->_A = new double[_estimatedNnz]; if ( !otherCsr->_A ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "CSRMatrix::otherCsrA" ); - memcpy( otherCsr->_A, _A, sizeof(double) * _estimatedNnz ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "CSRMatrix::otherCsrA" ); + memcpy( otherCsr->_A, _A, sizeof( double ) * _estimatedNnz ); otherCsr->_IA = new unsigned[_m + 1]; if ( !otherCsr->_IA ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "CSRMatrix::otherCsrIA" ); - memcpy( otherCsr->_IA, _IA, sizeof(unsigned) * ( _m + 1 ) ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "CSRMatrix::otherCsrIA" ); + memcpy( otherCsr->_IA, _IA, sizeof( unsigned ) * ( _m + 1 ) ); otherCsr->_JA = new unsigned[_estimatedNnz]; if ( !otherCsr->_JA ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "CSRMatrix::otherCsrJA" ); - memcpy( otherCsr->_JA, _JA, sizeof(unsigned) * _estimatedNnz ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "CSRMatrix::otherCsrJA" ); + memcpy( otherCsr->_JA, _JA, sizeof( unsigned ) * _estimatedNnz ); } void CSRMatrix::getRow( unsigned row, SparseUnsortedList *result ) const @@ -449,7 +457,7 @@ void CSRMatrix::insertElements( const Map> &inser Elements of row i are stored in _A and _JA between indices _IA[i] and _IA[i+1] - 1. */ - int j = _IA[i+1] - 1; + int j = _IA[i + 1] - 1; while ( j >= (int)_IA[i] ) { if ( !rowHasInsertions || nextInsertion == insertions[i].rend() ) @@ -496,7 +504,6 @@ void CSRMatrix::insertElements( const Map> &inser --newArrayIndex; } } - } // Make a final pass to adjust the IA indices @@ -504,7 +511,7 @@ void CSRMatrix::insertElements( const Map> &inser for ( unsigned i = 0; i < _m; ++i ) { totalAddedSoFar += insertions.exists( i ) ? insertions[i].size() : 0; - _IA[i+1] += totalAddedSoFar; + _IA[i + 1] += totalAddedSoFar; } _nnz += totalAddedSoFar; @@ -633,7 +640,7 @@ void CSRMatrix::executeChanges() void CSRMatrix::countElements( unsigned *numRowElements, unsigned *numColumnElements ) { for ( unsigned i = 0; i < _m; ++i ) - numRowElements[i] = _IA[i+1] - _IA[i]; + numRowElements[i] = _IA[i + 1] - _IA[i]; std::fill_n( numColumnElements, _n, 0 ); for ( unsigned i = 0; i < _nnz; ++i ) @@ -706,7 +713,6 @@ void CSRMatrix::dump() const for ( unsigned i = 0; i < _m + 1; ++i ) printf( "%5u ", _IA[i] ); printf( "\n" ); - } void CSRMatrix::dumpDense() const @@ -718,7 +724,7 @@ void CSRMatrix::dumpDense() const { for ( unsigned j = 0; j < _n; ++j ) { - printf( "%5.2lf ", work[i*_n + j] ); + printf( "%5.2lf ", work[i * _n + j] ); } printf( "\n" ); } @@ -745,11 +751,11 @@ void CSRMatrix::checkInvariants() const for ( unsigned i = 0; i < _m; ++i ) { unsigned start = _IA[i]; - unsigned end = _IA[i+1]; + unsigned end = _IA[i + 1]; for ( unsigned j = start; j + 1 < end; ++j ) { - if ( _JA[j] >= _JA[j+1] ) + if ( _JA[j] >= _JA[j + 1] ) { printf( "CSRMatrix error! _JA elements not increasing. " "Dumping and terminating\n" ); @@ -764,7 +770,7 @@ void CSRMatrix::clear() { _nnz = 0; for ( unsigned i = 0; i < _m; ++i ) - _IA[i+1] = 0; + _IA[i + 1] = 0; } const double *CSRMatrix::getA() const diff --git a/src/basis_factorization/EtaMatrix.cpp b/src/basis_factorization/EtaMatrix.cpp index 52c6ea9008..6e073a9af7 100644 --- a/src/basis_factorization/EtaMatrix.cpp +++ b/src/basis_factorization/EtaMatrix.cpp @@ -13,8 +13,9 @@ **/ -#include "BasisFactorizationError.h" #include "EtaMatrix.h" + +#include "BasisFactorizationError.h" #include "FloatUtils.h" #include @@ -28,9 +29,10 @@ EtaMatrix::EtaMatrix( unsigned m, unsigned index, const double *column ) { _column = new double[_m]; if ( !_column ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "EtaMatrix::column" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "EtaMatrix::column" ); - memcpy( _column, column, sizeof(double) * _m ); + memcpy( _column, column, sizeof( double ) * _m ); } EtaMatrix::EtaMatrix( unsigned m, unsigned index ) @@ -40,7 +42,8 @@ EtaMatrix::EtaMatrix( unsigned m, unsigned index ) { _column = new double[_m]; if ( !_column ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "EtaMatrix::column" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "EtaMatrix::column" ); std::fill( _column, _column + _m, 0.0 ); @@ -54,9 +57,10 @@ EtaMatrix::EtaMatrix( const EtaMatrix &other ) { _column = new double[_m]; if ( !_column ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "EtaMatrix::column" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "EtaMatrix::column" ); - memcpy( _column, other._column, sizeof(double) * _m ); + memcpy( _column, other._column, sizeof( double ) * _m ); } EtaMatrix &EtaMatrix::operator=( const EtaMatrix &other ) @@ -72,9 +76,10 @@ EtaMatrix &EtaMatrix::operator=( const EtaMatrix &other ) _column = new double[_m]; if ( !_column ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "EtaMatrix::column" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "EtaMatrix::column" ); - memcpy( _column, other._column, sizeof(double) * _m ); + memcpy( _column, other._column, sizeof( double ) * _m ); return *this; } @@ -101,11 +106,11 @@ void EtaMatrix::dump() const void EtaMatrix::toMatrix( double *A ) const { std::fill_n( A, _m * _m, 0.0 ); - for ( unsigned i = 0; i < _m; ++i ) + for ( unsigned i = 0; i < _m; ++i ) { - A[i * _m + i] = 1.; - A[_columnIndex + i * _m] = _column[i]; - } + A[i * _m + i] = 1.; + A[_columnIndex + i * _m] = _column[i]; + } } bool EtaMatrix::operator==( const EtaMatrix &other ) const diff --git a/src/basis_factorization/EtaMatrix.h b/src/basis_factorization/EtaMatrix.h index 090cf15b16..54a370e70a 100644 --- a/src/basis_factorization/EtaMatrix.h +++ b/src/basis_factorization/EtaMatrix.h @@ -31,7 +31,7 @@ class EtaMatrix ~EtaMatrix(); void dump() const; - void toMatrix( double *A ) const; + void toMatrix( double *A ) const; void resetToIdentity(); diff --git a/src/basis_factorization/ForrestTomlinFactorization.cpp b/src/basis_factorization/ForrestTomlinFactorization.cpp index 6b66f032d7..615165ebcb 100644 --- a/src/basis_factorization/ForrestTomlinFactorization.cpp +++ b/src/basis_factorization/ForrestTomlinFactorization.cpp @@ -13,15 +13,18 @@ **/ +#include "ForrestTomlinFactorization.h" + #include "BasisFactorizationError.h" #include "EtaMatrix.h" #include "FloatUtils.h" -#include "ForrestTomlinFactorization.h" #include "MalformedBasisException.h" + #include #include -ForrestTomlinFactorization::ForrestTomlinFactorization( unsigned m, const BasisColumnOracle &basisColumnOracle ) +ForrestTomlinFactorization::ForrestTomlinFactorization( unsigned m, + const BasisColumnOracle &basisColumnOracle ) : IBasisFactorization( basisColumnOracle ) , _m( m ) , _B( NULL ) @@ -84,14 +87,14 @@ ForrestTomlinFactorization::ForrestTomlinFactorization( unsigned m, const BasisC ForrestTomlinFactorization::~ForrestTomlinFactorization() { - if ( _B ) - { - delete[] _B; - _B = NULL; - } - - if ( _U ) - { + if ( _B ) + { + delete[] _B; + _B = NULL; + } + + if ( _U ) + { for ( unsigned i = 0; i < _m; ++i ) { if ( _U[i] ) @@ -101,15 +104,15 @@ ForrestTomlinFactorization::~ForrestTomlinFactorization() } } - delete[] _U; - _U = NULL; - } + delete[] _U; + _U = NULL; + } if ( _workMatrix ) - { - delete[] _workMatrix; - _workMatrix = NULL; - } + { + delete[] _workMatrix; + _workMatrix = NULL; + } if ( _workVector ) { @@ -142,7 +145,7 @@ ForrestTomlinFactorization::~ForrestTomlinFactorization() void ForrestTomlinFactorization::updateToAdjacentBasis( unsigned columnIndex, const double *changeColumn, - const double */* newColumn */ ) + const double * /* newColumn */ ) { // Pushing an eta matrix invalidates the explicit basis _explicitBasisAvailable = false; @@ -179,7 +182,7 @@ void ForrestTomlinFactorization::updateToAdjacentBasis( unsigned columnIndex, _workVector[j] += ( _workVector[_U[i]->_columnIndex] * _U[i]->_column[j] ); } - memcpy( _U[indexOfChangedUColumn]->_column, _workVector, sizeof(double) * _m ); + memcpy( _U[indexOfChangedUColumn]->_column, _workVector, sizeof( double ) * _m ); /* Now we have workQ * V * invWorkQ that is upper triangular except the last row. @@ -208,8 +211,8 @@ void ForrestTomlinFactorization::updateToAdjacentBasis( unsigned columnIndex, To find this entry we go through the permutations. */ - bumpValue += a->_value * - _U[_workQ._rowOrdering[i]]->_column[_workQ._rowOrdering[a->_column]]; + bumpValue += + a->_value * _U[_workQ._rowOrdering[i]]->_column[_workQ._rowOrdering[a->_column]]; } // If the bump value is zero, nothing needs to be done @@ -218,7 +221,7 @@ void ForrestTomlinFactorization::updateToAdjacentBasis( unsigned columnIndex, // If the bump value is 1 and this is the diagonal entry // already, nothing needs to be done - if ( FloatUtils::areEqual( bumpValue, 1 ) && ( i == _m - 1 ) ) + if ( FloatUtils::areEqual( bumpValue, 1 ) && ( i == _m - 1 ) ) continue; // Now we want to zero out the bump value using an A matrix. @@ -231,7 +234,7 @@ void ForrestTomlinFactorization::updateToAdjacentBasis( unsigned columnIndex, { double diagonalValue = _U[_workQ._rowOrdering[i]]->_column[_workQ._rowOrdering[i]]; ASSERT( !FloatUtils::isZero( diagonalValue ) ); - newA->_value = - bumpValue / diagonalValue; + newA->_value = -bumpValue / diagonalValue; } else { @@ -324,26 +327,26 @@ void ForrestTomlinFactorization::forwardTransformation( const double *y, double Step 1: Find w such that: w = inv(Q) * Ak...A1 * LsPs...L1P1 * y ****/ - memcpy( _workVector, y, sizeof(double) * _m ); + memcpy( _workVector, y, sizeof( double ) * _m ); // Multiply y by Ps and Ls for ( auto lp = _LP.rbegin(); lp != _LP.rend(); ++lp ) { - if ( (*lp)->_pair ) + if ( ( *lp )->_pair ) { - double temp = _workVector[(*lp)->_pair->first]; - _workVector[(*lp)->_pair->first] = _workVector[(*lp)->_pair->second]; - _workVector[(*lp)->_pair->second] = temp; - } + double temp = _workVector[( *lp )->_pair->first]; + _workVector[( *lp )->_pair->first] = _workVector[( *lp )->_pair->second]; + _workVector[( *lp )->_pair->second] = temp; + } else { - unsigned col = (*lp)->_eta->_columnIndex; + unsigned col = ( *lp )->_eta->_columnIndex; double diagonalEntry = _workVector[col]; - _workVector[col] *= (*lp)->_eta->_column[col]; + _workVector[col] *= ( *lp )->_eta->_column[col]; for ( unsigned i = col + 1; i < _m; ++i ) { - _workVector[i] += diagonalEntry * (*lp)->_eta->_column[i]; + _workVector[i] += diagonalEntry * ( *lp )->_eta->_column[i]; if ( FloatUtils::isZero( _workVector[i] ) ) _workVector[i] = 0.0; @@ -456,14 +459,14 @@ void ForrestTomlinFactorization::backwardTransformation( const double *y, double // Mutiply by the As for ( auto a = _A.rbegin(); a != _A.rend(); ++a ) { - columnIndex = (*a)->_column; - if ( columnIndex == (*a)->_row ) + columnIndex = ( *a )->_column; + if ( columnIndex == ( *a )->_row ) { - x[columnIndex] *= (*a)->_value; + x[columnIndex] *= ( *a )->_value; } else { - x[columnIndex] += ( (*a)->_value * x[(*a)->_row] ); + x[columnIndex] += ( ( *a )->_value * x[( *a )->_row] ); if ( FloatUtils::isZero( x[columnIndex] ) ) x[columnIndex] = 0.0; } @@ -474,10 +477,10 @@ void ForrestTomlinFactorization::backwardTransformation( const double *y, double { if ( lp->_pair ) { - double temp = x[lp->_pair->first]; - x[lp->_pair->first] = x[lp->_pair->second]; - x[lp->_pair->second] = temp; - } + double temp = x[lp->_pair->first]; + x[lp->_pair->first] = x[lp->_pair->second]; + x[lp->_pair->second] = temp; + } else { columnIndex = lp->_eta->_columnIndex; @@ -509,13 +512,14 @@ void ForrestTomlinFactorization::storeFactorization( IBasisFactorization *other otherFTFactorization->_explicitBasisAvailable = _explicitBasisAvailable; // Copy the basis matrix and its factorization - memcpy( otherFTFactorization->_B, _B, sizeof(double) * _m * _m ); + memcpy( otherFTFactorization->_B, _B, sizeof( double ) * _m * _m ); for ( unsigned i = 0; i < _m; ++i ) - *(otherFTFactorization->_U[i]) = *_U[i]; + *( otherFTFactorization->_U[i] ) = *_U[i]; List::iterator lpIt; - for ( lpIt = otherFTFactorization->_LP.begin(); lpIt != otherFTFactorization->_LP.end(); ++lpIt ) + for ( lpIt = otherFTFactorization->_LP.begin(); lpIt != otherFTFactorization->_LP.end(); + ++lpIt ) delete *lpIt; otherFTFactorization->_LP.clear(); @@ -546,10 +550,10 @@ void ForrestTomlinFactorization::restoreFactorization( const IBasisFactorization _explicitBasisAvailable = otherFTFactorization->_explicitBasisAvailable; // Copy the basis matrix and its factorization - memcpy( _B, otherFTFactorization->_B, sizeof(double) * _m * _m ); + memcpy( _B, otherFTFactorization->_B, sizeof( double ) * _m * _m ); for ( unsigned i = 0; i < _m; ++i ) - *_U[i] = *(otherFTFactorization->_U[i]); + *_U[i] = *( otherFTFactorization->_U[i] ); List::iterator lpIt; for ( lpIt = _LP.begin(); lpIt != _LP.end(); ++lpIt ) @@ -593,10 +597,10 @@ void ForrestTomlinFactorization::initialLUFactorization() clearFactorization(); // Copy the new matrix to the work memory - memcpy( _workMatrix, _B, sizeof(double) * _m * _m ); + memcpy( _workMatrix, _B, sizeof( double ) * _m * _m ); // Perform Gaussian eliminiation to obtain the LP matrices - for ( unsigned i = 0; i < _m; ++i ) + for ( unsigned i = 0; i < _m; ++i ) { // Begin work for the i'th column. // Employ partial pivoting: find the row with the largest element and swap it to position i @@ -631,7 +635,7 @@ void ForrestTomlinFactorization::initialLUFactorization() std::fill_n( _workVector, _m, 0 ); double div = _workMatrix[i * _m + i]; _workVector[i] = 1 / div; - for ( unsigned j = i + 1; j < _m; ++j ) + for ( unsigned j = i + 1; j < _m; ++j ) _workVector[j] = -_workMatrix[i + j * _m] / div; // Store the resulting lower-triangular eta matrix @@ -655,7 +659,7 @@ void ForrestTomlinFactorization::initialLUFactorization() _workMatrix[i * _m + j] *= L->_column[i]; _workMatrix[i * _m + i] = 1.0; - } + } // Extract the U matrices for ( unsigned i = 1; i < _m; ++i ) @@ -698,7 +702,8 @@ const SparseMatrix *ForrestTomlinFactorization::getSparseBasis() const void ForrestTomlinFactorization::invertBasis( double *result ) { if ( !_explicitBasisAvailable ) - throw BasisFactorizationError( BasisFactorizationError::CANT_INVERT_BASIS_BECAUSE_BASIS_ISNT_AVAILABLE ); + throw BasisFactorizationError( + BasisFactorizationError::CANT_INVERT_BASIS_BECAUSE_BASIS_ISNT_AVAILABLE ); /* We have a simple LU factorization of the basis, and we can use @@ -714,12 +719,12 @@ void ForrestTomlinFactorization::invertBasis( double *result ) if ( _LP.empty() ) { - DEBUG({ - // Assert B is the identity matrix. - for ( unsigned i = 0; i < _m; ++i ) - for ( unsigned j = 0; j < _m; ++j ) - ASSERT( _B[i * _m + j] == ( i == j ) ? 1.0 : 0.0 ); - }); + DEBUG( { + // Assert B is the identity matrix. + for ( unsigned i = 0; i < _m; ++i ) + for ( unsigned j = 0; j < _m; ++j ) + ASSERT( _B[i * _m + j] == ( i == j ) ? 1.0 : 0.0 ); + } ); return; } @@ -741,7 +746,8 @@ void ForrestTomlinFactorization::invertBasis( double *result ) for ( unsigned row = colIndex + 1; row < _m; ++row ) { for ( unsigned col = 0; col < _m; ++col ) - result[row * _m + col] += element->_eta->_column[row] * result[colIndex * _m + col]; + result[row * _m + col] += + element->_eta->_column[row] * result[colIndex * _m + col]; } // Finally, perform the multiplication for the pivot row @@ -794,9 +800,9 @@ const List *ForrestTomlinFactorization::getA() const void ForrestTomlinFactorization::rowSwap( unsigned rowOne, unsigned rowTwo, double *matrix ) { - memcpy( _workVector, matrix + (rowOne * _m), sizeof(double) * _m ); - memcpy( matrix + (rowOne * _m), matrix + (rowTwo * _m), sizeof(double) * _m ); - memcpy( matrix + (rowTwo * _m), _workVector, sizeof(double) * _m ); + memcpy( _workVector, matrix + ( rowOne * _m ), sizeof( double ) * _m ); + memcpy( matrix + ( rowOne * _m ), matrix + ( rowTwo * _m ), sizeof( double ) * _m ); + memcpy( matrix + ( rowTwo * _m ), _workVector, sizeof( double ) * _m ); } void ForrestTomlinFactorization::pushA( const AlmostIdentityMatrix &matrix ) diff --git a/src/basis_factorization/ForrestTomlinFactorization.h b/src/basis_factorization/ForrestTomlinFactorization.h index 77d6446f78..ec1f951941 100644 --- a/src/basis_factorization/ForrestTomlinFactorization.h +++ b/src/basis_factorization/ForrestTomlinFactorization.h @@ -52,7 +52,7 @@ class ForrestTomlinFactorization : public IBasisFactorization */ void updateToAdjacentBasis( unsigned columnIndex, const double *changeColumn, - const double */* newColumn */ ); + const double * /* newColumn */ ); /* Perform a forward transformation, i.e. find x such that Bx = y. @@ -72,7 +72,7 @@ class ForrestTomlinFactorization : public IBasisFactorization void storeFactorization( IBasisFactorization *other ); void restoreFactorization( const IBasisFactorization *other ); - /* + /* Ask the basis factorization to obtain a fresh basis (through the previously-provided oracle). */ @@ -121,7 +121,7 @@ class ForrestTomlinFactorization : public IBasisFactorization /* The current basis matrix B */ - double *_B; + double *_B; /* The components of the Forrest-Tomlin factorization. @@ -132,7 +132,7 @@ class ForrestTomlinFactorization : public IBasisFactorization // P1 is the last element of the list List _LP; // A1 is the first element of the list - List_A; + List _A; /* Indicates whether the explicit basis matrix is available. @@ -155,7 +155,7 @@ class ForrestTomlinFactorization : public IBasisFactorization void clearFactorization(); void initialLUFactorization(); - /* + /* Swap two rows of a matrix. */ void rowSwap( unsigned rowOne, unsigned rowTwo, double *matrix ); diff --git a/src/basis_factorization/GaussianEliminator.cpp b/src/basis_factorization/GaussianEliminator.cpp index 7869eb5486..d4a5a81f33 100644 --- a/src/basis_factorization/GaussianEliminator.cpp +++ b/src/basis_factorization/GaussianEliminator.cpp @@ -13,11 +13,12 @@ **/ +#include "GaussianEliminator.h" + #include "BasisFactorizationError.h" #include "Debug.h" #include "EtaMatrix.h" #include "FloatUtils.h" -#include "GaussianEliminator.h" #include "GlobalConfiguration.h" #include "MStringf.h" #include "MalformedBasisException.h" @@ -67,10 +68,10 @@ void GaussianEliminator::initializeFactorization( const double *A, LUFactors *lu V = U = A F = L = I */ - memcpy( _luFactors->_V, A, sizeof(double) * _m * _m ); + memcpy( _luFactors->_V, A, sizeof( double ) * _m * _m ); std::fill_n( _luFactors->_F, _m * _m, 0 ); for ( unsigned i = 0; i < _m; ++i ) - _luFactors->_F[i*_m +i] = 1; + _luFactors->_F[i * _m + i] = 1; _luFactors->_P.resetToIdentity(); _luFactors->_Q.resetToIdentity(); @@ -82,7 +83,7 @@ void GaussianEliminator::initializeFactorization( const double *A, LUFactors *lu { for ( unsigned j = 0; j < _m; ++j ) { - if ( !FloatUtils::isZero( A[i*_m + j] ) ) + if ( !FloatUtils::isZero( A[i * _m + j] ) ) { ++_numURowElements[i]; ++_numUColumnElements[j]; @@ -95,8 +96,8 @@ void GaussianEliminator::permute() { /* The element selected for pivoting is U[p,q], - We want to update P and Q to move u[p,q] to position [k,k] in U (= P'VQ'), where k is the current - eliminiation step. + We want to update P and Q to move u[p,q] to position [k,k] in U (= P'VQ'), where k is the + current eliminiation step. */ _luFactors->_P.swapColumns( _uPivotRow, _eliminationStep ); @@ -198,7 +199,7 @@ void GaussianEliminator::choosePivot() for ( unsigned j = _eliminationStep; j < _m; ++j ) { unsigned vCol = _luFactors->_Q._rowOrdering[j]; - if ( !FloatUtils::isZero( _luFactors->_V[_vPivotRow*_m + vCol] ) ) + if ( !FloatUtils::isZero( _luFactors->_V[_vPivotRow * _m + vCol] ) ) { _vPivotColumn = vCol; _uPivotColumn = j; @@ -211,9 +212,10 @@ void GaussianEliminator::choosePivot() ASSERT( found ); GAUSSIAN_LOG( Stringf( "Choose pivot selected a pivot (singleton row): V[%u,%u] = %lf", - _vPivotRow, - _vPivotColumn, - _luFactors->_V[_vPivotRow*_m + _vPivotColumn] ).ascii() ); + _vPivotRow, + _vPivotColumn, + _luFactors->_V[_vPivotRow * _m + _vPivotColumn] ) + .ascii() ); return; } @@ -231,7 +233,7 @@ void GaussianEliminator::choosePivot() for ( unsigned j = _eliminationStep; j < _m; ++j ) { unsigned vRow = _luFactors->_P._columnOrdering[j]; - if ( !FloatUtils::isZero( _luFactors->_V[vRow*_m + _vPivotColumn] ) ) + if ( !FloatUtils::isZero( _luFactors->_V[vRow * _m + _vPivotColumn] ) ) { _vPivotRow = vRow; _uPivotRow = j; @@ -243,10 +245,12 @@ void GaussianEliminator::choosePivot() ASSERT( found ); - GAUSSIAN_LOG( Stringf( "Choose pivot selected a pivot (singleton column): V[%u,%u] = %lf", - _vPivotRow, - _vPivotColumn, - _luFactors->_V[_vPivotRow*_m + _vPivotColumn] ).ascii() ); + GAUSSIAN_LOG( + Stringf( "Choose pivot selected a pivot (singleton column): V[%u,%u] = %lf", + _vPivotRow, + _vPivotColumn, + _luFactors->_V[_vPivotRow * _m + _vPivotColumn] ) + .ascii() ); return; } } @@ -266,7 +270,7 @@ void GaussianEliminator::choosePivot() { unsigned vRow = _luFactors->_P._columnOrdering[row]; unsigned vColumn = _luFactors->_Q._rowOrdering[column]; - double contender = FloatUtils::abs( _luFactors->_V[vRow*_m + vColumn] ); + double contender = FloatUtils::abs( _luFactors->_V[vRow * _m + vColumn] ); if ( FloatUtils::gt( contender, maxInColumn ) ) maxInColumn = contender; @@ -277,7 +281,6 @@ void GaussianEliminator::choosePivot() if ( !found ) throw BasisFactorizationError( BasisFactorizationError::GAUSSIAN_ELIMINATION_FAILED, "Have a zero column" ); - } // Now scan the column for candidates @@ -285,11 +288,13 @@ void GaussianEliminator::choosePivot() { unsigned vRow = _luFactors->_P._columnOrdering[row]; unsigned vColumn = _luFactors->_Q._rowOrdering[column]; - double contender = FloatUtils::abs( _luFactors->_V[vRow*_m + vColumn] ); + double contender = FloatUtils::abs( _luFactors->_V[vRow * _m + vColumn] ); // Only consider large-enough elements - if ( FloatUtils::gt( contender, - maxInColumn * GlobalConfiguration::GAUSSIAN_ELIMINATION_PIVOT_SCALE_THRESHOLD ) ) + if ( FloatUtils::gt( + contender, + maxInColumn * + GlobalConfiguration::GAUSSIAN_ELIMINATION_PIVOT_SCALE_THRESHOLD ) ) { unsigned cost = ( _numURowElements[row] - 1 ) * ( _numUColumnElements[column] - 1 ); @@ -310,7 +315,12 @@ void GaussianEliminator::choosePivot() } } - GAUSSIAN_LOG( Stringf( "Choose pivot selected a pivot: V[%u,%u] = %lf (cost %u)", _vPivotRow, _vPivotColumn, _luFactors->_V[_vPivotRow*_m + _vPivotColumn], minimalCost ).ascii() ); + GAUSSIAN_LOG( Stringf( "Choose pivot selected a pivot: V[%u,%u] = %lf (cost %u)", + _vPivotRow, + _vPivotColumn, + _luFactors->_V[_vPivotRow * _m + _vPivotColumn], + minimalCost ) + .ascii() ); if ( !found ) throw BasisFactorizationError( BasisFactorizationError::GAUSSIAN_ELIMINATION_FAILED, @@ -329,7 +339,7 @@ void GaussianEliminator::eliminate() for ( unsigned uColumn = _eliminationStep; uColumn < _m; ++uColumn ) { unsigned vColumn = _luFactors->_Q._rowOrdering[uColumn]; - if ( !FloatUtils::isZero( _luFactors->_V[_vPivotRow*_m + vColumn] ) ) + if ( !FloatUtils::isZero( _luFactors->_V[_vPivotRow * _m + vColumn] ) ) --_numUColumnElements[uColumn]; } @@ -337,7 +347,7 @@ void GaussianEliminator::eliminate() Eliminate all entries below the pivot element U[k,k] We know that V[_pivotRow, _pivotColumn] = U[k,k]. */ - double pivotElement = _luFactors->_V[_vPivotRow*_m + _vPivotColumn]; + double pivotElement = _luFactors->_V[_vPivotRow * _m + _vPivotColumn]; GAUSSIAN_LOG( Stringf( "Eliminate called. Pivot element: %lf", pivotElement ).ascii() ); @@ -350,17 +360,18 @@ void GaussianEliminator::eliminate() We compute it in terms of V */ unsigned vRowIndex = _luFactors->_P._columnOrdering[row]; - double subDiagonalEntry = _luFactors->_V[vRowIndex*_m + _vPivotColumn]; + double subDiagonalEntry = _luFactors->_V[vRowIndex * _m + _vPivotColumn]; // Ignore zero entries if ( FloatUtils::isZero( subDiagonalEntry ) ) continue; double rowMultiplier = -subDiagonalEntry / pivotElement; - GAUSSIAN_LOG( Stringf( "\tWorking on V row: %u. Multiplier: %lf", vRowIndex, rowMultiplier ).ascii() ); + GAUSSIAN_LOG( Stringf( "\tWorking on V row: %u. Multiplier: %lf", vRowIndex, rowMultiplier ) + .ascii() ); // Eliminate the row - _luFactors->_V[vRowIndex*_m + _vPivotColumn] = 0; + _luFactors->_V[vRowIndex * _m + _vPivotColumn] = 0; --_numUColumnElements[_eliminationStep]; --_numURowElements[row]; @@ -368,12 +379,12 @@ void GaussianEliminator::eliminate() { unsigned vColIndex = _luFactors->_Q._rowOrdering[column]; - bool wasZero = FloatUtils::isZero( _luFactors->_V[vRowIndex*_m + vColIndex] ); + bool wasZero = FloatUtils::isZero( _luFactors->_V[vRowIndex * _m + vColIndex] ); - _luFactors->_V[vRowIndex*_m + vColIndex] += - rowMultiplier * _luFactors->_V[_vPivotRow*_m + vColIndex]; + _luFactors->_V[vRowIndex * _m + vColIndex] += + rowMultiplier * _luFactors->_V[_vPivotRow * _m + vColIndex]; - bool isZero = FloatUtils::isZero( _luFactors->_V[vRowIndex*_m + vColIndex] ); + bool isZero = FloatUtils::isZero( _luFactors->_V[vRowIndex * _m + vColIndex] ); if ( wasZero != isZero ) { @@ -390,21 +401,21 @@ void GaussianEliminator::eliminate() } if ( isZero ) - _luFactors->_V[vRowIndex*_m + vColIndex] = 0; + _luFactors->_V[vRowIndex * _m + vColIndex] = 0; } /* Store the row multiplier in matrix F, using F = PLP'. F's rows are ordered same as V's */ - _luFactors->_F[vRowIndex*_m + fColumnIndex] = -rowMultiplier; + _luFactors->_F[vRowIndex * _m + fColumnIndex] = -rowMultiplier; } /* Put 1 in L's diagonal. TODO: This can be made implicit */ - _luFactors->_F[fColumnIndex*_m + fColumnIndex] = 1; + _luFactors->_F[fColumnIndex * _m + fColumnIndex] = 1; } // diff --git a/src/basis_factorization/GaussianEliminator.h b/src/basis_factorization/GaussianEliminator.h index 6970600583..101d85ee8f 100644 --- a/src/basis_factorization/GaussianEliminator.h +++ b/src/basis_factorization/GaussianEliminator.h @@ -18,7 +18,8 @@ #include "LUFactors.h" -#define GAUSSIAN_LOG( x, ... ) LOG( GlobalConfiguration::GAUSSIAN_ELIMINATION_LOGGING, "GaussianEliminator: %s\n", x ) +#define GAUSSIAN_LOG( x, ... ) \ + LOG( GlobalConfiguration::GAUSSIAN_ELIMINATION_LOGGING, "GaussianEliminator: %s\n", x ) class GaussianEliminator { diff --git a/src/basis_factorization/IBasisFactorization.h b/src/basis_factorization/IBasisFactorization.h index 0f2cb840d8..35a98ae7bf 100644 --- a/src/basis_factorization/IBasisFactorization.h +++ b/src/basis_factorization/IBasisFactorization.h @@ -26,6 +26,7 @@ class IBasisFactorization /* This is the interfact class for a basis factorization. */ + public: /* A callback for obtaining columns of the basis matrix @@ -33,7 +34,9 @@ class IBasisFactorization class BasisColumnOracle { public: - virtual ~BasisColumnOracle() {} + virtual ~BasisColumnOracle() + { + } virtual void getColumnOfBasis( unsigned column, double *result ) const = 0; virtual void getColumnOfBasis( unsigned column, SparseUnsortedList *result ) const = 0; virtual void getSparseBasis( SparseColumnsOfBasis &basis ) const = 0; @@ -44,7 +47,9 @@ class IBasisFactorization { } - virtual ~IBasisFactorization() {} + virtual ~IBasisFactorization() + { + } /* Inform the basis factorization that the basis has been changed @@ -79,10 +84,10 @@ class IBasisFactorization virtual void storeFactorization( IBasisFactorization *other ) = 0; virtual void restoreFactorization( const IBasisFactorization *other ) = 0; - /* + /* Ask the basis factorization to obtain a fresh basis (through the previously-provided oracle). - */ + */ virtual void obtainFreshBasis() = 0; /* @@ -109,7 +114,7 @@ class IBasisFactorization /* Have the Basis Factoriaztion object start reporting statistics. */ - virtual void setStatistics( Statistics * ) {}; + virtual void setStatistics( Statistics * ){}; /* For debugging diff --git a/src/basis_factorization/LPElement.cpp b/src/basis_factorization/LPElement.cpp index 8565cd1d90..f1b87de1fa 100644 --- a/src/basis_factorization/LPElement.cpp +++ b/src/basis_factorization/LPElement.cpp @@ -13,17 +13,18 @@ **/ -#include "EtaMatrix.h" #include "LPElement.h" +#include "EtaMatrix.h" + #include #include #include #include LPElement::LPElement( EtaMatrix *eta, std::pair *pair ) - : _eta( NULL ) - , _pair( NULL ) + : _eta( NULL ) + , _pair( NULL ) { ASSERT( eta || pair ); @@ -35,17 +36,17 @@ LPElement::LPElement( EtaMatrix *eta, std::pair *pair ) LPElement::~LPElement() { - if ( _eta ) - { - delete _eta; - _eta = NULL; - } + if ( _eta ) + { + delete _eta; + _eta = NULL; + } - if ( _pair ) - { - delete _pair; - _pair = NULL; - } + if ( _pair ) + { + delete _pair; + _pair = NULL; + } } void LPElement::dump() const diff --git a/src/basis_factorization/LPElement.h b/src/basis_factorization/LPElement.h index 2c2fd8d3d1..19c52366dc 100644 --- a/src/basis_factorization/LPElement.h +++ b/src/basis_factorization/LPElement.h @@ -17,6 +17,7 @@ #define __LPElement_h__ #include "Debug.h" + #include class EtaMatrix; @@ -24,14 +25,14 @@ class EtaMatrix; class LPElement { public: - LPElement( EtaMatrix *_eta, std::pair *_pair ); - ~LPElement(); + LPElement( EtaMatrix *_eta, std::pair *_pair ); + ~LPElement(); void dump() const; LPElement *duplicate() const; - EtaMatrix *_eta; - std::pair *_pair; + EtaMatrix *_eta; + std::pair *_pair; }; #endif //__LPElement_h__ diff --git a/src/basis_factorization/LUFactorization.cpp b/src/basis_factorization/LUFactorization.cpp index 286a862c8d..e10bffa184 100644 --- a/src/basis_factorization/LUFactorization.cpp +++ b/src/basis_factorization/LUFactorization.cpp @@ -13,30 +13,33 @@ **/ +#include "LUFactorization.h" + #include "BasisFactorizationError.h" #include "Debug.h" #include "EtaMatrix.h" #include "FloatUtils.h" #include "GlobalConfiguration.h" #include "LPElement.h" -#include "LUFactorization.h" #include "MalformedBasisException.h" LUFactorization::LUFactorization( unsigned m, const BasisColumnOracle &basisColumnOracle ) : IBasisFactorization( basisColumnOracle ) , _B( NULL ) - , _m( m ) + , _m( m ) , _luFactors( m ) , _gaussianEliminator( m ) , _z( NULL ) { - _B = new double[m*m]; + _B = new double[m * m]; if ( !_B ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "LUFactorization::B" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "LUFactorization::B" ); _z = new double[m]; if ( !_z ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "LUFactorization::z" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "LUFactorization::z" ); } LUFactorization::~LUFactorization() @@ -46,11 +49,11 @@ LUFactorization::~LUFactorization() void LUFactorization::freeIfNeeded() { - if ( _B ) - { - delete[] _B; - _B = NULL; - } + if ( _B ) + { + delete[] _B; + _B = NULL; + } List::iterator it; for ( it = _etas.begin(); it != _etas.end(); ++it ) @@ -66,7 +69,7 @@ void LUFactorization::freeIfNeeded() const double *LUFactorization::getBasis() const { - return _B; + return _B; } const SparseMatrix *LUFactorization::getSparseBasis() const @@ -77,21 +80,21 @@ const SparseMatrix *LUFactorization::getSparseBasis() const const List LUFactorization::getEtas() const { - return _etas; + return _etas; } void LUFactorization::updateToAdjacentBasis( unsigned columnIndex, const double *changeColumn, - const double */* newColumn */ ) + const double * /* newColumn */ ) { EtaMatrix *matrix = new EtaMatrix( _m, columnIndex, changeColumn ); _etas.append( matrix ); - if ( _etas.size() > GlobalConfiguration::REFACTORIZATION_THRESHOLD ) - { + if ( _etas.size() > GlobalConfiguration::REFACTORIZATION_THRESHOLD ) + { LU_FACTORIZATION_LOG( "Number of etas exceeds threshold. Refactoring basis\n" ); obtainFreshBasis(); - } + } } void LUFactorization::forwardTransformation( const double *y, double *x ) const @@ -135,18 +138,18 @@ void LUFactorization::backwardTransformation( const double *y, double *x ) const We are solving xB = y, where B = B0 * E1 ... * En. The first step is to eliminate the eta matrices. */ - memcpy( _z, y, sizeof(double) * _m ); + memcpy( _z, y, sizeof( double ) * _m ); for ( auto eta = _etas.rbegin(); eta != _etas.rend(); ++eta ) { // The only entry in y that changes is columnIndex - unsigned columnIndex = (*eta)->_columnIndex; + unsigned columnIndex = ( *eta )->_columnIndex; for ( unsigned i = 0; i < _m; ++i ) { if ( i != columnIndex ) - _z[columnIndex] -= (_z[i] * (*eta)->_column[i]); + _z[columnIndex] -= ( _z[i] * ( *eta )->_column[i] ); } - _z[columnIndex] = _z[columnIndex] / (*eta)->_column[columnIndex]; + _z[columnIndex] = _z[columnIndex] / ( *eta )->_column[columnIndex]; if ( FloatUtils::isZero( _z[columnIndex] ) ) _z[columnIndex] = 0.0; @@ -160,7 +163,7 @@ void LUFactorization::backwardTransformation( const double *y, double *x ) const void LUFactorization::clearFactorization() { - List::iterator it; + List::iterator it; for ( it = _etas.begin(); it != _etas.end(); ++it ) delete *it; _etas.clear(); @@ -193,7 +196,7 @@ void LUFactorization::storeFactorization( IBasisFactorization *other ) obtainFreshBasis(); // Store the new basis and factorization - memcpy( otherLUFactorization->_B, _B, sizeof(double) * _m * _m ); + memcpy( otherLUFactorization->_B, _B, sizeof( double ) * _m * _m ); _luFactors.storeToOther( &otherLUFactorization->_luFactors ); } @@ -208,7 +211,7 @@ void LUFactorization::restoreFactorization( const IBasisFactorization *other ) clearFactorization(); // Store the new basis and factorization - memcpy( _B, otherLUFactorization->_B, sizeof(double) * _m * _m ); + memcpy( _B, otherLUFactorization->_B, sizeof( double ) * _m * _m ); otherLUFactorization->_luFactors.storeToOther( &_luFactors ); } diff --git a/src/basis_factorization/LUFactorization.h b/src/basis_factorization/LUFactorization.h index 9668d85b1e..55fa14deaa 100644 --- a/src/basis_factorization/LUFactorization.h +++ b/src/basis_factorization/LUFactorization.h @@ -21,7 +21,8 @@ #include "LUFactors.h" #include "List.h" -#define LU_FACTORIZATION_LOG( x, ... ) LOG( GlobalConfiguration::BASIS_FACTORIZATION_LOGGING, "LUFactorization: %s\n", x ) +#define LU_FACTORIZATION_LOG( x, ... ) \ + LOG( GlobalConfiguration::BASIS_FACTORIZATION_LOGGING, "LUFactorization: %s\n", x ) class EtaMatrix; class LPElement; @@ -50,7 +51,7 @@ class LUFactorization : public IBasisFactorization */ void updateToAdjacentBasis( unsigned columnIndex, const double *changeColumn, - const double */* newColumn */ ); + const double * /* newColumn */ ); /* Perform a forward transformation, i.e. find x such that x = inv(B) * y, @@ -97,18 +98,18 @@ class LUFactorization : public IBasisFactorization void storeFactorization( IBasisFactorization *other ); void restoreFactorization( const IBasisFactorization *other ); - /* + /* Factorize the stored _B matrix into LU form. - */ + */ void factorizeBasis(); - /* + /* Ask the basis factorization to obtain a fresh basis (through the previously-provided oracle). - */ + */ void obtainFreshBasis(); - /* + /* Swap two rows of a matrix. */ void rowSwap( unsigned rowOne, unsigned rowTwo, double *matrix ); @@ -143,9 +144,9 @@ class LUFactorization : public IBasisFactorization /* Getter functions for the various factorization components. */ - const double *getU() const; - const List getLP() const; - const List getEtas() const; + const double *getU() const; + const List getLP() const; + const List getEtas() const; /* Debug @@ -156,7 +157,7 @@ class LUFactorization : public IBasisFactorization /* The Basis matrix. */ - double *_B; + double *_B; /* The dimension of the basis matrix. @@ -186,7 +187,7 @@ class LUFactorization : public IBasisFactorization /* Clear a previous factorization. */ - void clearFactorization(); + void clearFactorization(); }; #endif // __LUFactorization_h__ diff --git a/src/basis_factorization/LUFactors.cpp b/src/basis_factorization/LUFactors.cpp index 51624fb4f8..6ce4dc0f7f 100644 --- a/src/basis_factorization/LUFactors.cpp +++ b/src/basis_factorization/LUFactors.cpp @@ -13,10 +13,11 @@ **/ +#include "LUFactors.h" + #include "BasisFactorizationError.h" #include "Debug.h" #include "FloatUtils.h" -#include "LUFactors.h" #include "MString.h" LUFactors::LUFactors( unsigned m ) @@ -28,11 +29,11 @@ LUFactors::LUFactors( unsigned m ) , _z( NULL ) , _workMatrix( NULL ) { - _F = new double[m*m]; + _F = new double[m * m]; if ( !_F ) throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "LUFactors::F" ); - _V = new double[m*m]; + _V = new double[m * m]; if ( !_V ) throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "LUFactors::V" ); @@ -40,9 +41,10 @@ LUFactors::LUFactors( unsigned m ) if ( !_z ) throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "LUFactors::z" ); - _workMatrix = new double[m*m]; + _workMatrix = new double[m * m]; if ( !_workMatrix ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "LUFactors::workMatrix" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "LUFactors::workMatrix" ); } LUFactors::~LUFactors() @@ -82,7 +84,7 @@ void LUFactors::dump() const printf( "\t" ); for ( unsigned j = 0; j < _m; ++j ) { - printf( "%8.2lf ", _F[i*_m + j] ); + printf( "%8.2lf ", _F[i * _m + j] ); } printf( "\n" ); } @@ -93,24 +95,24 @@ void LUFactors::dump() const printf( "\t" ); for ( unsigned j = 0; j < _m; ++j ) { - printf( "%8.2lf ", _V[i*_m + j] ); + printf( "%8.2lf ", _V[i * _m + j] ); } printf( "\n" ); } printf( "\tDumping product F*V:\n" ); - double *result = new double[_m*_m]; + double *result = new double[_m * _m]; std::fill_n( result, _m * _m, 0.0 ); for ( unsigned i = 0; i < _m; ++i ) { for ( unsigned j = 0; j < _m; ++j ) { - result[i*_m + j] = 0; + result[i * _m + j] = 0; for ( unsigned k = 0; k < _m; ++k ) { - result[i*_m + j] += _F[i*_m + k] * _V[k*_m + j]; + result[i * _m + j] += _F[i * _m + k] * _V[k * _m + j]; } } } @@ -120,7 +122,7 @@ void LUFactors::dump() const printf( "\t" ); for ( unsigned j = 0; j < _m; ++j ) { - printf( "%8.2lf ", result[i*_m + j] ); + printf( "%8.2lf ", result[i * _m + j] ); } printf( "\n" ); } @@ -134,7 +136,7 @@ void LUFactors::dump() const for ( unsigned j = 0; j < _m; ++j ) { unsigned uCol = _Q._rowOrdering[j]; - printf( "%8.2lf ", _V[uRow*_m + uCol] ); + printf( "%8.2lf ", _V[uRow * _m + uCol] ); } printf( "\n" ); } @@ -148,7 +150,7 @@ void LUFactors::dump() const for ( unsigned j = 0; j < _m; ++j ) { unsigned lCol = _P._columnOrdering[j]; - printf( "%8.2lf ", _F[lRow*_m + lCol] ); + printf( "%8.2lf ", _F[lRow * _m + lCol] ); } printf( "\n" ); } @@ -179,7 +181,7 @@ void LUFactors::fForwardTransformation( const double *y, double *x ) const for j = P._rowOrdering[i]. Also observe that the diagonal elements of L remain diagonal elements in F, i.e. F has a diagonal of 1s. */ - memcpy( x, y, sizeof(double) * _m ); + memcpy( x, y, sizeof( double ) * _m ); for ( unsigned lColumn = 0; lColumn < _m; ++lColumn ) { @@ -194,7 +196,7 @@ void LUFactors::fForwardTransformation( const double *y, double *x ) const for ( unsigned lRow = lColumn + 1; lRow < _m; ++lRow ) { unsigned fRow = _P._columnOrdering[lRow]; - x[fRow] -= ( _F[fRow*_m + fColumn] * x[fColumn] ); + x[fRow] -= ( _F[fRow * _m + fColumn] * x[fColumn] ); } } } @@ -223,7 +225,7 @@ void LUFactors::fBackwardTransformation( const double *y, double *x ) const of L remain diagonal elements in F, i.e. F has a diagonal of 1s. */ - memcpy( x, y, sizeof(double) * _m ); + memcpy( x, y, sizeof( double ) * _m ); for ( int lRow = _m - 1; lRow >= 0; --lRow ) { @@ -238,7 +240,7 @@ void LUFactors::fBackwardTransformation( const double *y, double *x ) const for ( int lColumn = lRow - 1; lColumn >= 0; --lColumn ) { unsigned fColumn = _P._columnOrdering[lColumn]; - x[fColumn] -= ( _F[fRow*_m + fColumn] * x[fRow] ); + x[fColumn] -= ( _F[fRow * _m + fColumn] * x[fRow] ); } } } @@ -273,13 +275,13 @@ void LUFactors::vForwardTransformation( const double *y, double *x ) const for ( unsigned uColumn = uRow + 1; uColumn < _m; ++uColumn ) { unsigned vColumn = _Q._rowOrdering[uColumn]; - x[xBeingSolved] -= ( _V[vRow*_m + vColumn] * x[vColumn] ); + x[xBeingSolved] -= ( _V[vRow * _m + vColumn] * x[vColumn] ); } if ( FloatUtils::isZero( x[xBeingSolved] ) ) x[xBeingSolved] = 0.0; else - x[xBeingSolved] *= ( 1.0 / _V[vRow*_m + _Q._rowOrdering[uRow]] ); + x[xBeingSolved] *= ( 1.0 / _V[vRow * _m + _Q._rowOrdering[uRow]] ); } } @@ -313,13 +315,13 @@ void LUFactors::vBackwardTransformation( const double *y, double *x ) const for ( unsigned uRow = 0; uRow < uColumn; ++uRow ) { unsigned vRow = _P._columnOrdering[uRow]; - x[xBeingSolved] -= ( _V[vRow*_m + vColumn] * x[vRow] ); + x[xBeingSolved] -= ( _V[vRow * _m + vColumn] * x[vRow] ); } if ( FloatUtils::isZero( x[xBeingSolved] ) ) x[xBeingSolved] = 0.0; else - x[xBeingSolved] *= ( 1.0 / _V[ _P._columnOrdering[uColumn]*_m + vColumn] ); + x[xBeingSolved] *= ( 1.0 / _V[_P._columnOrdering[uColumn] * _m + vColumn] ); } } @@ -370,7 +372,7 @@ void LUFactors::invertBasis( double *result ) // Initialize _workMatrix to the identity std::fill_n( _workMatrix, _m * _m, 0 ); for ( unsigned i = 0; i < _m; ++i ) - _workMatrix[i*_m + i] = 1; + _workMatrix[i * _m + i] = 1; /* Step 1: Multiply I on the left by inv(L) using @@ -383,10 +385,10 @@ void LUFactors::invertBasis( double *result ) { for ( unsigned lRow = lColumn + 1; lRow < _m; ++lRow ) { - double multiplier = -_F[_P._columnOrdering[lRow]*_m + _P._columnOrdering[lColumn]]; + double multiplier = -_F[_P._columnOrdering[lRow] * _m + _P._columnOrdering[lColumn]]; for ( unsigned i = 0; i <= lColumn; ++i ) - _workMatrix[lRow*_m + i] += _workMatrix[lColumn*_m + i] * multiplier; + _workMatrix[lRow * _m + i] += _workMatrix[lColumn * _m + i] * multiplier; } } @@ -400,18 +402,19 @@ void LUFactors::invertBasis( double *result ) for ( int uColumn = _m - 1; uColumn >= 0; --uColumn ) { double invUDiagonalEntry = - 1 / _V[_P._columnOrdering[uColumn]*_m + _Q._rowOrdering[uColumn]]; + 1 / _V[_P._columnOrdering[uColumn] * _m + _Q._rowOrdering[uColumn]]; for ( int uRow = 0; uRow < uColumn; ++uRow ) { - double multiplier = -_V[_P._columnOrdering[uRow]*_m + _Q._rowOrdering[uColumn]] * invUDiagonalEntry; + double multiplier = + -_V[_P._columnOrdering[uRow] * _m + _Q._rowOrdering[uColumn]] * invUDiagonalEntry; for ( unsigned i = 0; i < _m; ++i ) - _workMatrix[uRow*_m + i] += _workMatrix[uColumn*_m +i] * multiplier; + _workMatrix[uRow * _m + i] += _workMatrix[uColumn * _m + i] * multiplier; } for ( unsigned i = 0; i < _m; ++i ) - _workMatrix[uColumn*_m + i] *= invUDiagonalEntry; + _workMatrix[uColumn * _m + i] *= invUDiagonalEntry; } /* @@ -428,7 +431,7 @@ void LUFactors::invertBasis( double *result ) invLURow = _Q._columnOrdering[i]; invLUColumn = _P._rowOrdering[j]; - result[i*_m + j] = _workMatrix[invLURow*_m + invLUColumn]; + result[i * _m + j] = _workMatrix[invLURow * _m + invLUColumn]; } } } @@ -437,8 +440,8 @@ void LUFactors::storeToOther( LUFactors *other ) const { ASSERT( _m == other->_m ); - memcpy( other->_F, _F, sizeof(double) * _m * _m ); - memcpy( other->_V, _V, sizeof(double) * _m * _m ); + memcpy( other->_F, _F, sizeof( double ) * _m * _m ); + memcpy( other->_V, _V, sizeof( double ) * _m * _m ); _P.storeToOther( &other->_P ); _Q.storeToOther( &other->_Q ); diff --git a/src/basis_factorization/PermutationMatrix.cpp b/src/basis_factorization/PermutationMatrix.cpp index 3e5fde1033..e4ebdc67fe 100644 --- a/src/basis_factorization/PermutationMatrix.cpp +++ b/src/basis_factorization/PermutationMatrix.cpp @@ -13,9 +13,11 @@ **/ +#include "PermutationMatrix.h" + #include "BasisFactorizationError.h" #include "Debug.h" -#include "PermutationMatrix.h" + #include #include #include @@ -77,8 +79,8 @@ PermutationMatrix &PermutationMatrix::operator=( const PermutationMatrix &other _columnOrdering = new unsigned[_m]; } - memcpy( _rowOrdering, other._rowOrdering, sizeof(unsigned) * _m ); - memcpy( _columnOrdering, other._columnOrdering, sizeof(unsigned) * _m ); + memcpy( _rowOrdering, other._rowOrdering, sizeof( unsigned ) * _m ); + memcpy( _columnOrdering, other._columnOrdering, sizeof( unsigned ) * _m ); return *this; } @@ -182,8 +184,8 @@ void PermutationMatrix::storeToOther( PermutationMatrix *other ) const { ASSERT( _m == other->_m ); - memcpy( other->_rowOrdering, _rowOrdering, sizeof(unsigned) * _m ); - memcpy( other->_columnOrdering, _columnOrdering, sizeof(unsigned) * _m ); + memcpy( other->_rowOrdering, _rowOrdering, sizeof( unsigned ) * _m ); + memcpy( other->_columnOrdering, _columnOrdering, sizeof( unsigned ) * _m ); } // diff --git a/src/basis_factorization/PermutationMatrix.h b/src/basis_factorization/PermutationMatrix.h index 8f905ad605..4a01730254 100644 --- a/src/basis_factorization/PermutationMatrix.h +++ b/src/basis_factorization/PermutationMatrix.h @@ -23,6 +23,7 @@ class PermutationMatrix /* The identity matrix with its rows in a different order */ + public: PermutationMatrix( unsigned m ); ~PermutationMatrix(); diff --git a/src/basis_factorization/SparseColumnsOfBasis.cpp b/src/basis_factorization/SparseColumnsOfBasis.cpp index 4ab22bd3f6..29b344c49f 100644 --- a/src/basis_factorization/SparseColumnsOfBasis.cpp +++ b/src/basis_factorization/SparseColumnsOfBasis.cpp @@ -13,16 +13,18 @@ **/ -#include "BasisFactorizationError.h" #include "SparseColumnsOfBasis.h" +#include "BasisFactorizationError.h" + SparseColumnsOfBasis::SparseColumnsOfBasis( unsigned m ) : _columns( NULL ) , _m( m ) { _columns = new const SparseUnsortedList *[m]; if ( !_columns ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "SparseColumnsOfBasis::columns" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "SparseColumnsOfBasis::columns" ); } SparseColumnsOfBasis::~SparseColumnsOfBasis() diff --git a/src/basis_factorization/SparseEtaMatrix.cpp b/src/basis_factorization/SparseEtaMatrix.cpp index 12a94af0e0..c46768a802 100644 --- a/src/basis_factorization/SparseEtaMatrix.cpp +++ b/src/basis_factorization/SparseEtaMatrix.cpp @@ -13,8 +13,9 @@ **/ -#include "BasisFactorizationError.h" #include "SparseEtaMatrix.h" + +#include "BasisFactorizationError.h" #include "FloatUtils.h" #include @@ -129,8 +130,8 @@ void SparseEtaMatrix::toMatrix( double *A ) const { std::fill_n( A, _m * _m, 0.0 ); - for ( unsigned i = 0; i < _m; ++i ) - A[i * _m + i] = 1; + for ( unsigned i = 0; i < _m; ++i ) + A[i * _m + i] = 1; for ( const auto &entry : _sparseColumn ) A[entry._index * _m + _columnIndex] = entry._value; diff --git a/src/basis_factorization/SparseFTFactorization.cpp b/src/basis_factorization/SparseFTFactorization.cpp index 41363d360e..c55ac60b20 100644 --- a/src/basis_factorization/SparseFTFactorization.cpp +++ b/src/basis_factorization/SparseFTFactorization.cpp @@ -13,17 +13,19 @@ **/ +#include "SparseFTFactorization.h" + #include "BasisFactorizationError.h" #include "Debug.h" #include "FloatUtils.h" #include "GlobalConfiguration.h" #include "MalformedBasisException.h" -#include "SparseFTFactorization.h" -SparseFTFactorization::SparseFTFactorization( unsigned m, const BasisColumnOracle &basisColumnOracle ) +SparseFTFactorization::SparseFTFactorization( unsigned m, + const BasisColumnOracle &basisColumnOracle ) : IBasisFactorization( basisColumnOracle ) , _B( m ) - , _m( m ) + , _m( m ) , _sparseLUFactors( m ) , _sparseGaussianEliminator( m ) , _statistics( NULL ) @@ -34,19 +36,23 @@ SparseFTFactorization::SparseFTFactorization( unsigned m, const BasisColumnOracl { _z1 = new double[m]; if ( !_z1 ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "SparseFTFactorization::z1" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "SparseFTFactorization::z1" ); _z2 = new double[m]; if ( !_z2 ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "SparseFTFactorization::z2" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "SparseFTFactorization::z2" ); _z3 = new double[m]; if ( !_z3 ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "SparseFTFactorization::z3" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "SparseFTFactorization::z3" ); _z4 = new double[m]; if ( !_z4 ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "SparseFTFactorization::z4" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "SparseFTFactorization::z4" ); } SparseFTFactorization::~SparseFTFactorization() @@ -96,7 +102,7 @@ const SparseMatrix *SparseFTFactorization::getSparseBasis() const } void SparseFTFactorization::updateToAdjacentBasis( unsigned columnIndex, - const double */* changeColumn */, + const double * /* changeColumn */, const double *newColumn ) { // q = columnIndex @@ -183,8 +189,8 @@ void SparseFTFactorization::updateToAdjacentBasis( unsigned columnIndex, for ( unsigned i = uColumnIndex; i < lastNonZeroEntryInU; ++i ) { // Rows move upwards, columns move to the left - _sparseLUFactors._P._columnOrdering[i] = _sparseLUFactors._P._columnOrdering[i+1]; - _sparseLUFactors._Q._rowOrdering[i] = _sparseLUFactors._Q._rowOrdering[i+1]; + _sparseLUFactors._P._columnOrdering[i] = _sparseLUFactors._P._columnOrdering[i + 1]; + _sparseLUFactors._Q._rowOrdering[i] = _sparseLUFactors._Q._rowOrdering[i + 1]; // Adjsut the transposed permutations, also _sparseLUFactors._P._rowOrdering[_sparseLUFactors._P._columnOrdering[i]] = i; @@ -278,10 +284,8 @@ void SparseFTFactorization::updateToAdjacentBasis( unsigned columnIndex, } if ( -GlobalConfiguration::SPARSE_FORREST_TOMLIN_DIAGONAL_ELEMENT_TOLERANCE < - _z3[columnIndex] - && - _z3[columnIndex] < - GlobalConfiguration::SPARSE_FORREST_TOMLIN_DIAGONAL_ELEMENT_TOLERANCE ) + _z3[columnIndex] && + _z3[columnIndex] < GlobalConfiguration::SPARSE_FORREST_TOMLIN_DIAGONAL_ELEMENT_TOLERANCE ) { obtainFreshBasis(); return; @@ -441,7 +445,7 @@ void SparseFTFactorization::hForwardTransformation( const double *y, double *x ) Eliminate etas one by one. */ - memcpy( x, y, sizeof(double) * _m ); + memcpy( x, y, sizeof( double ) * _m ); for ( const auto &eta : _etas ) { @@ -463,14 +467,14 @@ void SparseFTFactorization::hBackwardTransformation( const double *y, double *x Eliminate etas one by one. */ - memcpy( x, y, sizeof(double) * _m ); + memcpy( x, y, sizeof( double ) * _m ); for ( auto eta = _etas.rbegin(); eta != _etas.rend(); ++eta ) { - unsigned pivotIndex = (*eta)->_columnIndex; + unsigned pivotIndex = ( *eta )->_columnIndex; double pivotValue = x[pivotIndex]; - for ( const auto &entry : (*eta)->_sparseColumn ) + for ( const auto &entry : ( *eta )->_sparseColumn ) { unsigned entryIndex = entry._index; double value = entry._value; @@ -498,7 +502,7 @@ void SparseFTFactorization::dumpExplicitBasis() const // Start with F _sparseLUFactors._F->toDense( result ); for ( unsigned i = 0; i < _m; ++i ) - result[i*_m + i] = 1; + result[i * _m + i] = 1; // Go eta by eta for ( const auto &eta : _etas ) @@ -510,15 +514,15 @@ void SparseFTFactorization::dumpExplicitBasis() const { for ( unsigned j = 0; j < _m; ++j ) { - temp[i*_m + j] = 0; + temp[i * _m + j] = 0; for ( unsigned k = 0; k < _m; ++k ) { - temp[i*_m + j] += ( result[i*_m + k] * toMultiply[j*_m + k] ); + temp[i * _m + j] += ( result[i * _m + k] * toMultiply[j * _m + k] ); } } } - memcpy( result, temp, sizeof(double) * _m * _m ); + memcpy( result, temp, sizeof( double ) * _m * _m ); } // End with V @@ -528,14 +532,14 @@ void SparseFTFactorization::dumpExplicitBasis() const { for ( unsigned j = 0; j < _m; ++j ) { - temp[i*_m + j] = 0; + temp[i * _m + j] = 0; for ( unsigned k = 0; k < _m; ++k ) { - temp[i*_m + j] += ( result[i*_m + k] * toMultiply[k*_m + j] ); + temp[i * _m + j] += ( result[i * _m + k] * toMultiply[k * _m + j] ); } } } - memcpy( result, temp, sizeof(double) * _m * _m ); + memcpy( result, temp, sizeof( double ) * _m * _m ); // Print out the result printf( "SparseFTFactorization dumping explicit basis:\n" ); @@ -544,7 +548,7 @@ void SparseFTFactorization::dumpExplicitBasis() const printf( "\t" ); for ( unsigned j = 0; j < _m; ++j ) { - printf( "%5.2lf ", result[i*_m + j] ); + printf( "%5.2lf ", result[i * _m + j] ); } printf( "\n" ); diff --git a/src/basis_factorization/SparseFTFactorization.h b/src/basis_factorization/SparseFTFactorization.h index 742456e485..da2c13404d 100644 --- a/src/basis_factorization/SparseFTFactorization.h +++ b/src/basis_factorization/SparseFTFactorization.h @@ -23,7 +23,8 @@ #include "SparseLUFactors.h" #include "Statistics.h" -#define SFTF_FACTORIZATION_LOG( x, ... ) LOG( GlobalConfiguration::BASIS_FACTORIZATION_LOGGING, "SparseFTFactorization: %s\n", x ) +#define SFTF_FACTORIZATION_LOG( x, ... ) \ + LOG( GlobalConfiguration::BASIS_FACTORIZATION_LOGGING, "SparseFTFactorization: %s\n", x ) /* This class performs a sparse FT factorization of a given matrix. @@ -77,10 +78,10 @@ class SparseFTFactorization : public IBasisFactorization void storeFactorization( IBasisFactorization *other ); void restoreFactorization( const IBasisFactorization *other ); - /* + /* Ask the basis factorization to obtain a fresh basis (through the previously-provided oracle). - */ + */ void obtainFreshBasis(); /* @@ -157,7 +158,7 @@ class SparseFTFactorization : public IBasisFactorization /* Factorize the stored _B matrix into LU form. - */ + */ void factorizeBasis(); /* @@ -174,7 +175,7 @@ class SparseFTFactorization : public IBasisFactorization /* Clear a previous factorization. */ - void clearFactorization(); + void clearFactorization(); /* Have the Basis Factoriaztion object start reporting statistics. diff --git a/src/basis_factorization/SparseGaussianEliminator.cpp b/src/basis_factorization/SparseGaussianEliminator.cpp index 3e1b318f7f..2de9eb656f 100644 --- a/src/basis_factorization/SparseGaussianEliminator.cpp +++ b/src/basis_factorization/SparseGaussianEliminator.cpp @@ -13,6 +13,8 @@ **/ +#include "SparseGaussianEliminator.h" + #include "BasisFactorizationError.h" #include "Debug.h" #include "EtaMatrix.h" @@ -20,7 +22,6 @@ #include "GlobalConfiguration.h" #include "MStringf.h" #include "MalformedBasisException.h" -#include "SparseGaussianEliminator.h" #include @@ -80,7 +81,8 @@ SparseGaussianEliminator::~SparseGaussianEliminator() } } -void SparseGaussianEliminator::initializeFactorization( const SparseColumnsOfBasis *A, SparseLUFactors *sparseLUFactors ) +void SparseGaussianEliminator::initializeFactorization( const SparseColumnsOfBasis *A, + SparseLUFactors *sparseLUFactors ) { // Allocate the work space _sparseLUFactors = sparseLUFactors; @@ -115,8 +117,8 @@ void SparseGaussianEliminator::permute() { /* The element selected for pivoting is U[p,q], - We want to update P and Q to move u[p,q] to position [k,k] in U (= P'VQ'), where k is the current - eliminiation step. + We want to update P and Q to move u[p,q] to position [k,k] in U (= P'VQ'), where k is the + current eliminiation step. */ _sparseLUFactors->_P.swapColumns( _uPivotRow, _eliminationStep ); @@ -133,7 +135,8 @@ void SparseGaussianEliminator::permute() _numUColumnElements[_eliminationStep] = temp; } -void SparseGaussianEliminator::run( const SparseColumnsOfBasis *A, SparseLUFactors *sparseLUFactors ) +void SparseGaussianEliminator::run( const SparseColumnsOfBasis *A, + SparseLUFactors *sparseLUFactors ) { // Initialize the LU factors initializeFactorization( A, sparseLUFactors ); @@ -242,9 +245,10 @@ void SparseGaussianEliminator::choosePivot() _pivotElement = entry->_value; SGAUSSIAN_LOG( Stringf( "Choose pivot selected a pivot (singleton row): V[%u,%u] = %lf", - _vPivotRow, - _vPivotColumn, - _pivotElement ).ascii() ); + _vPivotRow, + _vPivotColumn, + _pivotElement ) + .ascii() ); return; } } @@ -286,10 +290,12 @@ void SparseGaussianEliminator::choosePivot() ASSERT( found ); - SGAUSSIAN_LOG( Stringf( "Choose pivot selected a pivot (singleton column): V[%u,%u] = %lf", - _vPivotRow, - _vPivotColumn, - _pivotElement ).ascii() ); + SGAUSSIAN_LOG( + Stringf( "Choose pivot selected a pivot (singleton column): V[%u,%u] = %lf", + _vPivotRow, + _vPivotColumn, + _pivotElement ) + .ascii() ); return; } } @@ -345,15 +351,18 @@ void SparseGaussianEliminator::choosePivot() double absContender = FloatUtils::abs( contender ); // Only consider large-enough elements - if ( FloatUtils::gt( absContender, - maxInColumn * GlobalConfiguration::GAUSSIAN_ELIMINATION_PIVOT_SCALE_THRESHOLD ) ) + if ( FloatUtils::gt( + absContender, + maxInColumn * + GlobalConfiguration::GAUSSIAN_ELIMINATION_PIVOT_SCALE_THRESHOLD ) ) { - unsigned cost = ( _numURowElements[uRow] - 1 ) * ( _numUColumnElements[uColumn] - 1 ); + unsigned cost = + ( _numURowElements[uRow] - 1 ) * ( _numUColumnElements[uColumn] - 1 ); ASSERT( ( cost != minimalCost ) || found ); - if ( ( cost < minimalCost ) || - ( ( cost == minimalCost ) && FloatUtils::gt( absContender, absPivotElement ) ) ) + if ( ( cost < minimalCost ) || ( ( cost == minimalCost ) && + FloatUtils::gt( absContender, absPivotElement ) ) ) { minimalCost = cost; _uPivotRow = uRow; @@ -373,7 +382,12 @@ void SparseGaussianEliminator::choosePivot() throw BasisFactorizationError( BasisFactorizationError::GAUSSIAN_ELIMINATION_FAILED, "Couldn't find a pivot" ); - SGAUSSIAN_LOG( Stringf( "Choose pivot selected a pivot: V[%u,%u] = %lf (cost %u)", _vPivotRow, _vPivotColumn, _pivotElement, minimalCost ).ascii() ); + SGAUSSIAN_LOG( Stringf( "Choose pivot selected a pivot: V[%u,%u] = %lf (cost %u)", + _vPivotRow, + _vPivotColumn, + _pivotElement, + minimalCost ) + .ascii() ); } void SparseGaussianEliminator::eliminate() @@ -421,7 +435,7 @@ void SparseGaussianEliminator::eliminate() Compute the Gaussian row multiplier for this row. The multiplier is: - U[row,k] / pivotElement */ - double rowMultiplier = - entry[index]._value / _pivotElement; + double rowMultiplier = -entry[index]._value / _pivotElement; // Get the row being eliminated in dense format _sparseLUFactors->_V->getRowDense( vRow, _work2 ); diff --git a/src/basis_factorization/SparseGaussianEliminator.h b/src/basis_factorization/SparseGaussianEliminator.h index c22a9376ad..25ad762f10 100644 --- a/src/basis_factorization/SparseGaussianEliminator.h +++ b/src/basis_factorization/SparseGaussianEliminator.h @@ -22,7 +22,8 @@ #include "SparseMatrix.h" #include "Statistics.h" -#define SGAUSSIAN_LOG( x, ... ) LOG( GlobalConfiguration::GAUSSIAN_ELIMINATION_LOGGING, "SparseGaussianEliminator: %s\n", x ) +#define SGAUSSIAN_LOG( x, ... ) \ + LOG( GlobalConfiguration::GAUSSIAN_ELIMINATION_LOGGING, "SparseGaussianEliminator: %s\n", x ) class SparseGaussianEliminator { diff --git a/src/basis_factorization/SparseLUFactorization.cpp b/src/basis_factorization/SparseLUFactorization.cpp index e8427a2df3..fb86d087bb 100644 --- a/src/basis_factorization/SparseLUFactorization.cpp +++ b/src/basis_factorization/SparseLUFactorization.cpp @@ -13,6 +13,8 @@ **/ +#include "SparseLUFactorization.h" + #include "BasisFactorizationError.h" #include "Debug.h" #include "EtaMatrix.h" @@ -20,9 +22,9 @@ #include "GlobalConfiguration.h" #include "LPElement.h" #include "MalformedBasisException.h" -#include "SparseLUFactorization.h" -SparseLUFactorization::SparseLUFactorization( unsigned m, const BasisColumnOracle &basisColumnOracle ) +SparseLUFactorization::SparseLUFactorization( unsigned m, + const BasisColumnOracle &basisColumnOracle ) : IBasisFactorization( basisColumnOracle ) , _B( m ) , _m( m ) @@ -32,7 +34,8 @@ SparseLUFactorization::SparseLUFactorization( unsigned m, const BasisColumnOracl { _z = new double[m]; if ( !_z ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "SparseLUFactorization::z" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "SparseLUFactorization::z" ); } SparseLUFactorization::~SparseLUFactorization() @@ -69,23 +72,23 @@ const SparseMatrix *SparseLUFactorization::getSparseBasis() const const List SparseLUFactorization::getEtas() const { - return _etas; + return _etas; } void SparseLUFactorization::updateToAdjacentBasis( unsigned columnIndex, const double *changeColumn, - const double */* newColumn */ ) + const double * /* newColumn */ ) { ASSERT( !FloatUtils::isZero( changeColumn[columnIndex] ) ); EtaMatrix *matrix = new EtaMatrix( _m, columnIndex, changeColumn ); _etas.append( matrix ); - if ( _etas.size() > GlobalConfiguration::REFACTORIZATION_THRESHOLD ) - { + if ( _etas.size() > GlobalConfiguration::REFACTORIZATION_THRESHOLD ) + { BASIS_FACTORIZATION_LOG( "Number of etas exceeds threshold. Refactoring basis\n" ); obtainFreshBasis(); - } + } } void SparseLUFactorization::forwardTransformation( const double *y, double *x ) const @@ -129,18 +132,18 @@ void SparseLUFactorization::backwardTransformation( const double *y, double *x ) We are solving xB = y, where B = B0 * E1 ... * En. The first step is to eliminate the eta matrices. */ - memcpy( _z, y, sizeof(double) * _m ); + memcpy( _z, y, sizeof( double ) * _m ); for ( auto eta = _etas.rbegin(); eta != _etas.rend(); ++eta ) { // The only entry in y that changes is columnIndex - unsigned columnIndex = (*eta)->_columnIndex; + unsigned columnIndex = ( *eta )->_columnIndex; for ( unsigned i = 0; i < _m; ++i ) { if ( i != columnIndex ) - _z[columnIndex] -= (_z[i] * (*eta)->_column[i]); + _z[columnIndex] -= ( _z[i] * ( *eta )->_column[i] ); } - _z[columnIndex] = _z[columnIndex] / (*eta)->_column[columnIndex]; + _z[columnIndex] = _z[columnIndex] / ( *eta )->_column[columnIndex]; if ( FloatUtils::isZero( _z[columnIndex] ) ) _z[columnIndex] = 0.0; @@ -154,7 +157,7 @@ void SparseLUFactorization::backwardTransformation( const double *y, double *x ) void SparseLUFactorization::clearFactorization() { - List::iterator it; + List::iterator it; for ( it = _etas.begin(); it != _etas.end(); ++it ) delete *it; _etas.clear(); @@ -258,7 +261,7 @@ void SparseLUFactorization::dumpExplicitBasis() const // Start with F _sparseLUFactors._F->toDense( result ); for ( unsigned i = 0; i < _m; ++i ) - result[i*_m + i] = 1; + result[i * _m + i] = 1; // Multiply by V _sparseLUFactors._V->toDense( toMultiply ); @@ -267,14 +270,14 @@ void SparseLUFactorization::dumpExplicitBasis() const { for ( unsigned j = 0; j < _m; ++j ) { - temp[i*_m + j] = 0; + temp[i * _m + j] = 0; for ( unsigned k = 0; k < _m; ++k ) { - temp[i*_m + j] += ( result[i*_m + k] * toMultiply[k*_m + j] ); + temp[i * _m + j] += ( result[i * _m + k] * toMultiply[k * _m + j] ); } } } - memcpy( result, temp, sizeof(double) * _m * _m ); + memcpy( result, temp, sizeof( double ) * _m * _m ); // Go eta by eta for ( const auto &eta : _etas ) @@ -285,15 +288,15 @@ void SparseLUFactorization::dumpExplicitBasis() const { for ( unsigned j = 0; j < _m; ++j ) { - temp[i*_m + j] = 0; + temp[i * _m + j] = 0; for ( unsigned k = 0; k < _m; ++k ) { - temp[i*_m + j] += ( result[i*_m + k] * toMultiply[k*_m + j] ); + temp[i * _m + j] += ( result[i * _m + k] * toMultiply[k * _m + j] ); } } } - memcpy( result, temp, sizeof(double) * _m * _m ); + memcpy( result, temp, sizeof( double ) * _m * _m ); } // Print out the result @@ -303,7 +306,7 @@ void SparseLUFactorization::dumpExplicitBasis() const printf( "\t" ); for ( unsigned j = 0; j < _m; ++j ) { - printf( "%5.2lf ", result[i*_m + j] ); + printf( "%5.2lf ", result[i * _m + j] ); } printf( "\n" ); diff --git a/src/basis_factorization/SparseLUFactorization.h b/src/basis_factorization/SparseLUFactorization.h index 4e6c3a94c9..14247264d9 100644 --- a/src/basis_factorization/SparseLUFactorization.h +++ b/src/basis_factorization/SparseLUFactorization.h @@ -21,7 +21,8 @@ #include "SparseGaussianEliminator.h" #include "SparseLUFactors.h" -#define BASIS_FACTORIZATION_LOG( x, ... ) LOG( GlobalConfiguration::BASIS_FACTORIZATION_LOGGING, "SparseLUFactorization: %s\n", x ) +#define BASIS_FACTORIZATION_LOG( x, ... ) \ + LOG( GlobalConfiguration::BASIS_FACTORIZATION_LOGGING, "SparseLUFactorization: %s\n", x ) class EtaMatrix; class LPElement; @@ -92,10 +93,10 @@ class SparseLUFactorization : public IBasisFactorization void storeFactorization( IBasisFactorization *other ); void restoreFactorization( const IBasisFactorization *other ); - /* + /* Ask the basis factorization to obtain a fresh basis (through the previously-provided oracle). - */ + */ void obtainFreshBasis(); /* @@ -122,7 +123,7 @@ class SparseLUFactorization : public IBasisFactorization /* Getter functions for the various factorization components. */ - const List getEtas() const; + const List getEtas() const; /* Debug @@ -168,7 +169,7 @@ class SparseLUFactorization : public IBasisFactorization /* Factorize the stored _B matrix into LU form. - */ + */ void factorizeBasis(); /* @@ -180,7 +181,7 @@ class SparseLUFactorization : public IBasisFactorization /* Clear a previous factorization. */ - void clearFactorization(); + void clearFactorization(); }; #endif // __SparseLUFactorization_h__ diff --git a/src/basis_factorization/SparseLUFactors.cpp b/src/basis_factorization/SparseLUFactors.cpp index b099a5d46f..f6a7634096 100644 --- a/src/basis_factorization/SparseLUFactors.cpp +++ b/src/basis_factorization/SparseLUFactors.cpp @@ -13,11 +13,12 @@ **/ +#include "SparseLUFactors.h" + #include "BasisFactorizationError.h" #include "Debug.h" #include "FloatUtils.h" #include "MString.h" -#include "SparseLUFactors.h" SparseLUFactors::SparseLUFactors( unsigned m ) : _m( m ) @@ -36,35 +37,43 @@ SparseLUFactors::SparseLUFactors( unsigned m ) { _F = new SparseUnsortedArrays(); if ( !_F ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "SparseLUFactors::F" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "SparseLUFactors::F" ); _V = new SparseUnsortedArrays(); if ( !_V ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "SparseLUFactors::V" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "SparseLUFactors::V" ); _Ft = new SparseUnsortedArrays(); if ( !_Ft ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "SparseLUFactors::Ft" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "SparseLUFactors::Ft" ); _Vt = new SparseUnsortedArrays(); if ( !_Vt ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "SparseLUFactors::Vt" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "SparseLUFactors::Vt" ); _vDiagonalElements = new double[m]; if ( !_vDiagonalElements ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "SparseLUFactors::vDiagonalElements" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "SparseLUFactors::vDiagonalElements" ); _z = new double[m]; if ( !_z ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "SparseLUFactors::z" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "SparseLUFactors::z" ); - _workMatrix = new double[m*m]; + _workMatrix = new double[m * m]; if ( !_workMatrix ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "SparseLUFactors::workMatrix" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "SparseLUFactors::workMatrix" ); _workVector = new double[m]; if ( !_workVector ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "SparseLUFactors::workVector" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "SparseLUFactors::workVector" ); } SparseLUFactors::~SparseLUFactors() @@ -130,17 +139,17 @@ void SparseLUFactors::dump() const printf( "\tDumping product F*V:\n" ); - double *result = new double[_m*_m]; + double *result = new double[_m * _m]; std::fill_n( result, _m * _m, 0.0 ); for ( unsigned i = 0; i < _m; ++i ) { for ( unsigned j = 0; j < _m; ++j ) { - result[i*_m + j] = 0; + result[i * _m + j] = 0; for ( unsigned k = 0; k < _m; ++k ) { - result[i*_m + j] += ( i == k ? 1.0 : _F->get( i, k ) ) * _V->get( k, j ); + result[i * _m + j] += ( i == k ? 1.0 : _F->get( i, k ) ) * _V->get( k, j ); } } } @@ -150,7 +159,7 @@ void SparseLUFactors::dump() const printf( "\t" ); for ( unsigned j = 0; j < _m; ++j ) { - printf( "%8.2lf ", result[i*_m + j] ); + printf( "%8.2lf ", result[i * _m + j] ); } printf( "\n" ); } @@ -216,7 +225,7 @@ void SparseLUFactors::fForwardTransformation( const double *y, double *x ) const elements in F, i.e. F has a diagonal of 1s. */ - memcpy( x, y, sizeof(double) * _m ); + memcpy( x, y, sizeof( double ) * _m ); const PermutationMatrix *p = ( _usePForF ) ? &_PForF : &_P; double xElement; @@ -264,7 +273,7 @@ void SparseLUFactors::fBackwardTransformation( const double *y, double *x ) cons elements in F, i.e. F has a diagonal of 1s. */ - memcpy( x, y, sizeof(double) * _m ); + memcpy( x, y, sizeof( double ) * _m ); const PermutationMatrix *p = ( _usePForF ) ? &_PForF : &_P; double xElement; @@ -318,7 +327,7 @@ void SparseLUFactors::vForwardTransformation( const double *y, double *x ) const const SparseUnsortedArray::Entry *entry; unsigned nnz; - memcpy( _workVector, y, sizeof(double) * _m ); + memcpy( _workVector, y, sizeof( double ) * _m ); for ( int uRow = _m - 1; uRow >= 0; --uRow ) { @@ -376,7 +385,7 @@ void SparseLUFactors::vBackwardTransformation( const double *y, double *x ) cons const SparseUnsortedArray::Entry *entry; unsigned nnz; - memcpy( _workVector, y, sizeof(double) * _m ); + memcpy( _workVector, y, sizeof( double ) * _m ); for ( unsigned utIndex = 0; utIndex < _m; ++utIndex ) { @@ -457,7 +466,7 @@ void SparseLUFactors::invertBasis( double *result ) // Initialize _workMatrix to the identity std::fill_n( _workMatrix, _m * _m, 0 ); for ( unsigned i = 0; i < _m; ++i ) - _workMatrix[i*_m + i] = 1; + _workMatrix[i * _m + i] = 1; SparseUnsortedArray::Entry entry; @@ -482,7 +491,7 @@ void SparseLUFactors::invertBasis( double *result ) if ( lRow > lColumn ) { for ( unsigned i = 0; i <= lColumn; ++i ) - _workMatrix[lRow*_m + i] += _workMatrix[lColumn*_m + i] * ( - entry._value ); + _workMatrix[lRow * _m + i] += _workMatrix[lColumn * _m + i] * ( -entry._value ); } } } @@ -499,8 +508,7 @@ void SparseLUFactors::invertBasis( double *result ) unsigned vColumn = _Q._rowOrdering[uColumn]; const SparseUnsortedArray *sparseColumn = _Vt->getRow( vColumn ); - double invUDiagonalEntry = - 1 / sparseColumn->get( _P._columnOrdering[uColumn] ); + double invUDiagonalEntry = 1 / sparseColumn->get( _P._columnOrdering[uColumn] ); for ( unsigned i = 0; i < sparseColumn->getNnz(); ++i ) { @@ -512,13 +520,12 @@ void SparseLUFactors::invertBasis( double *result ) { double multiplier = ( -entry._value * invUDiagonalEntry ); for ( unsigned i = 0; i < _m; ++i ) - _workMatrix[uRow*_m + i] += _workMatrix[uColumn*_m +i] * multiplier; + _workMatrix[uRow * _m + i] += _workMatrix[uColumn * _m + i] * multiplier; } - } for ( unsigned i = 0; i < _m; ++i ) - _workMatrix[uColumn*_m + i] *= invUDiagonalEntry; + _workMatrix[uColumn * _m + i] *= invUDiagonalEntry; } /* @@ -535,7 +542,7 @@ void SparseLUFactors::invertBasis( double *result ) invLURow = _Q._columnOrdering[i]; invLUColumn = _P._rowOrdering[j]; - result[i*_m + j] = _workMatrix[invLURow*_m + invLUColumn]; + result[i * _m + j] = _workMatrix[invLURow * _m + invLUColumn]; } } } @@ -554,7 +561,7 @@ void SparseLUFactors::storeToOther( SparseLUFactors *other ) const _P.storeToOther( &other->_P ); _Q.storeToOther( &other->_Q ); - memcpy( other->_vDiagonalElements, _vDiagonalElements, sizeof(double) * _m ); + memcpy( other->_vDiagonalElements, _vDiagonalElements, sizeof( double ) * _m ); other->_usePForF = false; } diff --git a/src/basis_factorization/SparseMatrix.h b/src/basis_factorization/SparseMatrix.h index dc3ac2032a..49a971eb1c 100644 --- a/src/basis_factorization/SparseMatrix.h +++ b/src/basis_factorization/SparseMatrix.h @@ -21,7 +21,9 @@ class SparseUnsortedList; class SparseMatrix { public: - virtual ~SparseMatrix() {} + virtual ~SparseMatrix() + { + } /* Initialize the sparse matrix from a given dense matrix diff --git a/src/basis_factorization/SparseUnsortedArray.cpp b/src/basis_factorization/SparseUnsortedArray.cpp index deef5f324a..c39c47c304 100644 --- a/src/basis_factorization/SparseUnsortedArray.cpp +++ b/src/basis_factorization/SparseUnsortedArray.cpp @@ -13,10 +13,11 @@ **/ +#include "SparseUnsortedArray.h" + #include "BasisFactorizationError.h" #include "Debug.h" #include "FloatUtils.h" -#include "SparseUnsortedArray.h" #include "SparseUnsortedList.h" SparseUnsortedArray::SparseUnsortedArray() @@ -174,7 +175,7 @@ SparseUnsortedArray &SparseUnsortedArray::operator=( const SparseUnsortedArray & _array = new Entry[_allocatedSize]; - memcpy( _array, other._array, sizeof(Entry) * _nnz ); + memcpy( _array, other._array, sizeof( Entry ) * _nnz ); return *this; } @@ -222,7 +223,7 @@ void SparseUnsortedArray::append( unsigned index, double value ) void SparseUnsortedArray::addLastEntry( double entry ) { if ( !FloatUtils::isZero( entry ) ) - append( _maxSize, entry ); + append( _maxSize, entry ); ++_maxSize; } @@ -293,7 +294,7 @@ void SparseUnsortedArray::incrementSize() void SparseUnsortedArray::increaseCapacity() { Entry *newArray = new Entry[_allocatedSize + CHUNK_SIZE]; - memcpy( newArray, _array, sizeof(Entry) * _nnz ); + memcpy( newArray, _array, sizeof( Entry ) * _nnz ); delete[] _array; _array = newArray; _allocatedSize += CHUNK_SIZE; diff --git a/src/basis_factorization/SparseUnsortedArrays.cpp b/src/basis_factorization/SparseUnsortedArrays.cpp index e3c24f234c..14a17ec88d 100644 --- a/src/basis_factorization/SparseUnsortedArrays.cpp +++ b/src/basis_factorization/SparseUnsortedArrays.cpp @@ -13,10 +13,12 @@ **/ +#include "SparseUnsortedArrays.h" + #include "BasisFactorizationError.h" #include "Debug.h" #include "FloatUtils.h" -#include "SparseUnsortedArrays.h" + #include SparseUnsortedArrays::SparseUnsortedArrays() @@ -58,13 +60,15 @@ void SparseUnsortedArrays::initialize( const double *M, unsigned m, unsigned n ) _rows = new SparseUnsortedArray *[_m]; if ( !_rows ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "SparseUnsortedArrays::rows" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "SparseUnsortedArrays::rows" ); for ( unsigned i = 0; i < _m; ++i ) { _rows[i] = new SparseUnsortedArray; if ( !_rows[i] ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "SparseUnsortedArrays::rows[i]" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "SparseUnsortedArrays::rows[i]" ); _rows[i]->initialize( M + ( i * n ), n ); } @@ -79,13 +83,15 @@ void SparseUnsortedArrays::initialize( const SparseUnsortedArray **V, unsigned m _rows = new SparseUnsortedArray *[_m]; if ( !_rows ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "SparseUnsortedArrays::rows" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "SparseUnsortedArrays::rows" ); for ( unsigned i = 0; i < _m; ++i ) { _rows[i] = new SparseUnsortedArray; if ( !_rows[i] ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "SparseUnsortedArrays::rows[i]" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "SparseUnsortedArrays::rows[i]" ); V[i]->storeIntoOther( _rows[i] ); } @@ -100,13 +106,15 @@ void SparseUnsortedArrays::initialize( const SparseUnsortedList **V, unsigned m, _rows = new SparseUnsortedArray *[_m]; if ( !_rows ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "SparseUnsortedLists::rows" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "SparseUnsortedLists::rows" ); for ( unsigned i = 0; i < _m; ++i ) { _rows[i] = new SparseUnsortedArray; if ( !_rows[i] ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "SparseUnsortedLists::rows[i]" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "SparseUnsortedLists::rows[i]" ); _rows[i]->initializeFromList( V[i] ); } @@ -121,13 +129,15 @@ void SparseUnsortedArrays::initializeToEmpty( unsigned m, unsigned n ) _rows = new SparseUnsortedArray *[_m]; if ( !_rows ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "SparseUnsortedArrays::rows" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "SparseUnsortedArrays::rows" ); for ( unsigned i = 0; i < _m; ++i ) { _rows[i] = new SparseUnsortedArray( _n ); if ( !_rows[i] ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "SparseUnsortedArrays::rows[i]" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "SparseUnsortedArrays::rows[i]" ); } } @@ -179,13 +189,15 @@ void SparseUnsortedArrays::addLastRow( const double *row ) { SparseUnsortedArray **newRows = new SparseUnsortedArray *[_m + 1]; if ( !newRows ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "SparseUnsortedArrays::newRows" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "SparseUnsortedArrays::newRows" ); - memcpy( newRows, _rows, sizeof(SparseUnsortedArray *) * _m ); + memcpy( newRows, _rows, sizeof( SparseUnsortedArray * ) * _m ); newRows[_m] = new SparseUnsortedArray; if ( !newRows[_m] ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "ArrayOfCSRUnsortedLists::newRows[_m]" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "ArrayOfCSRUnsortedLists::newRows[_m]" ); newRows[_m]->initialize( row, _n ); @@ -273,13 +285,15 @@ void SparseUnsortedArrays::storeIntoOther( SparseUnsortedArrays *other ) const other->_rows = new SparseUnsortedArray *[_m]; if ( !other->_rows ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "SparseUnsortedArrays::otherRows" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "SparseUnsortedArrays::otherRows" ); for ( unsigned i = 0; i < _m; ++i ) { other->_rows[i] = new SparseUnsortedArray; if ( !other->_rows[i] ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "SparseUnsortedArrays::otherRows[i]" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "SparseUnsortedArrays::otherRows[i]" ); _rows[i]->storeIntoOther( other->_rows[i] ); } diff --git a/src/basis_factorization/SparseUnsortedList.cpp b/src/basis_factorization/SparseUnsortedList.cpp index 7f0af64c00..09d42dab22 100644 --- a/src/basis_factorization/SparseUnsortedList.cpp +++ b/src/basis_factorization/SparseUnsortedList.cpp @@ -13,10 +13,11 @@ **/ +#include "SparseUnsortedList.h" + #include "BasisFactorizationError.h" #include "Debug.h" #include "FloatUtils.h" -#include "SparseUnsortedList.h" SparseUnsortedList::SparseUnsortedList() : _size( 0 ) @@ -228,10 +229,11 @@ void SparseUnsortedList::mergeEntries( unsigned source, unsigned target ) _list.erase( sourceIt ); if ( FloatUtils::isZero( targetIt->_value ) ) - _list.erase( targetIt ); + _list.erase( targetIt ); } -List::iterator SparseUnsortedList::erase( List::iterator it ) +List::iterator +SparseUnsortedList::erase( List::iterator it ) { return _list.erase( it ); } diff --git a/src/basis_factorization/SparseUnsortedLists.cpp b/src/basis_factorization/SparseUnsortedLists.cpp index 982a83c907..1588beaa1f 100644 --- a/src/basis_factorization/SparseUnsortedLists.cpp +++ b/src/basis_factorization/SparseUnsortedLists.cpp @@ -13,10 +13,12 @@ **/ +#include "SparseUnsortedLists.h" + #include "BasisFactorizationError.h" #include "Debug.h" #include "FloatUtils.h" -#include "SparseUnsortedLists.h" + #include SparseUnsortedLists::SparseUnsortedLists() @@ -58,13 +60,15 @@ void SparseUnsortedLists::initialize( const double *M, unsigned m, unsigned n ) _rows = new SparseUnsortedList *[_m]; if ( !_rows ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "SparseUnsortedLists::rows" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "SparseUnsortedLists::rows" ); for ( unsigned i = 0; i < _m; ++i ) { _rows[i] = new SparseUnsortedList; if ( !_rows[i] ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "SparseUnsortedLists::rows[i]" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "SparseUnsortedLists::rows[i]" ); _rows[i]->initialize( M + ( i * n ), n ); } @@ -79,13 +83,15 @@ void SparseUnsortedLists::initialize( const SparseUnsortedList **V, unsigned m, _rows = new SparseUnsortedList *[_m]; if ( !_rows ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "SparseUnsortedLists::rows" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "SparseUnsortedLists::rows" ); for ( unsigned i = 0; i < _m; ++i ) { _rows[i] = new SparseUnsortedList; if ( !_rows[i] ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "SparseUnsortedLists::rows[i]" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "SparseUnsortedLists::rows[i]" ); V[i]->storeIntoOther( _rows[i] ); } @@ -100,13 +106,15 @@ void SparseUnsortedLists::initializeToEmpty( unsigned m, unsigned n ) _rows = new SparseUnsortedList *[_m]; if ( !_rows ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "SparseUnsortedLists::rows" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "SparseUnsortedLists::rows" ); for ( unsigned i = 0; i < _m; ++i ) { _rows[i] = new SparseUnsortedList( _n ); if ( !_rows[i] ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "SparseUnsortedLists::rows[i]" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "SparseUnsortedLists::rows[i]" ); } } @@ -158,13 +166,15 @@ void SparseUnsortedLists::addLastRow( const double *row ) { SparseUnsortedList **newRows = new SparseUnsortedList *[_m + 1]; if ( !newRows ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "SparseUnsortedLists::newRows" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "SparseUnsortedLists::newRows" ); - memcpy( newRows, _rows, sizeof(SparseUnsortedList *) * _m ); + memcpy( newRows, _rows, sizeof( SparseUnsortedList * ) * _m ); newRows[_m] = new SparseUnsortedList; if ( !newRows[_m] ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "ArrayOfCSRUnsortedLists::newRows[_m]" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "ArrayOfCSRUnsortedLists::newRows[_m]" ); newRows[_m]->initialize( row, _n ); @@ -200,7 +210,7 @@ void SparseUnsortedLists::countElements( unsigned *numRowElements, unsigned *num numRowElements[i] = _rows[i]->getNnz(); // Columns - for ( const auto &element : (*_rows[i]) ) + for ( const auto &element : ( *_rows[i] ) ) ++numColumnElements[element._index]; } } @@ -211,7 +221,7 @@ void SparseUnsortedLists::transposeIntoOther( SparseUnsortedLists *other ) for ( unsigned row = 0; row < _m; ++row ) { - for ( const auto &element : (*_rows[row]) ) + for ( const auto &element : ( *_rows[row] ) ) { other->_rows[element._index]->append( row, element._value ); } @@ -244,13 +254,15 @@ void SparseUnsortedLists::storeIntoOther( SparseUnsortedLists *other ) const other->_rows = new SparseUnsortedList *[_m]; if ( !other->_rows ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "SparseUnsortedLists::otherRows" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "SparseUnsortedLists::otherRows" ); for ( unsigned i = 0; i < _m; ++i ) { other->_rows[i] = new SparseUnsortedList; if ( !other->_rows[i] ) - throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, "SparseUnsortedLists::otherRows[i]" ); + throw BasisFactorizationError( BasisFactorizationError::ALLOCATION_FAILED, + "SparseUnsortedLists::otherRows[i]" ); _rows[i]->storeIntoOther( other->_rows[i] ); } diff --git a/src/basis_factorization/tests/MockColumnOracle.h b/src/basis_factorization/tests/MockColumnOracle.h index a24e127677..23bca82f0c 100644 --- a/src/basis_factorization/tests/MockColumnOracle.h +++ b/src/basis_factorization/tests/MockColumnOracle.h @@ -83,7 +83,7 @@ class MockColumnOracle : public IBasisFactorization::BasisColumnOracle unsigned _m; void getColumnOfBasis( unsigned column, double *result ) const { - memcpy( result, _basis + ( _m * column ), sizeof(double) * _m ); + memcpy( result, _basis + ( _m * column ), sizeof( double ) * _m ); } void getColumnOfBasis( unsigned column, SparseUnsortedList *result ) const diff --git a/src/basis_factorization/tests/Test_CSRMatrix.h b/src/basis_factorization/tests/Test_CSRMatrix.h index 0f05d8c185..2c92363519 100644 --- a/src/basis_factorization/tests/Test_CSRMatrix.h +++ b/src/basis_factorization/tests/Test_CSRMatrix.h @@ -13,12 +13,12 @@ **/ -#include - #include "CSRMatrix.h" #include "MString.h" #include "SparseUnsortedList.h" +#include + class MockForCSRMatrix { public: @@ -49,42 +49,32 @@ class CSRMatrixTestSuite : public CxxTest::TestSuite // Initialize through empty constructor and initialize(); double M1[] = { - 0, 0, 0, 0, - 5, 8, 0, 0, - 0, 0, 3, 0, - 0, 6, 0, 0, - }; + 0, 0, 0, 0, 5, 8, 0, 0, 0, 0, 3, 0, 0, 6, 0, 0, + }; CSRMatrix csr1; csr1.initialize( M1, 4, 4 ); for ( unsigned i = 0; i < 4; ++i ) for ( unsigned j = 0; j < 4; ++j ) - TS_ASSERT_EQUALS( M1[i*4 + j], csr1.get( i, j ) ); + TS_ASSERT_EQUALS( M1[i * 4 + j], csr1.get( i, j ) ); // Dense matrix, initialize through constructor double M2[] = { - 1, 2, 3, 4, - 5, 8, 5, 6, - 1, 2, 3, 4, - 5, 6, 7, 8, - 9, 1, 2, 3, - }; + 1, 2, 3, 4, 5, 8, 5, 6, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, + }; CSRMatrix csr2; csr2.initialize( M2, 5, 4 ); for ( unsigned i = 0; i < 5; ++i ) for ( unsigned j = 0; j < 4; ++j ) - TS_ASSERT_EQUALS( M2[i*4 + j], csr2.get( i, j ) ); + TS_ASSERT_EQUALS( M2[i * 4 + j], csr2.get( i, j ) ); } void test_store_restore() { double M1[] = { - 0, 0, 0, 0, - 5, 8, 0, 0, - 0, 0, 3, 0, - 0, 6, 0, 0, + 0, 0, 0, 0, 5, 8, 0, 0, 0, 0, 3, 0, 0, 6, 0, 0, }; CSRMatrix csr1; @@ -104,10 +94,7 @@ class CSRMatrixTestSuite : public CxxTest::TestSuite void test_add_last_row() { double M1[] = { - 0, 0, 0, 0, - 5, 8, 0, 0, - 0, 0, 3, 0, - 0, 6, 0, 0, + 0, 0, 0, 0, 5, 8, 0, 0, 0, 0, 3, 0, 0, 6, 0, 0, }; CSRMatrix csr1; @@ -122,28 +109,19 @@ class CSRMatrixTestSuite : public CxxTest::TestSuite csr1.addLastRow( row7 ); double expected[] = { - 0, 0, 0, 0, - 5, 8, 0, 0, - 0, 0, 3, 0, - 0, 6, 0, 0, - 1, 2, 0, 0, - 0, 2, -3, 0, - 1, 0, 0, 4, + 0, 0, 0, 0, 5, 8, 0, 0, 0, 0, 3, 0, 0, 6, 0, 0, 1, 2, 0, 0, 0, 2, -3, 0, 1, 0, 0, 4, }; for ( unsigned i = 0; i < 7; ++i ) for ( unsigned j = 0; j < 4; ++j ) - TS_ASSERT_EQUALS( csr1.get( i, j ), expected[i*4 + j] ); + TS_ASSERT_EQUALS( csr1.get( i, j ), expected[i * 4 + j] ); } void test_add_last_column() { { double M1[] = { - 0, 0, 0, 2, - 5, 8, 0, 0, - 0, 0, 3, 0, - 0, 6, 0, 0, + 0, 0, 0, 2, 5, 8, 0, 0, 0, 0, 3, 0, 0, 6, 0, 0, }; CSRMatrix csr1; @@ -158,25 +136,19 @@ class CSRMatrixTestSuite : public CxxTest::TestSuite csr1.addLastColumn( col7 ); double expected[] = { - 0, 0, 0, 2, 1, 0, 1, - 5, 8, 0, 0, 2, 2, 0, - 0, 0, 3, 0, 0, -3, 0, - 0, 6, 0, 0, 0, 0, 4, + 0, 0, 0, 2, 1, 0, 1, 5, 8, 0, 0, 2, 2, 0, 0, 0, 3, 0, 0, -3, 0, 0, 6, 0, 0, 0, 0, 4, }; for ( unsigned i = 0; i < 4; ++i ) for ( unsigned j = 0; j < 7; ++j ) - TS_ASSERT_EQUALS( csr1.get( i, j ), expected[i*7 + j] ); + TS_ASSERT_EQUALS( csr1.get( i, j ), expected[i * 7 + j] ); TS_ASSERT_EQUALS( csr1.getNnz(), 11U ); } { double M1[] = { - 0, 0, 0, 0, - 0, 0, 0, 0, - 0, 0, 0, 0, - 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; CSRMatrix csr1; @@ -186,15 +158,12 @@ class CSRMatrixTestSuite : public CxxTest::TestSuite csr1.addLastColumn( col5 ); double expected[] = { - 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; for ( unsigned i = 0; i < 4; ++i ) for ( unsigned j = 0; j < 5; ++j ) - TS_ASSERT_EQUALS( csr1.get( i, j ), expected[i*5 + j] ); + TS_ASSERT_EQUALS( csr1.get( i, j ), expected[i * 5 + j] ); TS_ASSERT_EQUALS( csr1.getNnz(), 0U ); } @@ -203,10 +172,7 @@ class CSRMatrixTestSuite : public CxxTest::TestSuite void test_get_row() { double M1[] = { - 0, 0, 0, 0, - 5, 8, 0, 0, - 0, 0, 3, 0, - 0, 6, 0, 0, + 0, 0, 0, 0, 5, 8, 0, 0, 0, 0, 3, 0, 0, 6, 0, 0, }; CSRMatrix csr1; @@ -230,10 +196,7 @@ class CSRMatrixTestSuite : public CxxTest::TestSuite { { double M1[] = { - 0, 0, 0, 0, - 5, 8, 0, 0, - 0, 0, 3, 0, - 0, 6, 0, 0, + 0, 0, 0, 0, 5, 8, 0, 0, 0, 0, 3, 0, 0, 6, 0, 0, }; CSRMatrix csr1; @@ -243,16 +206,12 @@ class CSRMatrixTestSuite : public CxxTest::TestSuite TS_ASSERT_THROWS_NOTHING( csr1.toDense( dense ) ); - TS_ASSERT_SAME_DATA( M1, dense, sizeof(M1) ); + TS_ASSERT_SAME_DATA( M1, dense, sizeof( M1 ) ); } { double M1[] = { - 0, 0, 0, 0, - 0, 0, 0, 0, - 5, 8, 0, 0, - 1, 2, 3, 4, - 0, 6, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 0, 0, 1, 2, 3, 4, 0, 6, 0, 0, }; CSRMatrix csr1; @@ -262,17 +221,14 @@ class CSRMatrixTestSuite : public CxxTest::TestSuite TS_ASSERT_THROWS_NOTHING( csr1.toDense( dense ) ); - TS_ASSERT_SAME_DATA( M1, dense, sizeof(M1) ); + TS_ASSERT_SAME_DATA( M1, dense, sizeof( M1 ) ); } } void test_get_column() { double M1[] = { - 0, 0, 0, 0, - 5, 8, 0, 0, - 0, 0, 3, 0, - 0, 6, 0, 0, + 0, 0, 0, 0, 5, 8, 0, 0, 0, 0, 3, 0, 0, 6, 0, 0, }; CSRMatrix csr1; @@ -304,10 +260,7 @@ class CSRMatrixTestSuite : public CxxTest::TestSuite { { double M1[] = { - 0, 0, 0, 0, - 5, 8, 0, 0, - 0, 2, 3, 0, - 0, 0, 4, 0, + 0, 0, 0, 0, 5, 8, 0, 0, 0, 2, 3, 0, 0, 0, 4, 0, }; CSRMatrix csr1; @@ -316,25 +269,19 @@ class CSRMatrixTestSuite : public CxxTest::TestSuite TS_ASSERT_THROWS_NOTHING( csr1.mergeColumns( 1, 2 ) ); double expected[] = { - 0, 0, 0, 0, - 5, 8, 0, 0, - 0, 5, 0, 0, - 0, 4, 0, 0, + 0, 0, 0, 0, 5, 8, 0, 0, 0, 5, 0, 0, 0, 4, 0, 0, }; for ( unsigned i = 0; i < 4; ++i ) for ( unsigned j = 0; j < 4; ++j ) - TS_ASSERT_EQUALS( csr1.get( i, j ), expected[i*4 + j] ); + TS_ASSERT_EQUALS( csr1.get( i, j ), expected[i * 4 + j] ); TS_ASSERT_EQUALS( csr1.getNnz(), 4U ); } { double M1[] = { - 0, 0, -1, 1, - 5, 8, 0, 1, - 0, 2, 3, 0, - 0, 0, 4, 1, + 0, 0, -1, 1, 5, 8, 0, 1, 0, 2, 3, 0, 0, 0, 4, 1, }; CSRMatrix csr1; @@ -343,15 +290,12 @@ class CSRMatrixTestSuite : public CxxTest::TestSuite TS_ASSERT_THROWS_NOTHING( csr1.mergeColumns( 2, 3 ) ); double expected[] = { - 0, 0, 0, 0, - 5, 8, 1, 0, - 0, 2, 3, 0, - 0, 0, 5, 0, + 0, 0, 0, 0, 5, 8, 1, 0, 0, 2, 3, 0, 0, 0, 5, 0, }; for ( unsigned i = 0; i < 4; ++i ) for ( unsigned j = 0; j < 4; ++j ) - TS_ASSERT_EQUALS( csr1.get( i, j ), expected[i*4 + j] ); + TS_ASSERT_EQUALS( csr1.get( i, j ), expected[i * 4 + j] ); TS_ASSERT_EQUALS( csr1.getNnz(), 6U ); @@ -359,26 +303,19 @@ class CSRMatrixTestSuite : public CxxTest::TestSuite TS_ASSERT_THROWS_NOTHING( csr1.addLastRow( newRow ) ); double expected2[] = { - 0, 0, 0, 0, - 5, 8, 1, 0, - 0, 2, 3, 0, - 0, 0, 5, 0, - 1, 2, 3, 5, + 0, 0, 0, 0, 5, 8, 1, 0, 0, 2, 3, 0, 0, 0, 5, 0, 1, 2, 3, 5, }; for ( unsigned i = 0; i < 5; ++i ) for ( unsigned j = 0; j < 4; ++j ) - TS_ASSERT_EQUALS( csr1.get( i, j ), expected2[i*4 + j] ); + TS_ASSERT_EQUALS( csr1.get( i, j ), expected2[i * 4 + j] ); TS_ASSERT_EQUALS( csr1.getNnz(), 10U ); } { double M1[] = { - 0, 0, -1, 1, - 0, 0, -1, 1, - 0, 0, 0, 0, - 0, 0, -1, 1, + 0, 0, -1, 1, 0, 0, -1, 1, 0, 0, 0, 0, 0, 0, -1, 1, }; CSRMatrix csr1; @@ -387,25 +324,19 @@ class CSRMatrixTestSuite : public CxxTest::TestSuite TS_ASSERT_THROWS_NOTHING( csr1.mergeColumns( 2, 3 ) ); double expected[] = { - 0, 0, 0, 0, - 0, 0, 0, 0, - 0, 0, 0, 0, - 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; for ( unsigned i = 0; i < 4; ++i ) for ( unsigned j = 0; j < 4; ++j ) - TS_ASSERT_EQUALS( csr1.get( i, j ), expected[i*4 + j] ); + TS_ASSERT_EQUALS( csr1.get( i, j ), expected[i * 4 + j] ); TS_ASSERT_EQUALS( csr1.getNnz(), 0U ); } { double M1[] = { - 0, 0, 0, 0, - 5, 8, 0, 0, - 0, 2, 3, 1, - 0, 0, 4, 0, + 0, 0, 0, 0, 5, 8, 0, 0, 0, 2, 3, 1, 0, 0, 4, 0, }; CSRMatrix csr1; @@ -414,25 +345,19 @@ class CSRMatrixTestSuite : public CxxTest::TestSuite TS_ASSERT_THROWS_NOTHING( csr1.mergeColumns( 0, 3 ) ); double expected[] = { - 0, 0, 0, 0, - 5, 8, 0, 0, - 1, 2, 3, 0, - 0, 0, 4, 0, + 0, 0, 0, 0, 5, 8, 0, 0, 1, 2, 3, 0, 0, 0, 4, 0, }; for ( unsigned i = 0; i < 4; ++i ) for ( unsigned j = 0; j < 4; ++j ) - TS_ASSERT_EQUALS( csr1.get( i, j ), expected[i*4 + j] ); + TS_ASSERT_EQUALS( csr1.get( i, j ), expected[i * 4 + j] ); TS_ASSERT_EQUALS( csr1.getNnz(), 6U ); } { double M1[] = { - 0, 0, 0, 0, - 5, 8, 0, 0, - 0, 2, 3, 1, - 0, 0, 4, 0, + 0, 0, 0, 0, 5, 8, 0, 0, 0, 2, 3, 1, 0, 0, 4, 0, }; CSRMatrix csr1; @@ -441,15 +366,12 @@ class CSRMatrixTestSuite : public CxxTest::TestSuite TS_ASSERT_THROWS_NOTHING( csr1.mergeColumns( 0, 1 ) ); double expected[] = { - 0, 0, 0, 0, - 13, 0, 0, 0, - 2, 0, 3, 1, - 0, 0, 4, 0, + 0, 0, 0, 0, 13, 0, 0, 0, 2, 0, 3, 1, 0, 0, 4, 0, }; for ( unsigned i = 0; i < 4; ++i ) for ( unsigned j = 0; j < 4; ++j ) - TS_ASSERT_EQUALS( csr1.get( i, j ), expected[i*4 + j] ); + TS_ASSERT_EQUALS( csr1.get( i, j ), expected[i * 4 + j] ); TS_ASSERT_EQUALS( csr1.getNnz(), 5U ); } @@ -458,17 +380,11 @@ class CSRMatrixTestSuite : public CxxTest::TestSuite void test_deletions() { double M1[] = { - 0, 0, 0, 0, - 5, 8, 0, 0, - 0, 0, 3, 0, - 0, 6, 0, 0, + 0, 0, 0, 0, 5, 8, 0, 0, 0, 0, 3, 0, 0, 6, 0, 0, }; double expected[] = { - 0, 0, 0, 0, - 0, 8, 0, 0, - 0, 0, 3, 0, - 0, 0, 0, 0, + 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, }; CSRMatrix csr1; @@ -480,13 +396,13 @@ class CSRMatrixTestSuite : public CxxTest::TestSuite // No changes before "execute" is called for ( unsigned i = 0; i < 4; ++i ) for ( unsigned j = 0; j < 4; ++j ) - TS_ASSERT_EQUALS( csr1.get( i, j ), M1[i*4 + j] ); + TS_ASSERT_EQUALS( csr1.get( i, j ), M1[i * 4 + j] ); TS_ASSERT_THROWS_NOTHING( csr1.executeChanges() ); for ( unsigned i = 0; i < 4; ++i ) for ( unsigned j = 0; j < 4; ++j ) - TS_ASSERT_EQUALS( csr1.get( i, j ), expected[i*4 + j] ); + TS_ASSERT_EQUALS( csr1.get( i, j ), expected[i * 4 + j] ); // Fake elements csr1.commitChange( 1, 3, 0.0 ); @@ -495,7 +411,7 @@ class CSRMatrixTestSuite : public CxxTest::TestSuite for ( unsigned i = 0; i < 4; ++i ) for ( unsigned j = 0; j < 4; ++j ) - TS_ASSERT_EQUALS( csr1.get( i, j ), expected[i*4 + j] ); + TS_ASSERT_EQUALS( csr1.get( i, j ), expected[i * 4 + j] ); csr1.commitChange( 1, 1, 0.0 ); csr1.commitChange( 2, 2, 0.0 ); @@ -509,24 +425,15 @@ class CSRMatrixTestSuite : public CxxTest::TestSuite void test_changes() { double M1[] = { - 0, 0, 0, 0, - 5, 8, 0, 0, - 0, 0, 3, 0, - 0, 6, 0, 0, + 0, 0, 0, 0, 5, 8, 0, 0, 0, 0, 3, 0, 0, 6, 0, 0, }; double expected[] = { - 0, 0, 2, 0, - 5, 8, 0, 0, - 0, 0, 4, 0, - 0, 6, 0, 3, + 0, 0, 2, 0, 5, 8, 0, 0, 0, 0, 4, 0, 0, 6, 0, 3, }; double expected2[] = { - 0, 0, 5, 0, - 5, 8, 0, 0, - 1.5, 0, 4, 0, - 0, 6, 0, 3, + 0, 0, 5, 0, 5, 8, 0, 0, 1.5, 0, 4, 0, 0, 6, 0, 3, }; CSRMatrix csr1; @@ -539,13 +446,13 @@ class CSRMatrixTestSuite : public CxxTest::TestSuite // No changes before "execute" is called for ( unsigned i = 0; i < 4; ++i ) for ( unsigned j = 0; j < 4; ++j ) - TS_ASSERT_EQUALS( csr1.get( i, j ), M1[i*4 + j] ); + TS_ASSERT_EQUALS( csr1.get( i, j ), M1[i * 4 + j] ); TS_ASSERT_THROWS_NOTHING( csr1.executeChanges() ); for ( unsigned i = 0; i < 4; ++i ) for ( unsigned j = 0; j < 4; ++j ) - TS_ASSERT_EQUALS( csr1.get( i, j ), expected[i*4 + j] ); + TS_ASSERT_EQUALS( csr1.get( i, j ), expected[i * 4 + j] ); csr1.commitChange( 0, 2, 5.0 ); csr1.commitChange( 2, 0, 1.5 ); @@ -554,30 +461,21 @@ class CSRMatrixTestSuite : public CxxTest::TestSuite for ( unsigned i = 0; i < 4; ++i ) for ( unsigned j = 0; j < 4; ++j ) - TS_ASSERT_EQUALS( csr1.get( i, j ), expected2[i*4 + j] ); + TS_ASSERT_EQUALS( csr1.get( i, j ), expected2[i * 4 + j] ); } void test_changes_and_deletions() { double M1[] = { - 0, 0, 0, 0, - 5, 8, 0, 0, - 0, 0, 3, 0, - 0, 6, 0, 0, + 0, 0, 0, 0, 5, 8, 0, 0, 0, 0, 3, 0, 0, 6, 0, 0, }; double expected[] = { - 0, 0, 2, 0, - 5, 0, 0, 0, - 0, 0, 4, 0, - 0, 0, 0, 3, + 0, 0, 2, 0, 5, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 3, }; double expected2[] = { - 0, 0, 2, 0, - 5, 4, 0, 0, - 0, 0, 4, 0, - 0, 0, 0, 0, + 0, 0, 2, 0, 5, 4, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, }; CSRMatrix csr1; @@ -595,13 +493,13 @@ class CSRMatrixTestSuite : public CxxTest::TestSuite // No changes before "execute" is called for ( unsigned i = 0; i < 4; ++i ) for ( unsigned j = 0; j < 4; ++j ) - TS_ASSERT_EQUALS( csr1.get( i, j ), M1[i*4 + j] ); + TS_ASSERT_EQUALS( csr1.get( i, j ), M1[i * 4 + j] ); TS_ASSERT_THROWS_NOTHING( csr1.executeChanges() ); for ( unsigned i = 0; i < 4; ++i ) for ( unsigned j = 0; j < 4; ++j ) - TS_ASSERT_EQUALS( csr1.get( i, j ), expected[i*4 + j] ); + TS_ASSERT_EQUALS( csr1.get( i, j ), expected[i * 4 + j] ); csr1.commitChange( 1, 0, 5.0 ); @@ -613,16 +511,13 @@ class CSRMatrixTestSuite : public CxxTest::TestSuite for ( unsigned i = 0; i < 4; ++i ) for ( unsigned j = 0; j < 4; ++j ) - TS_ASSERT_EQUALS( csr1.get( i, j ), expected2[i*4 + j] ); + TS_ASSERT_EQUALS( csr1.get( i, j ), expected2[i * 4 + j] ); } void test_count_elements() { double M1[] = { - 0, 0, 0, 0, 1, - 5, 8, 0, 0, 2, - 0, 2, 3, 0, 3, - 0, 0, 4, 0, 4, + 0, 0, 0, 0, 1, 5, 8, 0, 0, 2, 0, 2, 3, 0, 3, 0, 0, 4, 0, 4, }; CSRMatrix csr1; @@ -648,10 +543,7 @@ class CSRMatrixTestSuite : public CxxTest::TestSuite void test_transpose() { double M1[] = { - 0, 0, 0, 0, 1, - 5, 8, 0, 0, 2, - 0, 2, 3, 0, 3, - 0, 0, 4, 0, 4, + 0, 0, 0, 0, 1, 5, 8, 0, 0, 2, 0, 2, 3, 0, 3, 0, 0, 4, 0, 4, }; CSRMatrix csr1; @@ -661,29 +553,23 @@ class CSRMatrixTestSuite : public CxxTest::TestSuite TS_ASSERT_THROWS_NOTHING( csr1.transposeIntoOther( &csr2 ) ); double expected[] = { - 0, 5, 0, 0, - 0, 8, 2, 0, - 0, 0, 3, 4, - 0, 0, 0, 0, - 1, 2, 3, 4, + 0, 5, 0, 0, 0, 8, 2, 0, 0, 0, 3, 4, 0, 0, 0, 0, 1, 2, 3, 4, }; for ( unsigned i = 0; i < 5; ++i ) for ( unsigned j = 0; j < 4; ++j ) - TS_ASSERT_EQUALS( csr2.get( i, j ), expected[i*4 + j] ); + TS_ASSERT_EQUALS( csr2.get( i, j ), expected[i * 4 + j] ); CSRMatrix csr3; TS_ASSERT_THROWS_NOTHING( csr2.transposeIntoOther( &csr3 ) ); for ( unsigned i = 0; i < 4; ++i ) for ( unsigned j = 0; j < 5; ++j ) - TS_ASSERT_EQUALS( csr3.get( i, j ), M1[i*5 + j] ); + TS_ASSERT_EQUALS( csr3.get( i, j ), M1[i * 5 + j] ); // Transpose an empty matrix double empty[] = { - 0, 0, - 0, 0, - 0, 0, + 0, 0, 0, 0, 0, 0, }; CSRMatrix csr4; @@ -700,10 +586,7 @@ class CSRMatrixTestSuite : public CxxTest::TestSuite void test_clear() { double M1[] = { - 0, 0, 0, 0, - 5, 8, 0, 0, - 0, 0, 3, 0, - 0, 6, 0, 0, + 0, 0, 0, 0, 5, 8, 0, 0, 0, 0, 3, 0, 0, 6, 0, 0, }; CSRMatrix csr1; diff --git a/src/basis_factorization/tests/Test_CompareFactorizations.h b/src/basis_factorization/tests/Test_CompareFactorizations.h index dd864a7fcd..d368889c46 100644 --- a/src/basis_factorization/tests/Test_CompareFactorizations.h +++ b/src/basis_factorization/tests/Test_CompareFactorizations.h @@ -13,8 +13,6 @@ **/ -#include - #include "FloatUtils.h" #include "ForrestTomlinFactorization.h" #include "LUFactorization.h" @@ -23,6 +21,8 @@ #include "SparseFTFactorization.h" #include "SparseLUFactorization.h" +#include + class MockForCompareFactorizations { public: @@ -58,13 +58,7 @@ class CompareFactorizationsTestSuite : public CxxTest::TestSuite TS_ASSERT( sft = new SparseFTFactorization( 4, *oracle ) ); TS_ASSERT( slu = new SparseLUFactorization( 4, *oracle ) ); - double B[] = - { - 2, 0, 3, -4, - 0, 1, 10, 0, - -3, 4.5, 1, 1, - 0, 0, 2, 2 - }; + double B[] = { 2, 0, 3, -4, 0, 1, 10, 0, -3, 4.5, 1, 1, 0, 0, 2, 2 }; oracle->storeBasis( 4, B ); ft->obtainFreshBasis(); @@ -149,10 +143,7 @@ class CompareFactorizationsTestSuite : public CxxTest::TestSuite } double basisAtThisPoint[] = { - 2, -20, 64, -4, - 0, 2, 96, 0, - -3, 24, -45, 1, - 0, 6, 14, 2, + 2, -20, 64, -4, 0, 2, 96, 0, -3, 24, -45, 1, 0, 6, 14, 2, }; oracle->storeBasis( 4, basisAtThisPoint ); diff --git a/src/basis_factorization/tests/Test_ForrestTomlinFactorization.h b/src/basis_factorization/tests/Test_ForrestTomlinFactorization.h index a62aaf695f..fdba924989 100644 --- a/src/basis_factorization/tests/Test_ForrestTomlinFactorization.h +++ b/src/basis_factorization/tests/Test_ForrestTomlinFactorization.h @@ -13,8 +13,6 @@ **/ -#include - #include "BasisFactorizationError.h" #include "EtaMatrix.h" #include "FloatUtils.h" @@ -24,6 +22,8 @@ #include "MockColumnOracle.h" #include "MockErrno.h" +#include + class MockForForrestTomlinFactorization { public: @@ -63,10 +63,7 @@ class ForrestTomlinFactorizationTestSuite : public CxxTest::TestSuite TS_ASSERT( ft = new ForrestTomlinFactorization( 4, *oracle ) ); double basisMatrix[16] = { - 1, 3, -2, 4, - 1, 5, -1, 5, - 1, 3, -3, 6, - -1, -3, 3, -8, + 1, 3, -2, 4, 1, 5, -1, 5, 1, 3, -3, 6, -1, -3, 3, -8, }; oracle->storeBasis( 4, basisMatrix ); @@ -167,14 +164,14 @@ class ForrestTomlinFactorizationTestSuite : public CxxTest::TestSuite const List *LP = ft->getLP(); TS_ASSERT_EQUALS( LP->size(), 4U ); auto lIt = LP->begin(); - TS_ASSERT( (*lIt)->_eta ); - TS_ASSERT_EQUALS( *((*lIt)->_eta), expectedL4 ); + TS_ASSERT( ( *lIt )->_eta ); + TS_ASSERT_EQUALS( *( ( *lIt )->_eta ), expectedL4 ); ++lIt; - TS_ASSERT_EQUALS( *((*lIt)->_eta), expectedL3 ); + TS_ASSERT_EQUALS( *( ( *lIt )->_eta ), expectedL3 ); ++lIt; - TS_ASSERT_EQUALS( *((*lIt)->_eta), expectedL2 ); + TS_ASSERT_EQUALS( *( ( *lIt )->_eta ), expectedL2 ); ++lIt; - TS_ASSERT_EQUALS( *((*lIt)->_eta), expectedL1 ); + TS_ASSERT_EQUALS( *( ( *lIt )->_eta ), expectedL1 ); TS_ASSERT_THROWS_NOTHING( delete ft ); } @@ -186,10 +183,7 @@ class ForrestTomlinFactorizationTestSuite : public CxxTest::TestSuite TS_ASSERT( ft = new ForrestTomlinFactorization( 4, *oracle ) ); double basisMatrix[16] = { - 1, 4, -2, 4, - -2, -6, -1, 5, - 1, 3, -3, 6, - -1, -3, 3, -8, + 1, 4, -2, 4, -2, -6, -1, 5, 1, 3, -3, 6, -1, -3, 3, -8, }; oracle->storeBasis( 4, basisMatrix ); @@ -261,7 +255,7 @@ class ForrestTomlinFactorizationTestSuite : public CxxTest::TestSuite So L3 has the column (0, 0, -2/7, 1) */ - double expectedL4Col[] = { 0, 0, -2.0/7, 1 }; + double expectedL4Col[] = { 0, 0, -2.0 / 7, 1 }; EtaMatrix expectedL4( 4, 2, expectedL4Col ); /* @@ -280,7 +274,7 @@ class ForrestTomlinFactorizationTestSuite : public CxxTest::TestSuite EtaMatrix expectedL5( 4, 3, expectedL5Col ); // The upper traingular matrix discovered gives us the Us - double expectedU4Col[] = { -2.5, 6.5, -17.0/7, 1 }; + double expectedU4Col[] = { -2.5, 6.5, -17.0 / 7, 1 }; EtaMatrix expectedU4( 4, 3, expectedU4Col ); double expectedU3Col[] = { 0.5, -2.5, 1, 0 }; @@ -302,16 +296,16 @@ class ForrestTomlinFactorizationTestSuite : public CxxTest::TestSuite const List *LP = ft->getLP(); TS_ASSERT_EQUALS( LP->size(), 5U ); auto lIt = LP->begin(); - TS_ASSERT( (*lIt)->_eta ); - TS_ASSERT_EQUALS( *((*lIt)->_eta), expectedL5 ); + TS_ASSERT( ( *lIt )->_eta ); + TS_ASSERT_EQUALS( *( ( *lIt )->_eta ), expectedL5 ); ++lIt; - TS_ASSERT_EQUALS( *((*lIt)->_eta), expectedL4 ); + TS_ASSERT_EQUALS( *( ( *lIt )->_eta ), expectedL4 ); ++lIt; - TS_ASSERT_EQUALS( *((*lIt)->_eta), expectedL3 ); + TS_ASSERT_EQUALS( *( ( *lIt )->_eta ), expectedL3 ); ++lIt; - TS_ASSERT_EQUALS( *((*lIt)->_eta), expectedL2 ); + TS_ASSERT_EQUALS( *( ( *lIt )->_eta ), expectedL2 ); ++lIt; - TS_ASSERT_EQUALS( *((*lIt)->_pair), P1pair ); + TS_ASSERT_EQUALS( *( ( *lIt )->_pair ), P1pair ); TS_ASSERT_THROWS_NOTHING( delete ft ); } @@ -323,10 +317,7 @@ class ForrestTomlinFactorizationTestSuite : public CxxTest::TestSuite TS_ASSERT( ft = new ForrestTomlinFactorization( 4, *oracle ) ); double basisMatrix[16] = { - 1, 3, -2, 4, - 1, 5, -1, 5, - 1, 3, -3, 6, - -1, -3, 3, -8, + 1, 3, -2, 4, 1, 5, -1, 5, 1, 3, -3, 6, -1, -3, 3, -8, }; oracle->storeBasis( 4, basisMatrix ); @@ -454,10 +445,7 @@ class ForrestTomlinFactorizationTestSuite : public CxxTest::TestSuite TS_ASSERT( ft = new ForrestTomlinFactorization( 4, *oracle ) ); double basisMatrix[16] = { - 1, 3, -2, 4, - 1, 5, -1, 5, - 1, 3, -3, 6, - -1, -3, 3, -8, + 1, 3, -2, 4, 1, 5, -1, 5, 1, 3, -3, 6, -1, -3, 3, -8, }; oracle->storeBasis( 4, basisMatrix ); @@ -600,10 +588,7 @@ class ForrestTomlinFactorizationTestSuite : public CxxTest::TestSuite // | 1 3 -3 6 | // | -1 -3 3 -8 | double basisMatrix[16] = { - 1, 3, -2, 4, - 1, 5, -1, 5, - 1, 3, -3, 6, - -1, -3, 3, -8, + 1, 3, -2, 4, 1, 5, -1, 5, 1, 3, -3, 6, -1, -3, 3, -8, }; oracle->storeBasis( 4, basisMatrix ); @@ -740,14 +725,14 @@ class ForrestTomlinFactorizationTestSuite : public CxxTest::TestSuite const List *LP = ft->getLP(); TS_ASSERT_EQUALS( LP->size(), 4U ); auto lIt = LP->begin(); - TS_ASSERT( (*lIt)->_eta ); - TS_ASSERT_EQUALS( *((*lIt)->_eta), expectedL4 ); + TS_ASSERT( ( *lIt )->_eta ); + TS_ASSERT_EQUALS( *( ( *lIt )->_eta ), expectedL4 ); ++lIt; - TS_ASSERT_EQUALS( *((*lIt)->_eta), expectedL3 ); + TS_ASSERT_EQUALS( *( ( *lIt )->_eta ), expectedL3 ); ++lIt; - TS_ASSERT_EQUALS( *((*lIt)->_eta), expectedL2 ); + TS_ASSERT_EQUALS( *( ( *lIt )->_eta ), expectedL2 ); ++lIt; - TS_ASSERT_EQUALS( *((*lIt)->_eta), expectedL1 ); + TS_ASSERT_EQUALS( *( ( *lIt )->_eta ), expectedL1 ); double expectedU4Col[] = { 14, -6, 3, 1 }; EtaMatrix expectedU4( 4, 3, expectedU4Col ); @@ -787,19 +772,19 @@ class ForrestTomlinFactorizationTestSuite : public CxxTest::TestSuite auto it = A->begin(); - TS_ASSERT_EQUALS( (*it)->_row, 1U ); - TS_ASSERT_EQUALS( (*it)->_column, 2U ); - TS_ASSERT( FloatUtils::areEqual( (*it)->_value, -0.5 ) ); + TS_ASSERT_EQUALS( ( *it )->_row, 1U ); + TS_ASSERT_EQUALS( ( *it )->_column, 2U ); + TS_ASSERT( FloatUtils::areEqual( ( *it )->_value, -0.5 ) ); ++it; - TS_ASSERT_EQUALS( (*it)->_row, 1U ); - TS_ASSERT_EQUALS( (*it)->_column, 3U ); - TS_ASSERT( FloatUtils::areEqual( (*it)->_value, -1.5 ) ); + TS_ASSERT_EQUALS( ( *it )->_row, 1U ); + TS_ASSERT_EQUALS( ( *it )->_column, 3U ); + TS_ASSERT( FloatUtils::areEqual( ( *it )->_value, -1.5 ) ); ++it; - TS_ASSERT_EQUALS( (*it)->_row, 1U ); - TS_ASSERT_EQUALS( (*it)->_column, 1U ); - TS_ASSERT( FloatUtils::areEqual( (*it)->_value, 0.5 ) ); + TS_ASSERT_EQUALS( ( *it )->_row, 1U ); + TS_ASSERT_EQUALS( ( *it )->_column, 1U ); + TS_ASSERT( FloatUtils::areEqual( ( *it )->_value, 0.5 ) ); TS_ASSERT_THROWS_NOTHING( delete ft ); } @@ -811,10 +796,7 @@ class ForrestTomlinFactorizationTestSuite : public CxxTest::TestSuite TS_ASSERT( ft = new ForrestTomlinFactorization( 4, *oracle ) ); double basisMatrix[16] = { - 1, 3, -2, 4, - 1, 5, -1, 5, - 1, 3, -3, 6, - -1, -3, 3, -8, + 1, 3, -2, 4, 1, 5, -1, 5, 1, 3, -3, 6, -1, -3, 3, -8, }; oracle->storeBasis( 4, basisMatrix ); @@ -860,10 +842,7 @@ class ForrestTomlinFactorizationTestSuite : public CxxTest::TestSuite // | 1 3 -3 6 | // | -1 -3 3 -8 | double basisMatrix[16] = { - 1, 3, -2, 4, - 1, 5, -1, 5, - 1, 3, -3, 6, - -1, -3, 3, -8, + 1, 3, -2, 4, 1, 5, -1, 5, 1, 3, -3, 6, -1, -3, 3, -8, }; oracle->storeBasis( 4, basisMatrix ); @@ -888,10 +867,7 @@ class ForrestTomlinFactorizationTestSuite : public CxxTest::TestSuite // | -1 -26 3 -8 | double expectedB[16] = { - 1, 14, -2, 4, - 1, 21, -1, 5, - 1, 20, -3, 6, - -1, -26, 3, -8, + 1, 14, -2, 4, 1, 21, -1, 5, 1, 20, -3, 6, -1, -26, 3, -8, }; oracle->storeBasis( 4, expectedB ); @@ -920,10 +896,7 @@ class ForrestTomlinFactorizationTestSuite : public CxxTest::TestSuite // | 1 3 -3 6 | // | -1 -3 3 -8 | double basisMatrix[16] = { - 1, 3, -2, 4, - 1, 5, -1, 5, - 1, 3, -3, 6, - -1, -3, 3, -8, + 1, 3, -2, 4, 1, 5, -1, 5, 1, 3, -3, 6, -1, -3, 3, -8, }; oracle->storeBasis( 4, basisMatrix ); @@ -934,10 +907,8 @@ class ForrestTomlinFactorizationTestSuite : public CxxTest::TestSuite // | 1 0 -2 -1 | // | 0 0 -1/2 -1/2 | double expectedInvB1[] = { - 6, -3.0/2, -23.0/4, -9.0/4, - -1, 1.0/2, 5.0/4, 3.0/4, - 1, 0, -2, -1, - 0, 0, -1.0/2, -1.0/2, + 6, -3.0 / 2, -23.0 / 4, -9.0 / 4, -1, 1.0 / 2, 5.0 / 4, 3.0 / 4, + 1, 0, -2, -1, 0, 0, -1.0 / 2, -1.0 / 2, }; double invB[16]; @@ -959,10 +930,7 @@ class ForrestTomlinFactorizationTestSuite : public CxxTest::TestSuite // | -1 -26 3 -8 | double expectedB[16] = { - 1, 14, -2, 4, - 1, 21, -1, 5, - 1, 20, -3, 6, - -1, -26, 3, -8, + 1, 14, -2, 4, 1, 21, -1, 5, 1, 20, -3, 6, -1, -26, 3, -8, }; oracle->storeBasis( 4, expectedB ); @@ -973,16 +941,15 @@ class ForrestTomlinFactorizationTestSuite : public CxxTest::TestSuite // | 3/2 -3/4 -19/8 -13/8 | double expectedInvB2[] = { - 4, -1.0/2, -13.0/4, -3.0/4, - -1.0/2, 1.0/4, 5.0/8, 3.0/8, - 1, 0, -2, -1, - 3.0/2, -3.0/4, -19.0/8, -13.0/8, + 4, -1.0 / 2, -13.0 / 4, -3.0 / 4, -1.0 / 2, 1.0 / 4, 5.0 / 8, 3.0 / 8, + 1, 0, -2, -1, 3.0 / 2, -3.0 / 4, -19.0 / 8, -13.0 / 8, }; - TS_ASSERT_THROWS_EQUALS( ft->invertBasis( invB ), - const BasisFactorizationError &e, - e.getCode(), - BasisFactorizationError::CANT_INVERT_BASIS_BECAUSE_BASIS_ISNT_AVAILABLE ); + TS_ASSERT_THROWS_EQUALS( + ft->invertBasis( invB ), + const BasisFactorizationError &e, + e.getCode(), + BasisFactorizationError::CANT_INVERT_BASIS_BECAUSE_BASIS_ISNT_AVAILABLE ); TS_ASSERT_THROWS_NOTHING( ft->makeExplicitBasisAvailable() ); diff --git a/src/basis_factorization/tests/Test_GaussianEliminator.h b/src/basis_factorization/tests/Test_GaussianEliminator.h index d09a26c2a2..5008546665 100644 --- a/src/basis_factorization/tests/Test_GaussianEliminator.h +++ b/src/basis_factorization/tests/Test_GaussianEliminator.h @@ -13,13 +13,13 @@ **/ -#include - #include "BasisFactorizationError.h" #include "EtaMatrix.h" #include "FloatUtils.h" #include "GaussianEliminator.h" + #include +#include class MockForGaussianEliminator { @@ -50,10 +50,10 @@ class GaussianEliminatorTestSuite : public CxxTest::TestSuite { for ( unsigned j = 0; j < m; ++j ) { - result[i*m + j] = 0; + result[i * m + j] = 0; for ( unsigned k = 0; k < m; ++k ) { - result[i*m + j] += lu->_F[i*m + k] * lu->_V[k*m + j]; + result[i * m + j] += lu->_F[i * m + k] * lu->_V[k * m + j]; } } } @@ -69,7 +69,7 @@ class GaussianEliminatorTestSuite : public CxxTest::TestSuite printf( "\t" ); for ( unsigned j = 0; j < m; ++j ) { - printf( "%8.lf ", matrix[i*m + j] ); + printf( "%8.lf ", matrix[i * m + j] ); } printf( "\n" ); } @@ -83,12 +83,7 @@ class GaussianEliminatorTestSuite : public CxxTest::TestSuite LUFactors lu4( 4 ); { - double A[] = - { - 2, 3, 0, - 0, 1, 0, - 0, 0, 1 - }; + double A[] = { 2, 3, 0, 0, 1, 0, 0, 0, 1 }; GaussianEliminator *ge; @@ -107,12 +102,7 @@ class GaussianEliminatorTestSuite : public CxxTest::TestSuite } { - double A[] = - { - 2, 3, 0, - 0, 1, 2, - 0, 4, 1 - }; + double A[] = { 2, 3, 0, 0, 1, 2, 0, 4, 1 }; GaussianEliminator *ge; @@ -131,12 +121,7 @@ class GaussianEliminatorTestSuite : public CxxTest::TestSuite } { - double A[] = - { - 2, 3, -4, - -5, 1, 2, - 0, 4, 1 - }; + double A[] = { 2, 3, -4, -5, 1, 2, 0, 4, 1 }; GaussianEliminator *ge; @@ -155,12 +140,8 @@ class GaussianEliminatorTestSuite : public CxxTest::TestSuite } { - double A[] = - { - 2, 3, -4, 0, - -5, 1, 2, 2, - 0, 4, 1, -5, - 1, 2, 3, 4, + double A[] = { + 2, 3, -4, 0, -5, 1, 2, 2, 0, 4, 1, -5, 1, 2, 3, 4, }; GaussianEliminator *ge; @@ -180,12 +161,7 @@ class GaussianEliminatorTestSuite : public CxxTest::TestSuite } { - double A[] = - { - 2, 3, 0, - 0, 1, 0, - 5, 4, 0 - }; + double A[] = { 2, 3, 0, 0, 1, 0, 5, 4, 0 }; GaussianEliminator *ge; @@ -199,12 +175,7 @@ class GaussianEliminatorTestSuite : public CxxTest::TestSuite } { - double A[] = - { - 2, 3, 7, - 0, 0, 0, - 5, 4, 0 - }; + double A[] = { 2, 3, 7, 0, 0, 0, 5, 4, 0 }; GaussianEliminator *ge; diff --git a/src/basis_factorization/tests/Test_LUFactorization.h b/src/basis_factorization/tests/Test_LUFactorization.h index 840b1dfaa5..98f8130aef 100644 --- a/src/basis_factorization/tests/Test_LUFactorization.h +++ b/src/basis_factorization/tests/Test_LUFactorization.h @@ -13,8 +13,6 @@ **/ -#include - #include "BasisFactorizationError.h" #include "EtaMatrix.h" #include "FloatUtils.h" @@ -24,6 +22,8 @@ #include "MockColumnOracle.h" #include "MockErrno.h" +#include + void matrixMultiply( unsigned dimension, const double *left, const double *right, double *result ) { for ( unsigned leftRow = 0; leftRow < dimension; ++leftRow ) @@ -67,9 +67,7 @@ class LUFactorizationTestSuite : public CxxTest::TestSuite LUFactorization basis( 3, *oracle ); double B[] = { - 1, 0, 0, - 0, 1, 0, - 0, 0, 1, + 1, 0, 0, 0, 1, 0, 0, 0, 1, }; oracle->storeBasis( 3, B ); basis.obtainFreshBasis(); @@ -80,7 +78,7 @@ class LUFactorizationTestSuite : public CxxTest::TestSuite double expected1[] = { 1, 1, 3 }; TS_ASSERT_THROWS_NOTHING( basis.forwardTransformation( a1, d1 ) ); - TS_ASSERT_SAME_DATA( d1, expected1, sizeof(double) * 3 ); + TS_ASSERT_SAME_DATA( d1, expected1, sizeof( double ) * 3 ); // E1 = | 1 1 | // | 1 | @@ -98,7 +96,7 @@ class LUFactorizationTestSuite : public CxxTest::TestSuite // --> d = [ 2 1 1 ]^T TS_ASSERT_THROWS_NOTHING( basis.forwardTransformation( a2, d2 ) ); - TS_ASSERT_SAME_DATA( d2, expected2, sizeof(double) * 3 ); + TS_ASSERT_SAME_DATA( d2, expected2, sizeof( double ) * 3 ); // E2 = | 2 | // | 1 1 | @@ -116,7 +114,7 @@ class LUFactorizationTestSuite : public CxxTest::TestSuite // --> d = [ 0.5 0.5 0.5 ]^T TS_ASSERT_THROWS_NOTHING( basis.forwardTransformation( a3, d3 ) ); - TS_ASSERT_SAME_DATA( d3, expected3, sizeof(double) * 3 ); + TS_ASSERT_SAME_DATA( d3, expected3, sizeof( double ) * 3 ); } void test_forward_transformation_with_B0() @@ -124,9 +122,7 @@ class LUFactorizationTestSuite : public CxxTest::TestSuite LUFactorization basis( 3, *oracle ); double identity[] = { - 1, 0, 0, - 0, 1, 0, - 0, 0, 1, + 1, 0, 0, 0, 1, 0, 0, 0, 1, }; oracle->storeBasis( 3, identity ); basis.obtainFreshBasis(); @@ -140,11 +136,7 @@ class LUFactorizationTestSuite : public CxxTest::TestSuite double e3[] = { 0.5, 0.5, 0.5 }; basis.updateToAdjacentBasis( 2, e3, NULL ); - double B[] = { - 1, 2, 4, - 4, 5, 7, - 7, 8, 9 - }; + double B[] = { 1, 2, 4, 4, 5, 7, 7, 8, 9 }; oracle->storeBasis( 3, B ); basis.obtainFreshBasis(); @@ -163,9 +155,7 @@ class LUFactorizationTestSuite : public CxxTest::TestSuite LUFactorization basis( 3, *oracle ); double B[] = { - 1, 0, 0, - 0, 1, 0, - 0, 0, 1, + 1, 0, 0, 0, 1, 0, 0, 0, 1, }; oracle->storeBasis( 3, B ); basis.obtainFreshBasis(); @@ -176,7 +166,7 @@ class LUFactorizationTestSuite : public CxxTest::TestSuite double expected1[] = { 1, 2, 3 }; TS_ASSERT_THROWS_NOTHING( basis.backwardTransformation( y1, x1 ) ); - TS_ASSERT_SAME_DATA( x1, expected1, sizeof(double) * 3 ); + TS_ASSERT_SAME_DATA( x1, expected1, sizeof( double ) * 3 ); // E1 = | 1 1 | // | 1 | @@ -195,7 +185,7 @@ class LUFactorizationTestSuite : public CxxTest::TestSuite // --> x = [ 0 12 0 ] TS_ASSERT_THROWS_NOTHING( basis.backwardTransformation( y2, x2 ) ); - TS_ASSERT_SAME_DATA( x2, expected2, sizeof(double) * 3 ); + TS_ASSERT_SAME_DATA( x2, expected2, sizeof( double ) * 3 ); // E2 = | 2 | // | 1 1 | @@ -214,7 +204,7 @@ class LUFactorizationTestSuite : public CxxTest::TestSuite // --> x = [ 3.5 8.5 0 ] TS_ASSERT_THROWS_NOTHING( basis.backwardTransformation( y3, x3 ) ); - TS_ASSERT_SAME_DATA( x3, expected3, sizeof(double) * 3 ); + TS_ASSERT_SAME_DATA( x3, expected3, sizeof( double ) * 3 ); // E3 = | 1 0.5 | // | 1 0.5 | @@ -232,7 +222,7 @@ class LUFactorizationTestSuite : public CxxTest::TestSuite // // --> x = [ 2 1 3 ] TS_ASSERT_THROWS_NOTHING( basis.backwardTransformation( y4, x4 ) ); - TS_ASSERT_SAME_DATA( x4, expected4, sizeof(double) * 3 ); + TS_ASSERT_SAME_DATA( x4, expected4, sizeof( double ) * 3 ); } void test_backward_transformation_2() @@ -240,9 +230,7 @@ class LUFactorizationTestSuite : public CxxTest::TestSuite LUFactorization basis( 3, *oracle ); double B[] = { - 1, 0, 0, - 0, 1, 0, - 0, 0, 1, + 1, 0, 0, 0, 1, 0, 0, 0, 1, }; oracle->storeBasis( 3, B ); basis.obtainFreshBasis(); @@ -264,7 +252,7 @@ class LUFactorizationTestSuite : public CxxTest::TestSuite // --> x = [ 0 0 -1 ] TS_ASSERT_THROWS_NOTHING( basis.backwardTransformation( y, x ) ); - TS_ASSERT_SAME_DATA( x, expected, sizeof(double) * 3 ); + TS_ASSERT_SAME_DATA( x, expected, sizeof( double ) * 3 ); } void test_backward_transformation_with_B0() @@ -272,31 +260,27 @@ class LUFactorizationTestSuite : public CxxTest::TestSuite LUFactorization basis( 3, *oracle ); double identity[] = { - 1, 0, 0, - 0, 1, 0, - 0, 0, 1, + 1, 0, 0, 0, 1, 0, 0, 0, 1, }; oracle->storeBasis( 3, identity ); basis.obtainFreshBasis(); double e1[] = { 1, 1, 3 }; basis.updateToAdjacentBasis( 1, e1, NULL ); - double e2[] = {2., 1., 1.}; + double e2[] = { 2., 1., 1. }; basis.updateToAdjacentBasis( 0, e2, NULL ); double e3[] = { 0.5, 0.5, 0.5 }; basis.updateToAdjacentBasis( 2, e3, NULL ); double B[] = { - 1, 2, 4, - 4, 5, 7, - 7, 8, 9, + 1, 2, 4, 4, 5, 7, 7, 8, 9, }; oracle->storeBasis( 3, B ); basis.obtainFreshBasis(); - double y[] = {19., 12., 17.}; - double x[] = {0., 0., 0.}; - double expected[] = { -104.0/3, 140.0/3, -19 }; + double y[] = { 19., 12., 17. }; + double x[] = { 0., 0., 0. }; + double expected[] = { -104.0 / 3, 140.0 / 3, -19 }; // | 1 2 4 | // x * | 4 5 7 | = | 19 12 17 | @@ -315,9 +299,7 @@ class LUFactorizationTestSuite : public CxxTest::TestSuite LUFactorization otherBasis( 3, *oracle ); double B[] = { - 1, 0, 0, - 0, 1, 0, - 0, 0, 1, + 1, 0, 0, 0, 1, 0, 0, 0, 1, }; oracle->storeBasis( 3, B ); basis.obtainFreshBasis(); @@ -329,11 +311,7 @@ class LUFactorizationTestSuite : public CxxTest::TestSuite basis.updateToAdjacentBasis( 1, a1, NULL ); // Save the expected basis after this push - double currentBasis[] = { - 1, 1, 0, - 0, 1, 0, - 0, 3, 1 - }; + double currentBasis[] = { 1, 1, 0, 0, 1, 0, 0, 3, 1 }; oracle->storeBasis( 3, currentBasis ); basis.obtainFreshBasis(); @@ -376,7 +354,7 @@ class LUFactorizationTestSuite : public CxxTest::TestSuite // The original basis wasn't modified, so the result should be different TS_ASSERT_THROWS_NOTHING( basis.forwardTransformation( a3, d3 ) ); - TS_ASSERT( memcmp( d3other, d3, sizeof(double) * 3 ) ); + TS_ASSERT( memcmp( d3other, d3, sizeof( double ) * 3 ) ); } }; diff --git a/src/basis_factorization/tests/Test_LUFactors.h b/src/basis_factorization/tests/Test_LUFactors.h index 4a3777d07b..996fdd6106 100644 --- a/src/basis_factorization/tests/Test_LUFactors.h +++ b/src/basis_factorization/tests/Test_LUFactors.h @@ -13,12 +13,12 @@ **/ -#include - #include "FloatUtils.h" #include "LUFactors.h" #include "MString.h" +#include + class MockForLUFactors { public: @@ -61,15 +61,11 @@ class LUFactorsTestSuite : public CxxTest::TestSuite | 0 0 3 1 | */ - double F[16] = - { - 1, 0, 2, 0, - -2, 1, 4, 5, - 0, 0, 1, 0, - 0, 0, 3, 1, - }; + double F[16] = { + 1, 0, 2, 0, -2, 1, 4, 5, 0, 0, 1, 0, 0, 0, 3, 1, + }; - memcpy( lu->_F, F, sizeof(F) ); + memcpy( lu->_F, F, sizeof( F ) ); /* @@ -97,15 +93,11 @@ class LUFactorsTestSuite : public CxxTest::TestSuite */ - double V[16] = - { - 0, 1, 5, 2, - 0, 7, 0, 0, - 1, -3, -2, 3, - 0, 2, -2, 0, - }; + double V[16] = { + 0, 1, 5, 2, 0, 7, 0, 0, 1, -3, -2, 3, 0, 2, -2, 0, + }; - memcpy( lu->_V, V, sizeof(V) ); + memcpy( lu->_V, V, sizeof( V ) ); /* Implies A = FV = | 2 -5 1 8 | @@ -208,7 +200,7 @@ class LUFactorsTestSuite : public CxxTest::TestSuite double y1[] = { 1, 2, 3, 4 }; double x1[] = { 0, 0, 0, 0 }; - double expected1[] = { -27.0/2, 2.0/7, -12.0/7, 65.0/14 }; + double expected1[] = { -27.0 / 2, 2.0 / 7, -12.0 / 7, 65.0 / 14 }; TS_ASSERT_THROWS_NOTHING( lu->vForwardTransformation( y1, x1 ) ); for ( unsigned i = 0; i < 4; ++i ) @@ -216,7 +208,7 @@ class LUFactorsTestSuite : public CxxTest::TestSuite double y2[] = { 2, 0, -3, 1 }; double x2[] = { 0, 0, 0, 0 }; - double expected2[] = { -43.0/4, 0, -1.0/2, 9.0/4 }; + double expected2[] = { -43.0 / 4, 0, -1.0 / 2, 9.0 / 4 }; TS_ASSERT_THROWS_NOTHING( lu->vForwardTransformation( y2, x2 ) ); for ( unsigned i = 0; i < 4; ++i ) @@ -242,7 +234,7 @@ class LUFactorsTestSuite : public CxxTest::TestSuite double y1[] = { 1, 2, 3, 4 }; double x1[] = { 0, 0, 0, 0 }; - double expected1[] = { 1.0/2, 1, 1, -5.0/4 }; + double expected1[] = { 1.0 / 2, 1, 1, -5.0 / 4 }; TS_ASSERT_THROWS_NOTHING( lu->vBackwardTransformation( y1, x1 ) ); for ( unsigned i = 0; i < 4; ++i ) @@ -250,7 +242,7 @@ class LUFactorsTestSuite : public CxxTest::TestSuite double y2[] = { 2, 0, -3, 1 }; double x2[] = { 0, 0, 0, 0 }; - double expected2[] = { -5.0/2, 22.0/7, 2, -27.0/4 }; + double expected2[] = { -5.0 / 2, 22.0 / 7, 2, -27.0 / 4 }; TS_ASSERT_THROWS_NOTHING( lu->vBackwardTransformation( y2, x2 ) ); for ( unsigned i = 0; i < 4; ++i ) @@ -276,7 +268,7 @@ class LUFactorsTestSuite : public CxxTest::TestSuite double y1[] = { 1, 2, 3, 4 }; double x1[] = { 0, 0, 0, 0 }; - double expected1[] = { 177.0/4, 5.0/7, 45.0/14, -305.0/28 }; + double expected1[] = { 177.0 / 4, 5.0 / 7, 45.0 / 14, -305.0 / 28 }; TS_ASSERT_THROWS_NOTHING( lu->forwardTransformation( y1, x1 ) ); for ( unsigned i = 0; i < 4; ++i ) @@ -284,7 +276,7 @@ class LUFactorsTestSuite : public CxxTest::TestSuite double y2[] = { 2, 0, -3, 1 }; double x2[] = { 0, 0, 0, 0 }; - double expected2[] = { -213.0/2, -22.0/7, -57.0/7, 363.0/14 }; + double expected2[] = { -213.0 / 2, -22.0 / 7, -57.0 / 7, 363.0 / 14 }; TS_ASSERT_THROWS_NOTHING( lu->forwardTransformation( y2, x2 ) ); for ( unsigned i = 0; i < 4; ++i ) @@ -310,7 +302,7 @@ class LUFactorsTestSuite : public CxxTest::TestSuite double y1[] = { 1, 2, 3, 4 }; double x1[] = { 0, 0, 0, 0 }; - double expected1[] = { 5.0/2, 1, 43.0/4, -25.0/4 }; + double expected1[] = { 5.0 / 2, 1, 43.0 / 4, -25.0 / 4 }; TS_ASSERT_THROWS_NOTHING( lu->backwardTransformation( y1, x1 ) ); for ( unsigned i = 0; i < 4; ++i ) @@ -318,7 +310,7 @@ class LUFactorsTestSuite : public CxxTest::TestSuite double y2[] = { 2, 0, -3, 1 }; double x2[] = { 0, 0, 0, 0 }; - double expected2[] = { 53.0/14, 22.0/7, 197.0/4, -629.0/28 }; + double expected2[] = { 53.0 / 14, 22.0 / 7, 197.0 / 4, -629.0 / 28 }; TS_ASSERT_THROWS_NOTHING( lu->backwardTransformation( y2, x2 ) ); for ( unsigned i = 0; i < 4; ++i ) @@ -339,10 +331,8 @@ class LUFactorsTestSuite : public CxxTest::TestSuite | -5/14 -3/7 -31/4 95/28 | */ double expectedInverse[] = { - 5.0/2, 2, 129.0/4, -59.0/4, - 2.0/7, 1.0/7, 1, -5.0/7, - 2.0/7, 1.0/7, 5.0/2, -17.0/14, - -5.0/14, -3.0/7, -31.0/4, 95.0/28, + 5.0 / 2, 2, 129.0 / 4, -59.0 / 4, 2.0 / 7, 1.0 / 7, 1, -5.0 / 7, + 2.0 / 7, 1.0 / 7, 5.0 / 2, -17.0 / 14, -5.0 / 14, -3.0 / 7, -31.0 / 4, 95.0 / 28, }; double result[16]; diff --git a/src/basis_factorization/tests/Test_PermutationMatrix.h b/src/basis_factorization/tests/Test_PermutationMatrix.h index f3433c960a..73f1c18f5d 100644 --- a/src/basis_factorization/tests/Test_PermutationMatrix.h +++ b/src/basis_factorization/tests/Test_PermutationMatrix.h @@ -13,15 +13,15 @@ **/ -#include - #include "BasisFactorizationError.h" #include "EtaMatrix.h" #include "FloatUtils.h" #include "GlobalConfiguration.h" -#include "PermutationMatrix.h" #include "List.h" #include "MockErrno.h" +#include "PermutationMatrix.h" + +#include class MockForPermutationMatrix { diff --git a/src/basis_factorization/tests/Test_SparseFTFactorization.h b/src/basis_factorization/tests/Test_SparseFTFactorization.h index 260fc625de..7a7ace573e 100644 --- a/src/basis_factorization/tests/Test_SparseFTFactorization.h +++ b/src/basis_factorization/tests/Test_SparseFTFactorization.h @@ -13,16 +13,16 @@ **/ -#include - #include "BasisFactorizationError.h" #include "EtaMatrix.h" #include "FloatUtils.h" #include "GlobalConfiguration.h" -#include "SparseFTFactorization.h" #include "List.h" #include "MockColumnOracle.h" #include "MockErrno.h" +#include "SparseFTFactorization.h" + +#include class MockForSparseFTFactorization { @@ -51,10 +51,8 @@ class SparseFTFactorizationTestSuite : public CxxTest::TestSuite { SparseFTFactorization basis( 3, *oracle ); - double B[] = { - 1, 0, 0, - 0, 1, 0, - 0, 0, 1, + double B[] = { + 1, 0, 0, 0, 1, 0, 0, 0, 1, }; oracle->storeBasis( 3, B ); basis.obtainFreshBasis(); @@ -65,7 +63,7 @@ class SparseFTFactorizationTestSuite : public CxxTest::TestSuite double expected1[] = { 1, 1, 3 }; TS_ASSERT_THROWS_NOTHING( basis.forwardTransformation( a1, d1 ) ); - TS_ASSERT_SAME_DATA( d1, expected1, sizeof(double) * 3 ); + TS_ASSERT_SAME_DATA( d1, expected1, sizeof( double ) * 3 ); // E1 = | 1 1 | // | 1 | @@ -83,7 +81,7 @@ class SparseFTFactorizationTestSuite : public CxxTest::TestSuite // --> d = [ 2 1 1 ]^T TS_ASSERT_THROWS_NOTHING( basis.forwardTransformation( a2, d2 ) ); - TS_ASSERT_SAME_DATA( d2, expected2, sizeof(double) * 3 ); + TS_ASSERT_SAME_DATA( d2, expected2, sizeof( double ) * 3 ); // E2 = | 2 | // | 1 1 | @@ -101,56 +99,48 @@ class SparseFTFactorizationTestSuite : public CxxTest::TestSuite // --> d = [ 0.5 0.5 0.5 ]^T TS_ASSERT_THROWS_NOTHING( basis.forwardTransformation( a3, d3 ) ); - TS_ASSERT_SAME_DATA( d3, expected3, sizeof(double) * 3 ); + TS_ASSERT_SAME_DATA( d3, expected3, sizeof( double ) * 3 ); } - void test_forward_transformation_with_B0() - { + void test_forward_transformation_with_B0() + { SparseFTFactorization basis( 3, *oracle ); double identity[] = { - 1, 0, 0, - 0, 1, 0, - 0, 0, 1, + 1, 0, 0, 0, 1, 0, 0, 0, 1, }; oracle->storeBasis( 3, identity ); basis.obtainFreshBasis(); - double e1[] = { 1, 1, 3 }; - basis.updateToAdjacentBasis( 1, NULL, e1 ); + double e1[] = { 1, 1, 3 }; + basis.updateToAdjacentBasis( 1, NULL, e1 ); - double e2[] = { 2, 1, 1 }; - basis.updateToAdjacentBasis ( 0, NULL, e2 ); + double e2[] = { 2, 1, 1 }; + basis.updateToAdjacentBasis( 0, NULL, e2 ); - double e3[] = { 0.5, 0.5, 0.5 }; - basis.updateToAdjacentBasis( 2, NULL, e3 ); + double e3[] = { 0.5, 0.5, 0.5 }; + basis.updateToAdjacentBasis( 2, NULL, e3 ); - double B[] = { - 1, 2, 4, - 4, 5, 7, - 7, 8, 9 - }; + double B[] = { 1, 2, 4, 4, 5, 7, 7, 8, 9 }; oracle->storeBasis( 3, B ); basis.obtainFreshBasis(); - double a[] = { 2., -1., 4. }; - double d[] = { 0., 0., 0. }; + double a[] = { 2., -1., 4. }; + double d[] = { 0., 0., 0. }; double expected[] = { -20, 27, -8 }; basis.forwardTransformation( a, d ); for ( unsigned i = 0; i < 3; ++i ) TS_ASSERT( FloatUtils::areEqual( d[i], expected[i] ) ); - } + } - void test_backward_transformation() + void test_backward_transformation() { SparseFTFactorization basis( 3, *oracle ); double B[] = { - 1, 0, 0, - 0, 1, 0, - 0, 0, 1, + 1, 0, 0, 0, 1, 0, 0, 0, 1, }; oracle->storeBasis( 3, B ); basis.obtainFreshBasis(); @@ -161,7 +151,7 @@ class SparseFTFactorizationTestSuite : public CxxTest::TestSuite double expected1[] = { 1, 2, 3 }; TS_ASSERT_THROWS_NOTHING( basis.backwardTransformation( y1, x1 ) ); - TS_ASSERT_SAME_DATA( x1, expected1, sizeof(double) * 3 ); + TS_ASSERT_SAME_DATA( x1, expected1, sizeof( double ) * 3 ); // Change basis into: // | 1 1 | @@ -181,7 +171,7 @@ class SparseFTFactorizationTestSuite : public CxxTest::TestSuite // --> x = [ 0 12 0 ] TS_ASSERT_THROWS_NOTHING( basis.backwardTransformation( y2, x2 ) ); - TS_ASSERT_SAME_DATA( x2, expected2, sizeof(double) * 3 ); + TS_ASSERT_SAME_DATA( x2, expected2, sizeof( double ) * 3 ); // Change basis into: // | 3 1 | @@ -201,7 +191,7 @@ class SparseFTFactorizationTestSuite : public CxxTest::TestSuite // --> x = [ 3.5 8.5 0 ] TS_ASSERT_THROWS_NOTHING( basis.backwardTransformation( y3, x3 ) ); - TS_ASSERT_SAME_DATA( x3, expected3, sizeof(double) * 3 ); + TS_ASSERT_SAME_DATA( x3, expected3, sizeof( double ) * 3 ); // Change basis into: // | 3 1 2 | @@ -220,7 +210,7 @@ class SparseFTFactorizationTestSuite : public CxxTest::TestSuite // // --> x = [ 2 1 3 ] TS_ASSERT_THROWS_NOTHING( basis.backwardTransformation( y4, x4 ) ); - TS_ASSERT_SAME_DATA( x4, expected4, sizeof(double) * 3 ); + TS_ASSERT_SAME_DATA( x4, expected4, sizeof( double ) * 3 ); } void test_backward_transformation_2() @@ -228,9 +218,7 @@ class SparseFTFactorizationTestSuite : public CxxTest::TestSuite SparseFTFactorization basis( 3, *oracle ); double B[] = { - 1, 0, 0, - 0, 1, 0, - 0, 0, 1, + 1, 0, 0, 0, 1, 0, 0, 0, 1, }; oracle->storeBasis( 3, B ); basis.obtainFreshBasis(); @@ -257,49 +245,45 @@ class SparseFTFactorizationTestSuite : public CxxTest::TestSuite TS_ASSERT( FloatUtils::areEqual( x[i], expected[i] ) ); } - void test_backward_transformation_with_B0() - { + void test_backward_transformation_with_B0() + { SparseFTFactorization basis( 3, *oracle ); double identity[] = { - 1, 0, 0, - 0, 1, 0, - 0, 0, 1, + 1, 0, 0, 0, 1, 0, 0, 0, 1, }; oracle->storeBasis( 3, identity ); basis.obtainFreshBasis(); - double e1[] = { 1, 1, 3 }; - basis.updateToAdjacentBasis( 1, NULL, e1 ); + double e1[] = { 1, 1, 3 }; + basis.updateToAdjacentBasis( 1, NULL, e1 ); - double e2[] = { 2, 1, 1 }; - basis.updateToAdjacentBasis( 0, NULL, e2 ); + double e2[] = { 2, 1, 1 }; + basis.updateToAdjacentBasis( 0, NULL, e2 ); - double e3[] = { 0.5, 0.5, 0.5 }; + double e3[] = { 0.5, 0.5, 0.5 }; basis.updateToAdjacentBasis( 2, NULL, e3 ); - double B[] = { - 1, 2, 4, - 4, 5, 7, - 7, 8, 9, + double B[] = { + 1, 2, 4, 4, 5, 7, 7, 8, 9, }; oracle->storeBasis( 3, B ); basis.obtainFreshBasis(); - double y[] = { 19, 12, 17 }; - double x[] = { 0, 0, 0 }; - double expected[] = { -104.0/3, 140.0/3, -19 }; + double y[] = { 19, 12, 17 }; + double x[] = { 0, 0, 0 }; + double expected[] = { -104.0 / 3, 140.0 / 3, -19 }; - // | 1 2 4 | + // | 1 2 4 | // x * | 4 5 7 | = | 19 12 17 | // | 7 8 9 | // // --> x = [ -104/3, 140/3, -19 ] - basis.backwardTransformation( y, x ); + basis.backwardTransformation( y, x ); for ( unsigned i = 0; i < 3; ++i ) TS_ASSERT( FloatUtils::areEqual( x[i], expected[i] ) ); - } + } void test_store_and_restore() { @@ -307,9 +291,7 @@ class SparseFTFactorizationTestSuite : public CxxTest::TestSuite SparseFTFactorization otherBasis( 3, *oracle ); double B[] = { - 1, 0, 0, - 0, 1, 0, - 0, 0, 1, + 1, 0, 0, 0, 1, 0, 0, 0, 1, }; oracle->storeBasis( 3, B ); basis.obtainFreshBasis(); @@ -321,11 +303,7 @@ class SparseFTFactorizationTestSuite : public CxxTest::TestSuite basis.updateToAdjacentBasis( 1, NULL, a1 ); // Save the expected basis after this push - double currentBasis[] = { - 1, 1, 0, - 0, 1, 0, - 0, 3, 1 - }; + double currentBasis[] = { 1, 1, 0, 0, 1, 0, 0, 3, 1 }; oracle->storeBasis( 3, currentBasis ); basis.obtainFreshBasis(); @@ -373,7 +351,7 @@ class SparseFTFactorizationTestSuite : public CxxTest::TestSuite // The original basis wasn't modified, so the result should be different TS_ASSERT_THROWS_NOTHING( basis.forwardTransformation( a3, d3 ) ); - TS_ASSERT( memcmp( d3other, d3, sizeof(double) * 3 ) ); + TS_ASSERT( memcmp( d3other, d3, sizeof( double ) * 3 ) ); } }; diff --git a/src/basis_factorization/tests/Test_SparseGaussianEliminator.h b/src/basis_factorization/tests/Test_SparseGaussianEliminator.h index 0aaf0cdc43..515c7c1643 100644 --- a/src/basis_factorization/tests/Test_SparseGaussianEliminator.h +++ b/src/basis_factorization/tests/Test_SparseGaussianEliminator.h @@ -13,14 +13,14 @@ **/ -#include - #include "BasisFactorizationError.h" #include "CSRMatrix.h" #include "EtaMatrix.h" #include "FloatUtils.h" #include "SparseGaussianEliminator.h" + #include +#include class MockForSparseGaussianEliminator { @@ -57,12 +57,12 @@ class SparseGaussianEliminatorTestSuite : public CxxTest::TestSuite { for ( unsigned j = 0; j < m; ++j ) { - result[i*m + j] = 0; + result[i * m + j] = 0; for ( unsigned k = 0; k < m; ++k ) { double fValue = ( i == k ) ? 1.0 : lu->_F->get( i, k ); double vValue = lu->_V->get( k, j ); - result[i*m + j] += fValue * vValue; + result[i * m + j] += fValue * vValue; } } } @@ -77,7 +77,7 @@ class SparseGaussianEliminatorTestSuite : public CxxTest::TestSuite { for ( unsigned row = 0; row < m; ++row ) { - denseColumn[row] = B[row*m + col]; + denseColumn[row] = B[row * m + col]; } SparseUnsortedList *list = new SparseUnsortedList( denseColumn, m ); @@ -99,13 +99,13 @@ class SparseGaussianEliminatorTestSuite : public CxxTest::TestSuite { for ( unsigned j = 0; j < m; ++j ) { - result[i*m + j] = 0; + result[i * m + j] = 0; for ( unsigned k = 0; k < m; ++k ) { double vtValue = lu->_Vt->get( i, k ); double ftValue = ( k == j ) ? 1.0 : lu->_Ft->get( k, j ); - result[i*m + j] += vtValue * ftValue; + result[i * m + j] += vtValue * ftValue; } } } @@ -121,7 +121,7 @@ class SparseGaussianEliminatorTestSuite : public CxxTest::TestSuite printf( "\t" ); for ( unsigned j = 0; j < m; ++j ) { - printf( "%8.lf ", matrix[i*m + j] ); + printf( "%8.lf ", matrix[i * m + j] ); } printf( "\n" ); } @@ -135,7 +135,7 @@ class SparseGaussianEliminatorTestSuite : public CxxTest::TestSuite { for ( unsigned j = 0; j < m; ++j ) { - result[i*m + j] = orig[j*m + i]; + result[i * m + j] = orig[j * m + i]; } } } @@ -146,12 +146,7 @@ class SparseGaussianEliminatorTestSuite : public CxxTest::TestSuite SparseLUFactors lu4( 4 ); { - double A[] = - { - 2, 3, 0, - 0, 1, 0, - 0, 0, 1 - }; + double A[] = { 2, 3, 0, 0, 1, 0, 0, 0, 1 }; SparseColumnsOfBasis sparseCols( 3 ); basisIntoSparseColumns( A, 3, sparseCols ); @@ -182,12 +177,7 @@ class SparseGaussianEliminatorTestSuite : public CxxTest::TestSuite } { - double A[] = - { - 2, 3, 0, - 0, 1, 2, - 0, 4, 1 - }; + double A[] = { 2, 3, 0, 0, 1, 2, 0, 4, 1 }; SparseColumnsOfBasis sparseCols( 3 ); basisIntoSparseColumns( A, 3, sparseCols ); @@ -218,12 +208,7 @@ class SparseGaussianEliminatorTestSuite : public CxxTest::TestSuite } { - double A[] = - { - 2, 3, -4, - -5, 1, 2, - 0, 4, 1 - }; + double A[] = { 2, 3, -4, -5, 1, 2, 0, 4, 1 }; SparseColumnsOfBasis sparseCols( 3 ); basisIntoSparseColumns( A, 3, sparseCols ); @@ -254,12 +239,8 @@ class SparseGaussianEliminatorTestSuite : public CxxTest::TestSuite } { - double A[] = - { - 2, 3, -4, 0, - -5, 1, 2, 2, - 0, 4, 1, -5, - 1, 2, 3, 4, + double A[] = { + 2, 3, -4, 0, -5, 1, 2, 2, 0, 4, 1, -5, 1, 2, 3, 4, }; SparseColumnsOfBasis sparseCols( 4 ); @@ -291,12 +272,7 @@ class SparseGaussianEliminatorTestSuite : public CxxTest::TestSuite } { - double A[] = - { - 2, 3, 0, - 0, 1, 0, - 5, 4, 0 - }; + double A[] = { 2, 3, 0, 0, 1, 0, 5, 4, 0 }; SparseColumnsOfBasis sparseCols( 3 ); basisIntoSparseColumns( A, 3, sparseCols ); @@ -313,12 +289,7 @@ class SparseGaussianEliminatorTestSuite : public CxxTest::TestSuite } { - double A[] = - { - 2, 3, 7, - 0, 0, 0, - 5, 4, 0 - }; + double A[] = { 2, 3, 7, 0, 0, 0, 5, 4, 0 }; SparseColumnsOfBasis sparseCols( 3 ); basisIntoSparseColumns( A, 3, sparseCols ); diff --git a/src/basis_factorization/tests/Test_SparseLUFactorization.h b/src/basis_factorization/tests/Test_SparseLUFactorization.h index 2d20ed9cd7..f6e84020c6 100644 --- a/src/basis_factorization/tests/Test_SparseLUFactorization.h +++ b/src/basis_factorization/tests/Test_SparseLUFactorization.h @@ -13,16 +13,16 @@ **/ -#include - #include "BasisFactorizationError.h" #include "EtaMatrix.h" #include "FloatUtils.h" #include "GlobalConfiguration.h" -#include "SparseLUFactorization.h" #include "List.h" #include "MockColumnOracle.h" #include "MockErrno.h" +#include "SparseLUFactorization.h" + +#include class MockForSparseLUFactorization { @@ -52,9 +52,7 @@ class SparseLUFactorizationTestSuite : public CxxTest::TestSuite SparseLUFactorization basis( 3, *oracle ); double B[] = { - 1, 0, 0, - 0, 1, 0, - 0, 0, 1, + 1, 0, 0, 0, 1, 0, 0, 0, 1, }; oracle->storeBasis( 3, B ); basis.obtainFreshBasis(); @@ -65,7 +63,7 @@ class SparseLUFactorizationTestSuite : public CxxTest::TestSuite double expected1[] = { 1, 1, 3 }; TS_ASSERT_THROWS_NOTHING( basis.forwardTransformation( a1, d1 ) ); - TS_ASSERT_SAME_DATA( d1, expected1, sizeof(double) * 3 ); + TS_ASSERT_SAME_DATA( d1, expected1, sizeof( double ) * 3 ); // E1 = | 1 1 | // | 1 | @@ -83,7 +81,7 @@ class SparseLUFactorizationTestSuite : public CxxTest::TestSuite // --> d = [ 2 1 1 ]^T TS_ASSERT_THROWS_NOTHING( basis.forwardTransformation( a2, d2 ) ); - TS_ASSERT_SAME_DATA( d2, expected2, sizeof(double) * 3 ); + TS_ASSERT_SAME_DATA( d2, expected2, sizeof( double ) * 3 ); // E2 = | 2 | // | 1 1 | @@ -101,7 +99,7 @@ class SparseLUFactorizationTestSuite : public CxxTest::TestSuite // --> d = [ 0.5 0.5 0.5 ]^T TS_ASSERT_THROWS_NOTHING( basis.forwardTransformation( a3, d3 ) ); - TS_ASSERT_SAME_DATA( d3, expected3, sizeof(double) * 3 ); + TS_ASSERT_SAME_DATA( d3, expected3, sizeof( double ) * 3 ); } void test_forward_transformation_with_B0() @@ -113,16 +111,12 @@ class SparseLUFactorizationTestSuite : public CxxTest::TestSuite basis.updateToAdjacentBasis( 1, e1, NULL ); double e2[] = { 2, 1, 1 }; - basis.updateToAdjacentBasis ( 0, e2, NULL ); + basis.updateToAdjacentBasis( 0, e2, NULL ); double e3[] = { 0.5, 0.5, 0.5 }; basis.updateToAdjacentBasis( 2, e3, NULL ); - double B[] = { - 1, 2, 4, - 4, 5, 7, - 7, 8, 9 - }; + double B[] = { 1, 2, 4, 4, 5, 7, 7, 8, 9 }; oracle->storeBasis( 3, B ); basis.obtainFreshBasis(); @@ -141,9 +135,7 @@ class SparseLUFactorizationTestSuite : public CxxTest::TestSuite SparseLUFactorization basis( 3, *oracle ); double B[] = { - 1, 0, 0, - 0, 1, 0, - 0, 0, 1, + 1, 0, 0, 0, 1, 0, 0, 0, 1, }; oracle->storeBasis( 3, B ); basis.obtainFreshBasis(); @@ -154,7 +146,7 @@ class SparseLUFactorizationTestSuite : public CxxTest::TestSuite double expected1[] = { 1, 2, 3 }; TS_ASSERT_THROWS_NOTHING( basis.backwardTransformation( y1, x1 ) ); - TS_ASSERT_SAME_DATA( x1, expected1, sizeof(double) * 3 ); + TS_ASSERT_SAME_DATA( x1, expected1, sizeof( double ) * 3 ); // E1 = | 1 1 | // | 1 | @@ -173,7 +165,7 @@ class SparseLUFactorizationTestSuite : public CxxTest::TestSuite // --> x = [ 0 12 0 ] TS_ASSERT_THROWS_NOTHING( basis.backwardTransformation( y2, x2 ) ); - TS_ASSERT_SAME_DATA( x2, expected2, sizeof(double) * 3 ); + TS_ASSERT_SAME_DATA( x2, expected2, sizeof( double ) * 3 ); // E2 = | 2 | // | 1 1 | @@ -192,7 +184,7 @@ class SparseLUFactorizationTestSuite : public CxxTest::TestSuite // --> x = [ 3.5 8.5 0 ] TS_ASSERT_THROWS_NOTHING( basis.backwardTransformation( y3, x3 ) ); - TS_ASSERT_SAME_DATA( x3, expected3, sizeof(double) * 3 ); + TS_ASSERT_SAME_DATA( x3, expected3, sizeof( double ) * 3 ); // E3 = | 1 0.5 | // | 1 0.5 | @@ -210,7 +202,7 @@ class SparseLUFactorizationTestSuite : public CxxTest::TestSuite // // --> x = [ 2 1 3 ] TS_ASSERT_THROWS_NOTHING( basis.backwardTransformation( y4, x4 ) ); - TS_ASSERT_SAME_DATA( x4, expected4, sizeof(double) * 3 ); + TS_ASSERT_SAME_DATA( x4, expected4, sizeof( double ) * 3 ); } void test_backward_transformation_2() @@ -218,9 +210,7 @@ class SparseLUFactorizationTestSuite : public CxxTest::TestSuite SparseLUFactorization basis( 3, *oracle ); double B[] = { - 1, 0, 0, - 0, 1, 0, - 0, 0, 1, + 1, 0, 0, 0, 1, 0, 0, 0, 1, }; oracle->storeBasis( 3, B ); basis.obtainFreshBasis(); @@ -242,7 +232,7 @@ class SparseLUFactorizationTestSuite : public CxxTest::TestSuite // --> x = [ 0 0 -1 ] TS_ASSERT_THROWS_NOTHING( basis.backwardTransformation( y, x ) ); - TS_ASSERT_SAME_DATA( x, expected, sizeof(double) * 3 ); + TS_ASSERT_SAME_DATA( x, expected, sizeof( double ) * 3 ); } void test_backward_transformation_with_B0() @@ -260,16 +250,14 @@ class SparseLUFactorizationTestSuite : public CxxTest::TestSuite basis.updateToAdjacentBasis( 2, e3, NULL ); double B[] = { - 1, 2, 4, - 4, 5, 7, - 7, 8, 9, + 1, 2, 4, 4, 5, 7, 7, 8, 9, }; oracle->storeBasis( 3, B ); basis.obtainFreshBasis(); double y[] = { 19, 12, 17 }; double x[] = { 0, 0, 0 }; - double expected[] = { -104.0/3, 140.0/3, -19 }; + double expected[] = { -104.0 / 3, 140.0 / 3, -19 }; // | 1 2 4 | // x * | 4 5 7 | = | 19 12 17 | @@ -288,9 +276,7 @@ class SparseLUFactorizationTestSuite : public CxxTest::TestSuite SparseLUFactorization otherBasis( 3, *oracle ); double B[] = { - 1, 0, 0, - 0, 1, 0, - 0, 0, 1, + 1, 0, 0, 0, 1, 0, 0, 0, 1, }; oracle->storeBasis( 3, B ); basis.obtainFreshBasis(); @@ -302,11 +288,7 @@ class SparseLUFactorizationTestSuite : public CxxTest::TestSuite basis.updateToAdjacentBasis( 1, a1, NULL ); // Save the expected basis after this push - double currentBasis[] = { - 1, 1, 0, - 0, 1, 0, - 0, 3, 1 - }; + double currentBasis[] = { 1, 1, 0, 0, 1, 0, 0, 3, 1 }; oracle->storeBasis( 3, currentBasis ); // Do a computation using both basis, see that we get the same result. @@ -348,7 +330,7 @@ class SparseLUFactorizationTestSuite : public CxxTest::TestSuite // The original basis wasn't modified, so the result should be different TS_ASSERT_THROWS_NOTHING( basis.forwardTransformation( a3, d3 ) ); - TS_ASSERT( memcmp( d3other, d3, sizeof(double) * 3 ) ); + TS_ASSERT( memcmp( d3other, d3, sizeof( double ) * 3 ) ); } }; diff --git a/src/basis_factorization/tests/Test_SparseLUFactors.h b/src/basis_factorization/tests/Test_SparseLUFactors.h index 5c088a6996..8d263259bc 100644 --- a/src/basis_factorization/tests/Test_SparseLUFactors.h +++ b/src/basis_factorization/tests/Test_SparseLUFactors.h @@ -13,11 +13,11 @@ **/ -#include - #include "FloatUtils.h" -#include "SparseLUFactors.h" #include "MString.h" +#include "SparseLUFactors.h" + +#include class MockForSparseLUFactors { @@ -36,7 +36,7 @@ class SparseLUFactorsTestSuite : public CxxTest::TestSuite { for ( unsigned j = 0; j < dim; ++j ) { - At[i*dim + j] = A[j*dim + i]; + At[i * dim + j] = A[j * dim + i]; } } } @@ -74,13 +74,9 @@ class SparseLUFactorsTestSuite : public CxxTest::TestSuite Recall that F's 1-diagonal is IMPLICIT */ - double F[16] = - { - 0, 0, 2, 0, - -2, 0, 4, 5, - 0, 0, 0, 0, - 0, 0, 3, 0, - }; + double F[16] = { + 0, 0, 2, 0, -2, 0, 4, 5, 0, 0, 0, 0, 0, 0, 3, 0, + }; lu->_F->initialize( F, 4, 4 ); @@ -113,13 +109,9 @@ class SparseLUFactorsTestSuite : public CxxTest::TestSuite */ - double V[16] = - { - 0, 1, 5, 2, - 0, 7, 0, 0, - 1, -3, -2, 3, - 0, 2, -2, 0, - }; + double V[16] = { + 0, 1, 5, 2, 0, 7, 0, 0, 1, -3, -2, 3, 0, 2, -2, 0, + }; lu->_V->initialize( V, 4, 4 ); @@ -237,7 +229,7 @@ class SparseLUFactorsTestSuite : public CxxTest::TestSuite double y1[] = { 1, 2, 3, 4 }; double x1[] = { 0, 0, 0, 0 }; - double expected1[] = { -27.0/2, 2.0/7, -12.0/7, 65.0/14 }; + double expected1[] = { -27.0 / 2, 2.0 / 7, -12.0 / 7, 65.0 / 14 }; TS_ASSERT_THROWS_NOTHING( lu->vForwardTransformation( y1, x1 ) ); for ( unsigned i = 0; i < 4; ++i ) @@ -245,7 +237,7 @@ class SparseLUFactorsTestSuite : public CxxTest::TestSuite double y2[] = { 2, 0, -3, 1 }; double x2[] = { 0, 0, 0, 0 }; - double expected2[] = { -43.0/4, 0, -1.0/2, 9.0/4 }; + double expected2[] = { -43.0 / 4, 0, -1.0 / 2, 9.0 / 4 }; TS_ASSERT_THROWS_NOTHING( lu->vForwardTransformation( y2, x2 ) ); for ( unsigned i = 0; i < 4; ++i ) @@ -271,7 +263,7 @@ class SparseLUFactorsTestSuite : public CxxTest::TestSuite double y1[] = { 1, 2, 3, 4 }; double x1[] = { 0, 0, 0, 0 }; - double expected1[] = { 1.0/2, 1, 1, -5.0/4 }; + double expected1[] = { 1.0 / 2, 1, 1, -5.0 / 4 }; TS_ASSERT_THROWS_NOTHING( lu->vBackwardTransformation( y1, x1 ) ); for ( unsigned i = 0; i < 4; ++i ) @@ -279,7 +271,7 @@ class SparseLUFactorsTestSuite : public CxxTest::TestSuite double y2[] = { 2, 0, -3, 1 }; double x2[] = { 0, 0, 0, 0 }; - double expected2[] = { -5.0/2, 22.0/7, 2, -27.0/4 }; + double expected2[] = { -5.0 / 2, 22.0 / 7, 2, -27.0 / 4 }; TS_ASSERT_THROWS_NOTHING( lu->vBackwardTransformation( y2, x2 ) ); for ( unsigned i = 0; i < 4; ++i ) @@ -305,7 +297,7 @@ class SparseLUFactorsTestSuite : public CxxTest::TestSuite double y1[] = { 1, 2, 3, 4 }; double x1[] = { 0, 0, 0, 0 }; - double expected1[] = { 177.0/4, 5.0/7, 45.0/14, -305.0/28 }; + double expected1[] = { 177.0 / 4, 5.0 / 7, 45.0 / 14, -305.0 / 28 }; TS_ASSERT_THROWS_NOTHING( lu->forwardTransformation( y1, x1 ) ); for ( unsigned i = 0; i < 4; ++i ) @@ -313,7 +305,7 @@ class SparseLUFactorsTestSuite : public CxxTest::TestSuite double y2[] = { 2, 0, -3, 1 }; double x2[] = { 0, 0, 0, 0 }; - double expected2[] = { -213.0/2, -22.0/7, -57.0/7, 363.0/14 }; + double expected2[] = { -213.0 / 2, -22.0 / 7, -57.0 / 7, 363.0 / 14 }; TS_ASSERT_THROWS_NOTHING( lu->forwardTransformation( y2, x2 ) ); for ( unsigned i = 0; i < 4; ++i ) @@ -339,7 +331,7 @@ class SparseLUFactorsTestSuite : public CxxTest::TestSuite double y1[] = { 1, 2, 3, 4 }; double x1[] = { 0, 0, 0, 0 }; - double expected1[] = { 5.0/2, 1, 43.0/4, -25.0/4 }; + double expected1[] = { 5.0 / 2, 1, 43.0 / 4, -25.0 / 4 }; TS_ASSERT_THROWS_NOTHING( lu->backwardTransformation( y1, x1 ) ); for ( unsigned i = 0; i < 4; ++i ) @@ -347,7 +339,7 @@ class SparseLUFactorsTestSuite : public CxxTest::TestSuite double y2[] = { 2, 0, -3, 1 }; double x2[] = { 0, 0, 0, 0 }; - double expected2[] = { 53.0/14, 22.0/7, 197.0/4, -629.0/28 }; + double expected2[] = { 53.0 / 14, 22.0 / 7, 197.0 / 4, -629.0 / 28 }; TS_ASSERT_THROWS_NOTHING( lu->backwardTransformation( y2, x2 ) ); for ( unsigned i = 0; i < 4; ++i ) @@ -368,10 +360,8 @@ class SparseLUFactorsTestSuite : public CxxTest::TestSuite | -5/14 -3/7 -31/4 95/28 | */ double expectedInverse[] = { - 5.0/2, 2, 129.0/4, -59.0/4, - 2.0/7, 1.0/7, 1, -5.0/7, - 2.0/7, 1.0/7, 5.0/2, -17.0/14, - -5.0/14, -3.0/7, -31.0/4, 95.0/28, + 5.0 / 2, 2, 129.0 / 4, -59.0 / 4, 2.0 / 7, 1.0 / 7, 1, -5.0 / 7, + 2.0 / 7, 1.0 / 7, 5.0 / 2, -17.0 / 14, -5.0 / 14, -3.0 / 7, -31.0 / 4, 95.0 / 28, }; double result[16]; diff --git a/src/basis_factorization/tests/Test_SparseUnsortedArray.h b/src/basis_factorization/tests/Test_SparseUnsortedArray.h index 5a1d42ff2a..1ce0b99dc8 100644 --- a/src/basis_factorization/tests/Test_SparseUnsortedArray.h +++ b/src/basis_factorization/tests/Test_SparseUnsortedArray.h @@ -13,12 +13,12 @@ **/ -#include - #include "FloatUtils.h" #include "Map.h" #include "SparseUnsortedArray.h" +#include + class MockForSparseUnsortedArray { public: @@ -51,9 +51,7 @@ class SparseUnsortedArrayTestSuite : public CxxTest::TestSuite void test_initialize_from_dense() { - double dense[8] = { - 1, 2, 3, 0, 0, 4, 5, 6 - }; + double dense[8] = { 1, 2, 3, 0, 0, 4, 5, 6 }; SparseUnsortedArray v1( dense, 8 ); @@ -66,9 +64,7 @@ class SparseUnsortedArrayTestSuite : public CxxTest::TestSuite void test_cloning() { - double dense[8] = { - 1, 2, 3, 0, 0, 4, 5, 6 - }; + double dense[8] = { 1, 2, 3, 0, 0, 4, 5, 6 }; SparseUnsortedArray v1( dense, 8 ); @@ -88,9 +84,7 @@ class SparseUnsortedArrayTestSuite : public CxxTest::TestSuite void test_iterate() { - double dense[8] = { - 1, 2, 3, 0, 0, 4, 5, 6 - }; + double dense[8] = { 1, 2, 3, 0, 0, 4, 5, 6 }; Map answers; answers[0] = 1; @@ -129,9 +123,7 @@ class SparseUnsortedArrayTestSuite : public CxxTest::TestSuite double dense[5]; TS_ASSERT_THROWS_NOTHING( v1.toDense( dense ) ); - double expected[5] = { - 4, 0, 3, 0, -7 - }; + double expected[5] = { 4, 0, 3, 0, -7 }; for ( unsigned i = 0; i < 5; ++i ) TS_ASSERT( FloatUtils::areEqual( expected[i], dense[i] ) ); @@ -141,9 +133,7 @@ class SparseUnsortedArrayTestSuite : public CxxTest::TestSuite TS_ASSERT_THROWS_NOTHING( v1.toDense( dense ) ); - double expected2[5] = { - 4, 5, 0, 0, -7 - }; + double expected2[5] = { 4, 5, 0, 0, -7 }; for ( unsigned i = 0; i < 5; ++i ) TS_ASSERT( FloatUtils::areEqual( expected2[i], dense[i] ) ); diff --git a/src/basis_factorization/tests/Test_SparseUnsortedArrays.h b/src/basis_factorization/tests/Test_SparseUnsortedArrays.h index 52be20cf7f..906ae5123a 100644 --- a/src/basis_factorization/tests/Test_SparseUnsortedArrays.h +++ b/src/basis_factorization/tests/Test_SparseUnsortedArrays.h @@ -13,12 +13,12 @@ **/ -#include - #include "FloatUtils.h" #include "MString.h" #include "SparseUnsortedArrays.h" +#include + class MockForSparseUnsortedArrays { public: @@ -49,42 +49,32 @@ class SparseUnsortedArraysTestSuite : public CxxTest::TestSuite // Initialize through empty constructor and initialize(); double M1[] = { - 0, 0, 0, 0, - 5, 8, 0, 0, - 0, 0, 3, 0, - 0, 6, 0, 0, - }; + 0, 0, 0, 0, 5, 8, 0, 0, 0, 0, 3, 0, 0, 6, 0, 0, + }; SparseUnsortedArrays sv1; sv1.initialize( M1, 4, 4 ); for ( unsigned i = 0; i < 4; ++i ) for ( unsigned j = 0; j < 4; ++j ) - TS_ASSERT_EQUALS( M1[i*4 + j], sv1.get( i, j ) ); + TS_ASSERT_EQUALS( M1[i * 4 + j], sv1.get( i, j ) ); // Dense matrix, initialize through constructor double M2[] = { - 1, 2, 3, 4, - 5, 8, 5, 6, - 1, 2, 3, 4, - 5, 6, 7, 8, - 9, 1, 2, 3, - }; + 1, 2, 3, 4, 5, 8, 5, 6, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, + }; SparseUnsortedArrays sv2; sv2.initialize( M2, 5, 4 ); for ( unsigned i = 0; i < 5; ++i ) for ( unsigned j = 0; j < 4; ++j ) - TS_ASSERT_EQUALS( M2[i*4 + j], sv2.get( i, j ) ); + TS_ASSERT_EQUALS( M2[i * 4 + j], sv2.get( i, j ) ); } void test_store_restore() { double M1[] = { - 0, 0, 0, 0, - 5, 8, 0, 0, - 0, 0, 3, 0, - 0, 6, 0, 0, + 0, 0, 0, 0, 5, 8, 0, 0, 0, 0, 3, 0, 0, 6, 0, 0, }; SparseUnsortedArrays sv1; @@ -104,10 +94,7 @@ class SparseUnsortedArraysTestSuite : public CxxTest::TestSuite void test_add_last_row() { double M1[] = { - 0, 0, 0, 0, - 5, 8, 0, 0, - 0, 0, 3, 0, - 0, 6, 0, 0, + 0, 0, 0, 0, 5, 8, 0, 0, 0, 0, 3, 0, 0, 6, 0, 0, }; SparseUnsortedArrays sv1; @@ -122,28 +109,19 @@ class SparseUnsortedArraysTestSuite : public CxxTest::TestSuite sv1.addLastRow( row7 ); double expected[] = { - 0, 0, 0, 0, - 5, 8, 0, 0, - 0, 0, 3, 0, - 0, 6, 0, 0, - 1, 2, 0, 0, - 0, 2, -3, 0, - 1, 0, 0, 4, + 0, 0, 0, 0, 5, 8, 0, 0, 0, 0, 3, 0, 0, 6, 0, 0, 1, 2, 0, 0, 0, 2, -3, 0, 1, 0, 0, 4, }; for ( unsigned i = 0; i < 7; ++i ) for ( unsigned j = 0; j < 4; ++j ) - TS_ASSERT_EQUALS( sv1.get( i, j ), expected[i*4 + j] ); + TS_ASSERT_EQUALS( sv1.get( i, j ), expected[i * 4 + j] ); } void test_add_last_column() { { double M1[] = { - 0, 0, 0, 2, - 5, 8, 0, 0, - 0, 0, 3, 0, - 0, 6, 0, 0, + 0, 0, 0, 2, 5, 8, 0, 0, 0, 0, 3, 0, 0, 6, 0, 0, }; SparseUnsortedArrays sv1; @@ -158,25 +136,19 @@ class SparseUnsortedArraysTestSuite : public CxxTest::TestSuite sv1.addLastColumn( col7 ); double expected[] = { - 0, 0, 0, 2, 1, 0, 1, - 5, 8, 0, 0, 2, 2, 0, - 0, 0, 3, 0, 0, -3, 0, - 0, 6, 0, 0, 0, 0, 4, + 0, 0, 0, 2, 1, 0, 1, 5, 8, 0, 0, 2, 2, 0, 0, 0, 3, 0, 0, -3, 0, 0, 6, 0, 0, 0, 0, 4, }; for ( unsigned i = 0; i < 4; ++i ) for ( unsigned j = 0; j < 7; ++j ) - TS_ASSERT_EQUALS( sv1.get( i, j ), expected[i*7 + j] ); + TS_ASSERT_EQUALS( sv1.get( i, j ), expected[i * 7 + j] ); TS_ASSERT_EQUALS( sv1.getNnz(), 11U ); } { double M1[] = { - 0, 0, 0, 0, - 0, 0, 0, 0, - 0, 0, 0, 0, - 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; SparseUnsortedArrays sv1; @@ -186,15 +158,12 @@ class SparseUnsortedArraysTestSuite : public CxxTest::TestSuite sv1.addLastColumn( col5 ); double expected[] = { - 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; for ( unsigned i = 0; i < 4; ++i ) for ( unsigned j = 0; j < 5; ++j ) - TS_ASSERT_EQUALS( sv1.get( i, j ), expected[i*5 + j] ); + TS_ASSERT_EQUALS( sv1.get( i, j ), expected[i * 5 + j] ); TS_ASSERT_EQUALS( sv1.getNnz(), 0U ); } @@ -203,10 +172,7 @@ class SparseUnsortedArraysTestSuite : public CxxTest::TestSuite void test_get_row() { double M1[] = { - 0, 0, 0, 0, - 5, 8, 0, 0, - 0, 0, 3, 0, - 0, 6, 0, 0, + 0, 0, 0, 0, 5, 8, 0, 0, 0, 0, 3, 0, 0, 6, 0, 0, }; SparseUnsortedArrays sv1; @@ -230,10 +196,7 @@ class SparseUnsortedArraysTestSuite : public CxxTest::TestSuite { { double M1[] = { - 0, 0, 0, 0, - 5, 8, 0, 0, - 0, 0, 3, 0, - 0, 6, 0, 0, + 0, 0, 0, 0, 5, 8, 0, 0, 0, 0, 3, 0, 0, 6, 0, 0, }; SparseUnsortedArrays sv1; @@ -243,16 +206,12 @@ class SparseUnsortedArraysTestSuite : public CxxTest::TestSuite TS_ASSERT_THROWS_NOTHING( sv1.toDense( dense ) ); - TS_ASSERT_SAME_DATA( M1, dense, sizeof(M1) ); + TS_ASSERT_SAME_DATA( M1, dense, sizeof( M1 ) ); } { double M1[] = { - 0, 0, 0, 0, - 0, 0, 0, 0, - 5, 8, 0, 0, - 1, 2, 3, 4, - 0, 6, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 0, 0, 1, 2, 3, 4, 0, 6, 0, 0, }; SparseUnsortedArrays sv1; @@ -262,17 +221,14 @@ class SparseUnsortedArraysTestSuite : public CxxTest::TestSuite TS_ASSERT_THROWS_NOTHING( sv1.toDense( dense ) ); - TS_ASSERT_SAME_DATA( M1, dense, sizeof(M1) ); + TS_ASSERT_SAME_DATA( M1, dense, sizeof( M1 ) ); } } void test_get_column() { double M1[] = { - 0, 0, 0, 0, - 5, 8, 0, 0, - 0, 0, 3, 0, - 0, 6, 0, 0, + 0, 0, 0, 0, 5, 8, 0, 0, 0, 0, 3, 0, 0, 6, 0, 0, }; SparseUnsortedArrays sv1; @@ -303,17 +259,11 @@ class SparseUnsortedArraysTestSuite : public CxxTest::TestSuite void test_deletions() { double M1[] = { - 0, 0, 0, 0, - 5, 8, 0, 0, - 0, 0, 3, 0, - 0, 6, 0, 0, + 0, 0, 0, 0, 5, 8, 0, 0, 0, 0, 3, 0, 0, 6, 0, 0, }; double expected[] = { - 0, 0, 0, 0, - 0, 8, 0, 0, - 0, 0, 3, 0, - 0, 0, 0, 0, + 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, }; SparseUnsortedArrays sv1; @@ -328,7 +278,7 @@ class SparseUnsortedArraysTestSuite : public CxxTest::TestSuite for ( unsigned i = 0; i < 4; ++i ) for ( unsigned j = 0; j < 4; ++j ) - TS_ASSERT_EQUALS( sv1.get( i, j ), expected[i*4 + j] ); + TS_ASSERT_EQUALS( sv1.get( i, j ), expected[i * 4 + j] ); TS_ASSERT_THROWS_NOTHING( sv1.set( 1, 1, 0.0 ) ); TS_ASSERT_THROWS_NOTHING( sv1.set( 2, 2, 0.0 ) ); @@ -341,24 +291,15 @@ class SparseUnsortedArraysTestSuite : public CxxTest::TestSuite void test_changes() { double M1[] = { - 0, 0, 0, 0, - 5, 8, 0, 0, - 0, 0, 3, 0, - 0, 6, 0, 0, + 0, 0, 0, 0, 5, 8, 0, 0, 0, 0, 3, 0, 0, 6, 0, 0, }; double expected[] = { - 0, 0, 2, 0, - 5, 8, 0, 0, - 0, 0, 4, 0, - 0, 6, 0, 3, + 0, 0, 2, 0, 5, 8, 0, 0, 0, 0, 4, 0, 0, 6, 0, 3, }; double expected2[] = { - 0, 0, 5, 0, - 5, 8, 0, 0, - 1.5, 0, 4, 0, - 0, 6, 0, 3, + 0, 0, 5, 0, 5, 8, 0, 0, 1.5, 0, 4, 0, 0, 6, 0, 3, }; SparseUnsortedArrays sv1; @@ -370,37 +311,28 @@ class SparseUnsortedArraysTestSuite : public CxxTest::TestSuite for ( unsigned i = 0; i < 4; ++i ) for ( unsigned j = 0; j < 4; ++j ) - TS_ASSERT_EQUALS( sv1.get( i, j ), expected[i*4 + j] ); + TS_ASSERT_EQUALS( sv1.get( i, j ), expected[i * 4 + j] ); sv1.set( 0, 2, 5.0 ); sv1.set( 2, 0, 1.5 ); for ( unsigned i = 0; i < 4; ++i ) for ( unsigned j = 0; j < 4; ++j ) - TS_ASSERT_EQUALS( sv1.get( i, j ), expected2[i*4 + j] ); + TS_ASSERT_EQUALS( sv1.get( i, j ), expected2[i * 4 + j] ); } void test_changes_and_deletions() { double M1[] = { - 0, 0, 0, 0, - 5, 8, 0, 0, - 0, 0, 3, 0, - 0, 6, 0, 0, + 0, 0, 0, 0, 5, 8, 0, 0, 0, 0, 3, 0, 0, 6, 0, 0, }; double expected[] = { - 0, 0, 2, 0, - 5, 0, 0, 0, - 0, 0, 4, 0, - 0, 0, 0, 3, + 0, 0, 2, 0, 5, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 3, }; double expected2[] = { - 0, 0, 2, 0, - 5, 4, 0, 0, - 0, 0, 4, 0, - 0, 0, 0, 0, + 0, 0, 2, 0, 5, 4, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, }; SparseUnsortedArrays sv1; @@ -417,7 +349,7 @@ class SparseUnsortedArraysTestSuite : public CxxTest::TestSuite for ( unsigned i = 0; i < 4; ++i ) for ( unsigned j = 0; j < 4; ++j ) - TS_ASSERT_EQUALS( sv1.get( i, j ), expected[i*4 + j] ); + TS_ASSERT_EQUALS( sv1.get( i, j ), expected[i * 4 + j] ); sv1.set( 1, 0, 5.0 ); sv1.set( 1, 1, 4.0 ); @@ -426,16 +358,13 @@ class SparseUnsortedArraysTestSuite : public CxxTest::TestSuite for ( unsigned i = 0; i < 4; ++i ) for ( unsigned j = 0; j < 4; ++j ) - TS_ASSERT_EQUALS( sv1.get( i, j ), expected2[i*4 + j] ); + TS_ASSERT_EQUALS( sv1.get( i, j ), expected2[i * 4 + j] ); } void test_count_elements() { double M1[] = { - 0, 0, 0, 0, 1, - 5, 8, 0, 0, 2, - 0, 2, 3, 0, 3, - 0, 0, 4, 0, 4, + 0, 0, 0, 0, 1, 5, 8, 0, 0, 2, 0, 2, 3, 0, 3, 0, 0, 4, 0, 4, }; SparseUnsortedArrays sv1; @@ -461,10 +390,7 @@ class SparseUnsortedArraysTestSuite : public CxxTest::TestSuite void test_transpose() { double M1[] = { - 0, 0, 0, 0, 1, - 5, 8, 0, 0, 2, - 0, 2, 3, 0, 3, - 0, 0, 4, 0, 4, + 0, 0, 0, 0, 1, 5, 8, 0, 0, 2, 0, 2, 3, 0, 3, 0, 0, 4, 0, 4, }; SparseUnsortedArrays sv1; @@ -474,28 +400,23 @@ class SparseUnsortedArraysTestSuite : public CxxTest::TestSuite TS_ASSERT_THROWS_NOTHING( sv1.transposeIntoOther( &sv2 ) ); double expected[] = { - 0, 5, 0, 0, - 0, 8, 2, 0, - 0, 0, 3, 4, - 0, 0, 0, 0, - 1, 2, 3, 4, + 0, 5, 0, 0, 0, 8, 2, 0, 0, 0, 3, 4, 0, 0, 0, 0, 1, 2, 3, 4, }; for ( unsigned i = 0; i < 5; ++i ) for ( unsigned j = 0; j < 4; ++j ) - TS_ASSERT_EQUALS( sv2.get( i, j ), expected[i*4 + j] ); + TS_ASSERT_EQUALS( sv2.get( i, j ), expected[i * 4 + j] ); SparseUnsortedArrays sv3; TS_ASSERT_THROWS_NOTHING( sv2.transposeIntoOther( &sv3 ) ); for ( unsigned i = 0; i < 4; ++i ) for ( unsigned j = 0; j < 5; ++j ) - TS_ASSERT_EQUALS( sv3.get( i, j ), M1[i*5 + j] ); + TS_ASSERT_EQUALS( sv3.get( i, j ), M1[i * 5 + j] ); // Transpose an empty matrix double empty[] = { - 0, 0, 0, - 0, 0, 0, + 0, 0, 0, 0, 0, 0, }; SparseUnsortedArrays sv4; @@ -512,10 +433,7 @@ class SparseUnsortedArraysTestSuite : public CxxTest::TestSuite void test_clear() { double M1[] = { - 0, 0, 0, 0, - 5, 8, 0, 0, - 0, 0, 3, 0, - 0, 6, 0, 0, + 0, 0, 0, 0, 5, 8, 0, 0, 0, 0, 3, 0, 0, 6, 0, 0, }; SparseUnsortedArrays sv1; diff --git a/src/basis_factorization/tests/Test_SparseUnsortedList.h b/src/basis_factorization/tests/Test_SparseUnsortedList.h index 72055c76b1..28982a647f 100644 --- a/src/basis_factorization/tests/Test_SparseUnsortedList.h +++ b/src/basis_factorization/tests/Test_SparseUnsortedList.h @@ -13,12 +13,12 @@ **/ -#include - #include "FloatUtils.h" #include "Map.h" #include "SparseUnsortedList.h" +#include + class MockForSparseUnsortedList { public: @@ -51,9 +51,7 @@ class SparseUnsortedListTestSuite : public CxxTest::TestSuite void test_initialize_from_dense() { - double dense[8] = { - 1, 2, 3, 0, 0, 4, 5, 6 - }; + double dense[8] = { 1, 2, 3, 0, 0, 4, 5, 6 }; SparseUnsortedList v1( dense, 8 ); @@ -66,9 +64,7 @@ class SparseUnsortedListTestSuite : public CxxTest::TestSuite void test_cloning() { - double dense[8] = { - 1, 2, 3, 0, 0, 4, 5, 6 - }; + double dense[8] = { 1, 2, 3, 0, 0, 4, 5, 6 }; SparseUnsortedList v1( dense, 8 ); @@ -88,9 +84,7 @@ class SparseUnsortedListTestSuite : public CxxTest::TestSuite void test_iterate() { - double dense[8] = { - 1, 2, 3, 0, 0, 4, 5, 6 - }; + double dense[8] = { 1, 2, 3, 0, 0, 4, 5, 6 }; Map answers; answers[0] = 1; @@ -131,9 +125,7 @@ class SparseUnsortedListTestSuite : public CxxTest::TestSuite double dense[5]; TS_ASSERT_THROWS_NOTHING( v1.toDense( dense ) ); - double expected[5] = { - 4, 0, 3, 0, -7 - }; + double expected[5] = { 4, 0, 3, 0, -7 }; for ( unsigned i = 0; i < 5; ++i ) TS_ASSERT( FloatUtils::areEqual( expected[i], dense[i] ) ); @@ -143,9 +135,7 @@ class SparseUnsortedListTestSuite : public CxxTest::TestSuite TS_ASSERT_THROWS_NOTHING( v1.toDense( dense ) ); - double expected2[5] = { - 4, 5, 0, 0, -7 - }; + double expected2[5] = { 4, 5, 0, 0, -7 }; for ( unsigned i = 0; i < 5; ++i ) TS_ASSERT( FloatUtils::areEqual( expected2[i], dense[i] ) ); diff --git a/src/basis_factorization/tests/Test_SparseUnsortedLists.h b/src/basis_factorization/tests/Test_SparseUnsortedLists.h index bce9e5df5b..cb5446f781 100644 --- a/src/basis_factorization/tests/Test_SparseUnsortedLists.h +++ b/src/basis_factorization/tests/Test_SparseUnsortedLists.h @@ -13,12 +13,12 @@ **/ -#include - #include "FloatUtils.h" #include "MString.h" #include "SparseUnsortedLists.h" +#include + class MockForSparseUnsortedLists { public: @@ -49,42 +49,32 @@ class SparseUnsortedListsTestSuite : public CxxTest::TestSuite // Initialize through empty constructor and initialize(); double M1[] = { - 0, 0, 0, 0, - 5, 8, 0, 0, - 0, 0, 3, 0, - 0, 6, 0, 0, - }; + 0, 0, 0, 0, 5, 8, 0, 0, 0, 0, 3, 0, 0, 6, 0, 0, + }; SparseUnsortedLists sv1; sv1.initialize( M1, 4, 4 ); for ( unsigned i = 0; i < 4; ++i ) for ( unsigned j = 0; j < 4; ++j ) - TS_ASSERT_EQUALS( M1[i*4 + j], sv1.get( i, j ) ); + TS_ASSERT_EQUALS( M1[i * 4 + j], sv1.get( i, j ) ); // Dense matrix, initialize through constructor double M2[] = { - 1, 2, 3, 4, - 5, 8, 5, 6, - 1, 2, 3, 4, - 5, 6, 7, 8, - 9, 1, 2, 3, - }; + 1, 2, 3, 4, 5, 8, 5, 6, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, + }; SparseUnsortedLists sv2; sv2.initialize( M2, 5, 4 ); for ( unsigned i = 0; i < 5; ++i ) for ( unsigned j = 0; j < 4; ++j ) - TS_ASSERT_EQUALS( M2[i*4 + j], sv2.get( i, j ) ); + TS_ASSERT_EQUALS( M2[i * 4 + j], sv2.get( i, j ) ); } void test_store_restore() { double M1[] = { - 0, 0, 0, 0, - 5, 8, 0, 0, - 0, 0, 3, 0, - 0, 6, 0, 0, + 0, 0, 0, 0, 5, 8, 0, 0, 0, 0, 3, 0, 0, 6, 0, 0, }; SparseUnsortedLists sv1; @@ -104,10 +94,7 @@ class SparseUnsortedListsTestSuite : public CxxTest::TestSuite void test_add_last_row() { double M1[] = { - 0, 0, 0, 0, - 5, 8, 0, 0, - 0, 0, 3, 0, - 0, 6, 0, 0, + 0, 0, 0, 0, 5, 8, 0, 0, 0, 0, 3, 0, 0, 6, 0, 0, }; SparseUnsortedLists sv1; @@ -122,28 +109,19 @@ class SparseUnsortedListsTestSuite : public CxxTest::TestSuite sv1.addLastRow( row7 ); double expected[] = { - 0, 0, 0, 0, - 5, 8, 0, 0, - 0, 0, 3, 0, - 0, 6, 0, 0, - 1, 2, 0, 0, - 0, 2, -3, 0, - 1, 0, 0, 4, + 0, 0, 0, 0, 5, 8, 0, 0, 0, 0, 3, 0, 0, 6, 0, 0, 1, 2, 0, 0, 0, 2, -3, 0, 1, 0, 0, 4, }; for ( unsigned i = 0; i < 7; ++i ) for ( unsigned j = 0; j < 4; ++j ) - TS_ASSERT_EQUALS( sv1.get( i, j ), expected[i*4 + j] ); + TS_ASSERT_EQUALS( sv1.get( i, j ), expected[i * 4 + j] ); } void test_add_last_column() { { double M1[] = { - 0, 0, 0, 2, - 5, 8, 0, 0, - 0, 0, 3, 0, - 0, 6, 0, 0, + 0, 0, 0, 2, 5, 8, 0, 0, 0, 0, 3, 0, 0, 6, 0, 0, }; SparseUnsortedLists sv1; @@ -158,25 +136,19 @@ class SparseUnsortedListsTestSuite : public CxxTest::TestSuite sv1.addLastColumn( col7 ); double expected[] = { - 0, 0, 0, 2, 1, 0, 1, - 5, 8, 0, 0, 2, 2, 0, - 0, 0, 3, 0, 0, -3, 0, - 0, 6, 0, 0, 0, 0, 4, + 0, 0, 0, 2, 1, 0, 1, 5, 8, 0, 0, 2, 2, 0, 0, 0, 3, 0, 0, -3, 0, 0, 6, 0, 0, 0, 0, 4, }; for ( unsigned i = 0; i < 4; ++i ) for ( unsigned j = 0; j < 7; ++j ) - TS_ASSERT_EQUALS( sv1.get( i, j ), expected[i*7 + j] ); + TS_ASSERT_EQUALS( sv1.get( i, j ), expected[i * 7 + j] ); TS_ASSERT_EQUALS( sv1.getNnz(), 11U ); } { double M1[] = { - 0, 0, 0, 0, - 0, 0, 0, 0, - 0, 0, 0, 0, - 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; SparseUnsortedLists sv1; @@ -186,15 +158,12 @@ class SparseUnsortedListsTestSuite : public CxxTest::TestSuite sv1.addLastColumn( col5 ); double expected[] = { - 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; for ( unsigned i = 0; i < 4; ++i ) for ( unsigned j = 0; j < 5; ++j ) - TS_ASSERT_EQUALS( sv1.get( i, j ), expected[i*5 + j] ); + TS_ASSERT_EQUALS( sv1.get( i, j ), expected[i * 5 + j] ); TS_ASSERT_EQUALS( sv1.getNnz(), 0U ); } @@ -203,10 +172,7 @@ class SparseUnsortedListsTestSuite : public CxxTest::TestSuite void test_get_row() { double M1[] = { - 0, 0, 0, 0, - 5, 8, 0, 0, - 0, 0, 3, 0, - 0, 6, 0, 0, + 0, 0, 0, 0, 5, 8, 0, 0, 0, 0, 3, 0, 0, 6, 0, 0, }; SparseUnsortedLists sv1; @@ -230,10 +196,7 @@ class SparseUnsortedListsTestSuite : public CxxTest::TestSuite { { double M1[] = { - 0, 0, 0, 0, - 5, 8, 0, 0, - 0, 0, 3, 0, - 0, 6, 0, 0, + 0, 0, 0, 0, 5, 8, 0, 0, 0, 0, 3, 0, 0, 6, 0, 0, }; SparseUnsortedLists sv1; @@ -243,16 +206,12 @@ class SparseUnsortedListsTestSuite : public CxxTest::TestSuite TS_ASSERT_THROWS_NOTHING( sv1.toDense( dense ) ); - TS_ASSERT_SAME_DATA( M1, dense, sizeof(M1) ); + TS_ASSERT_SAME_DATA( M1, dense, sizeof( M1 ) ); } { double M1[] = { - 0, 0, 0, 0, - 0, 0, 0, 0, - 5, 8, 0, 0, - 1, 2, 3, 4, - 0, 6, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 0, 0, 1, 2, 3, 4, 0, 6, 0, 0, }; SparseUnsortedLists sv1; @@ -262,17 +221,14 @@ class SparseUnsortedListsTestSuite : public CxxTest::TestSuite TS_ASSERT_THROWS_NOTHING( sv1.toDense( dense ) ); - TS_ASSERT_SAME_DATA( M1, dense, sizeof(M1) ); + TS_ASSERT_SAME_DATA( M1, dense, sizeof( M1 ) ); } } void test_get_column() { double M1[] = { - 0, 0, 0, 0, - 5, 8, 0, 0, - 0, 0, 3, 0, - 0, 6, 0, 0, + 0, 0, 0, 0, 5, 8, 0, 0, 0, 0, 3, 0, 0, 6, 0, 0, }; SparseUnsortedLists sv1; @@ -303,17 +259,11 @@ class SparseUnsortedListsTestSuite : public CxxTest::TestSuite void test_deletions() { double M1[] = { - 0, 0, 0, 0, - 5, 8, 0, 0, - 0, 0, 3, 0, - 0, 6, 0, 0, + 0, 0, 0, 0, 5, 8, 0, 0, 0, 0, 3, 0, 0, 6, 0, 0, }; double expected[] = { - 0, 0, 0, 0, - 0, 8, 0, 0, - 0, 0, 3, 0, - 0, 0, 0, 0, + 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, }; SparseUnsortedLists sv1; @@ -328,7 +278,7 @@ class SparseUnsortedListsTestSuite : public CxxTest::TestSuite for ( unsigned i = 0; i < 4; ++i ) for ( unsigned j = 0; j < 4; ++j ) - TS_ASSERT_EQUALS( sv1.get( i, j ), expected[i*4 + j] ); + TS_ASSERT_EQUALS( sv1.get( i, j ), expected[i * 4 + j] ); TS_ASSERT_THROWS_NOTHING( sv1.set( 1, 1, 0.0 ) ); TS_ASSERT_THROWS_NOTHING( sv1.set( 2, 2, 0.0 ) ); @@ -341,24 +291,15 @@ class SparseUnsortedListsTestSuite : public CxxTest::TestSuite void test_changes() { double M1[] = { - 0, 0, 0, 0, - 5, 8, 0, 0, - 0, 0, 3, 0, - 0, 6, 0, 0, + 0, 0, 0, 0, 5, 8, 0, 0, 0, 0, 3, 0, 0, 6, 0, 0, }; double expected[] = { - 0, 0, 2, 0, - 5, 8, 0, 0, - 0, 0, 4, 0, - 0, 6, 0, 3, + 0, 0, 2, 0, 5, 8, 0, 0, 0, 0, 4, 0, 0, 6, 0, 3, }; double expected2[] = { - 0, 0, 5, 0, - 5, 8, 0, 0, - 1.5, 0, 4, 0, - 0, 6, 0, 3, + 0, 0, 5, 0, 5, 8, 0, 0, 1.5, 0, 4, 0, 0, 6, 0, 3, }; SparseUnsortedLists sv1; @@ -370,37 +311,28 @@ class SparseUnsortedListsTestSuite : public CxxTest::TestSuite for ( unsigned i = 0; i < 4; ++i ) for ( unsigned j = 0; j < 4; ++j ) - TS_ASSERT_EQUALS( sv1.get( i, j ), expected[i*4 + j] ); + TS_ASSERT_EQUALS( sv1.get( i, j ), expected[i * 4 + j] ); sv1.set( 0, 2, 5.0 ); sv1.set( 2, 0, 1.5 ); for ( unsigned i = 0; i < 4; ++i ) for ( unsigned j = 0; j < 4; ++j ) - TS_ASSERT_EQUALS( sv1.get( i, j ), expected2[i*4 + j] ); + TS_ASSERT_EQUALS( sv1.get( i, j ), expected2[i * 4 + j] ); } void test_changes_and_deletions() { double M1[] = { - 0, 0, 0, 0, - 5, 8, 0, 0, - 0, 0, 3, 0, - 0, 6, 0, 0, + 0, 0, 0, 0, 5, 8, 0, 0, 0, 0, 3, 0, 0, 6, 0, 0, }; double expected[] = { - 0, 0, 2, 0, - 5, 0, 0, 0, - 0, 0, 4, 0, - 0, 0, 0, 3, + 0, 0, 2, 0, 5, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 3, }; double expected2[] = { - 0, 0, 2, 0, - 5, 4, 0, 0, - 0, 0, 4, 0, - 0, 0, 0, 0, + 0, 0, 2, 0, 5, 4, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, }; SparseUnsortedLists sv1; @@ -417,7 +349,7 @@ class SparseUnsortedListsTestSuite : public CxxTest::TestSuite for ( unsigned i = 0; i < 4; ++i ) for ( unsigned j = 0; j < 4; ++j ) - TS_ASSERT_EQUALS( sv1.get( i, j ), expected[i*4 + j] ); + TS_ASSERT_EQUALS( sv1.get( i, j ), expected[i * 4 + j] ); sv1.set( 1, 0, 5.0 ); sv1.set( 1, 1, 4.0 ); @@ -426,16 +358,13 @@ class SparseUnsortedListsTestSuite : public CxxTest::TestSuite for ( unsigned i = 0; i < 4; ++i ) for ( unsigned j = 0; j < 4; ++j ) - TS_ASSERT_EQUALS( sv1.get( i, j ), expected2[i*4 + j] ); + TS_ASSERT_EQUALS( sv1.get( i, j ), expected2[i * 4 + j] ); } void test_count_elements() { double M1[] = { - 0, 0, 0, 0, 1, - 5, 8, 0, 0, 2, - 0, 2, 3, 0, 3, - 0, 0, 4, 0, 4, + 0, 0, 0, 0, 1, 5, 8, 0, 0, 2, 0, 2, 3, 0, 3, 0, 0, 4, 0, 4, }; SparseUnsortedLists sv1; @@ -461,10 +390,7 @@ class SparseUnsortedListsTestSuite : public CxxTest::TestSuite void test_transpose() { double M1[] = { - 0, 0, 0, 0, 1, - 5, 8, 0, 0, 2, - 0, 2, 3, 0, 3, - 0, 0, 4, 0, 4, + 0, 0, 0, 0, 1, 5, 8, 0, 0, 2, 0, 2, 3, 0, 3, 0, 0, 4, 0, 4, }; SparseUnsortedLists sv1; @@ -474,28 +400,23 @@ class SparseUnsortedListsTestSuite : public CxxTest::TestSuite TS_ASSERT_THROWS_NOTHING( sv1.transposeIntoOther( &sv2 ) ); double expected[] = { - 0, 5, 0, 0, - 0, 8, 2, 0, - 0, 0, 3, 4, - 0, 0, 0, 0, - 1, 2, 3, 4, + 0, 5, 0, 0, 0, 8, 2, 0, 0, 0, 3, 4, 0, 0, 0, 0, 1, 2, 3, 4, }; for ( unsigned i = 0; i < 5; ++i ) for ( unsigned j = 0; j < 4; ++j ) - TS_ASSERT_EQUALS( sv2.get( i, j ), expected[i*4 + j] ); + TS_ASSERT_EQUALS( sv2.get( i, j ), expected[i * 4 + j] ); SparseUnsortedLists sv3; TS_ASSERT_THROWS_NOTHING( sv2.transposeIntoOther( &sv3 ) ); for ( unsigned i = 0; i < 4; ++i ) for ( unsigned j = 0; j < 5; ++j ) - TS_ASSERT_EQUALS( sv3.get( i, j ), M1[i*5 + j] ); + TS_ASSERT_EQUALS( sv3.get( i, j ), M1[i * 5 + j] ); // Transpose an empty matrix double empty[] = { - 0, 0, 0, - 0, 0, 0, + 0, 0, 0, 0, 0, 0, }; SparseUnsortedLists sv4; @@ -512,10 +433,7 @@ class SparseUnsortedListsTestSuite : public CxxTest::TestSuite void test_clear() { double M1[] = { - 0, 0, 0, 0, - 5, 8, 0, 0, - 0, 0, 3, 0, - 0, 6, 0, 0, + 0, 0, 0, 0, 5, 8, 0, 0, 0, 0, 3, 0, 0, 6, 0, 0, }; SparseUnsortedLists sv1; diff --git a/src/common/AutoFile.h b/src/common/AutoFile.h index fa611b0893..9380fdb9c2 100644 --- a/src/common/AutoFile.h +++ b/src/common/AutoFile.h @@ -22,29 +22,29 @@ class AutoFile { public: - AutoFile( const String &path ) - { - _file = T::createFile( path ); - } - - ~AutoFile() - { - T::discardFile( _file ); - _file = 0; - } - - operator IFile &() - { - return *_file; - } - - IFile *operator->() - { - return _file; - } + AutoFile( const String &path ) + { + _file = T::createFile( path ); + } + + ~AutoFile() + { + T::discardFile( _file ); + _file = 0; + } + + operator IFile &() + { + return *_file; + } + + IFile *operator->() + { + return _file; + } private: - IFile *_file; + IFile *_file; }; #endif // __AutoFile_h__ diff --git a/src/common/CommonError.h b/src/common/CommonError.h index 67dab9df60..2b64247d8f 100644 --- a/src/common/CommonError.h +++ b/src/common/CommonError.h @@ -21,7 +21,7 @@ class CommonError : public Error { public: - enum Code { + enum Code { QUEUE_IS_EMPTY = 0, VALUE_DOESNT_EXIST_IN_VECTOR = 1, VECTOR_OUT_OF_BOUNDS = 2, @@ -41,11 +41,13 @@ class CommonError : public Error UNEXPECTED_GUROBI_STATUS = 16, }; - CommonError( CommonError::Code code ) : Error( "CommonError", (int)code ) - { - } + CommonError( CommonError::Code code ) + : Error( "CommonError", (int)code ) + { + } - CommonError( CommonError::Code code, const char *userMessage ) : Error( "CommonError", (int)code, userMessage ) + CommonError( CommonError::Code code, const char *userMessage ) + : Error( "CommonError", (int)code, userMessage ) { } }; diff --git a/src/common/ConstSimpleData.cpp b/src/common/ConstSimpleData.cpp index 334444ef39..99bd851a2f 100644 --- a/src/common/ConstSimpleData.cpp +++ b/src/common/ConstSimpleData.cpp @@ -14,14 +14,19 @@ **/ #include "ConstSimpleData.h" + #include "HeapData.h" #include "MStringf.h" -ConstSimpleData::ConstSimpleData( const void *data, unsigned size ) : _data( data ), _size( size ) +ConstSimpleData::ConstSimpleData( const void *data, unsigned size ) + : _data( data ) + , _size( size ) { } -ConstSimpleData::ConstSimpleData( const HeapData &data ) : _data( data.data() ), _size( data.size() ) +ConstSimpleData::ConstSimpleData( const HeapData &data ) + : _data( data.data() ) + , _size( data.size() ) { } diff --git a/src/common/ConstSimpleData.h b/src/common/ConstSimpleData.h index 8e0d131692..e3a574b3ff 100644 --- a/src/common/ConstSimpleData.h +++ b/src/common/ConstSimpleData.h @@ -24,17 +24,17 @@ class String; class ConstSimpleData { public: - ConstSimpleData( const void *data, unsigned size ); + ConstSimpleData( const void *data, unsigned size ); ConstSimpleData( const HeapData &data ); - const void *data() const; + const void *data() const; unsigned size() const; const char *asChar() const; void hexDump() const; String toString() const; private: - const void *_data; - unsigned _size; + const void *_data; + unsigned _size; }; #endif // __ConstSimpleData_h__ diff --git a/src/common/Debug.h b/src/common/Debug.h index e25ba32cb2..646891499c 100644 --- a/src/common/Debug.h +++ b/src/common/Debug.h @@ -21,47 +21,49 @@ #ifndef NDEBUG -# define DEBUG(x) x +#define DEBUG( x ) x #else -# define DEBUG(x) +#define DEBUG( x ) #endif #ifndef NDEBUG -# define LOG(x, f, y, ...) \ - { \ - if ( ( x ) ) \ - { \ - printf( f, y ); \ - } \ +#define LOG( x, f, y, ... ) \ + { \ + if ( ( x ) ) \ + { \ + printf( f, y ); \ + } \ } #else -# define LOG(x, f, y, ...) {} +#define LOG( x, f, y, ... ) \ + { \ + } #endif #ifndef NDEBUG -# define ASSERTM(x, y, ...) \ - { \ - if ( !( x ) ) \ - { \ - printf( y ); \ - exit( 1 ); \ - } \ +#define ASSERTM( x, y, ... ) \ + { \ + if ( !( x ) ) \ + { \ + printf( y ); \ + exit( 1 ); \ + } \ } #else -# define ASSERTM(x, y, ...) +#define ASSERTM( x, y, ... ) #endif #ifndef NDEBUG -# define ASSERT(x) \ - { \ - if ( !( x ) ) \ - { \ - printf( "Assertion violation! File %s, line %d\n", __FILE__, __LINE__ ); \ - exit( 1 ); \ - } \ +#define ASSERT( x ) \ + { \ + if ( !( x ) ) \ + { \ + printf( "Assertion violation! File %s, line %d\n", __FILE__, __LINE__ ); \ + exit( 1 ); \ + } \ } #else -# define ASSERT(x) +#define ASSERT( x ) #endif #endif // __Debug_h__ diff --git a/src/common/Error.cpp b/src/common/Error.cpp index bb441ab07e..beff2ba98f 100644 --- a/src/common/Error.cpp +++ b/src/common/Error.cpp @@ -14,23 +14,27 @@ **/ #include "Error.h" + #include "T/Errno.h" + #include #include -Error::Error( const char *errorClass, int code ) : _code( code ) +Error::Error( const char *errorClass, int code ) + : _code( code ) { - memset( _errorClass, 0, sizeof(_userMessage) ); - memset( _userMessage, 0, sizeof(_userMessage) ); + memset( _errorClass, 0, sizeof( _userMessage ) ); + memset( _userMessage, 0, sizeof( _userMessage ) ); strncpy( _errorClass, errorClass, BUFFER_SIZE - 1 ); _errno = T::errorNumber(); } -Error::Error( const char *errorClass, int code, const char *userMessage ) : _code( code ) +Error::Error( const char *errorClass, int code, const char *userMessage ) + : _code( code ) { - memset( _errorClass, 0, sizeof(_userMessage) ); - memset( _userMessage, 0, sizeof(_userMessage) ); + memset( _errorClass, 0, sizeof( _userMessage ) ); + memset( _userMessage, 0, sizeof( _userMessage ) ); strncpy( _errorClass, errorClass, BUFFER_SIZE - 1 ); setUserMessage( userMessage ); diff --git a/src/common/File.cpp b/src/common/File.cpp index f9cf85a720..914d5d817a 100644 --- a/src/common/File.cpp +++ b/src/common/File.cpp @@ -13,16 +13,19 @@ **/ +#include "File.h" + #include "CommonError.h" #include "ConstSimpleData.h" -#include "File.h" #include "HeapData.h" #include "MStringf.h" #include "T/sys/stat.h" #include "T/unistd.h" #include "Vector.h" -File::File( const String &path ) : _path( path ), _descriptor( NO_DESCRIPTOR ) +File::File( const String &path ) + : _path( path ) + , _descriptor( NO_DESCRIPTOR ) { } @@ -39,7 +42,7 @@ void File::close() bool File::directory( const String &path ) { struct stat fileData; - memset( &fileData, 0, sizeof(struct stat) ); + memset( &fileData, 0, sizeof( struct stat ) ); if ( T::stat( path.ascii(), &fileData ) == 0 ) return S_ISDIR( fileData.st_mode ); @@ -50,7 +53,7 @@ bool File::directory( const String &path ) unsigned File::getSize( const String &path ) { struct stat dataBuffer; - memset( &dataBuffer, 0, sizeof(dataBuffer) ); + memset( &dataBuffer, 0, sizeof( dataBuffer ) ); if ( T::stat( path.ascii(), &dataBuffer ) != 0 ) throw CommonError( CommonError::STAT_FAILED ); @@ -97,7 +100,7 @@ void File::read( HeapData &buffer, unsigned maxReadSize ) char *readBuffer( readVector.data() ); int bytesRead; - if ( ( bytesRead = T::read( _descriptor, readBuffer, sizeof(readBuffer) ) ) == -1 ) + if ( ( bytesRead = T::read( _descriptor, readBuffer, sizeof( readBuffer ) ) ) == -1 ) throw CommonError( CommonError::READ_FAILED ); buffer = ConstSimpleData( readBuffer, bytesRead ); @@ -114,7 +117,7 @@ String File::readLine( char lineSeparatingChar ) while ( !_readLineBuffer.contains( separatorAsString ) ) { char *buffer = new char[SIZE_OF_BUFFER + 1]; - int n = T::read( _descriptor, buffer, sizeof(char) * SIZE_OF_BUFFER ); + int n = T::read( _descriptor, buffer, sizeof( char ) * SIZE_OF_BUFFER ); if ( ( n == -1 ) || ( n == 0 ) ) { delete[] buffer; diff --git a/src/common/File.h b/src/common/File.h index 10b322e2be..9403d2ff13 100644 --- a/src/common/File.h +++ b/src/common/File.h @@ -24,7 +24,7 @@ class HeapData; #ifdef _WIN32 #include -#define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR) +#define S_ISDIR( mode ) ( ( (mode)&S_IFMT ) == S_IFDIR ) typedef int mode_t; @@ -36,27 +36,27 @@ typedef int mode_t; /// @Note For the POSIX modes that do not have a Windows equivalent, the modes /// defined here use the POSIX values left shifted 16 bits. -static const mode_t S_ISUID = 0x08000000; ///< does nothing -static const mode_t S_ISGID = 0x04000000; ///< does nothing -static const mode_t S_ISVTX = 0x02000000; ///< does nothing -static const mode_t S_IRUSR = mode_t(_S_IREAD); ///< read by user -static const mode_t S_IWUSR = mode_t(_S_IWRITE); ///< write by user -static const mode_t S_IXUSR = 0x00400000; ///< does nothing -# ifndef STRICT_UGO_PERMISSIONS -static const mode_t S_IRGRP = mode_t(_S_IREAD); ///< read by *USER* -static const mode_t S_IWGRP = mode_t(_S_IWRITE); ///< write by *USER* -static const mode_t S_IXGRP = 0x00080000; ///< does nothing -static const mode_t S_IROTH = mode_t(_S_IREAD); ///< read by *USER* -static const mode_t S_IWOTH = mode_t(_S_IWRITE); ///< write by *USER* -static const mode_t S_IXOTH = 0x00010000; ///< does nothing -# else -static const mode_t S_IRGRP = 0x00200000; ///< does nothing -static const mode_t S_IWGRP = 0x00100000; ///< does nothing -static const mode_t S_IXGRP = 0x00080000; ///< does nothing -static const mode_t S_IROTH = 0x00040000; ///< does nothing -static const mode_t S_IWOTH = 0x00020000; ///< does nothing -static const mode_t S_IXOTH = 0x00010000; ///< does nothing -# endif +static const mode_t S_ISUID = 0x08000000; ///< does nothing +static const mode_t S_ISGID = 0x04000000; ///< does nothing +static const mode_t S_ISVTX = 0x02000000; ///< does nothing +static const mode_t S_IRUSR = mode_t( _S_IREAD ); ///< read by user +static const mode_t S_IWUSR = mode_t( _S_IWRITE ); ///< write by user +static const mode_t S_IXUSR = 0x00400000; ///< does nothing +#ifndef STRICT_UGO_PERMISSIONS +static const mode_t S_IRGRP = mode_t( _S_IREAD ); ///< read by *USER* +static const mode_t S_IWGRP = mode_t( _S_IWRITE ); ///< write by *USER* +static const mode_t S_IXGRP = 0x00080000; ///< does nothing +static const mode_t S_IROTH = mode_t( _S_IREAD ); ///< read by *USER* +static const mode_t S_IWOTH = mode_t( _S_IWRITE ); ///< write by *USER* +static const mode_t S_IXOTH = 0x00010000; ///< does nothing +#else +static const mode_t S_IRGRP = 0x00200000; ///< does nothing +static const mode_t S_IWGRP = 0x00100000; ///< does nothing +static const mode_t S_IXGRP = 0x00080000; ///< does nothing +static const mode_t S_IROTH = 0x00040000; ///< does nothing +static const mode_t S_IWOTH = 0x00020000; ///< does nothing +static const mode_t S_IXOTH = 0x00010000; ///< does nothing +#endif #endif class File : public IFile diff --git a/src/common/FloatUtils.cpp b/src/common/FloatUtils.cpp index 1bbc1bb566..aae10f1600 100644 --- a/src/common/FloatUtils.cpp +++ b/src/common/FloatUtils.cpp @@ -14,6 +14,7 @@ **/ #include "FloatUtils.h" + #include #include @@ -41,13 +42,13 @@ bool FloatUtils::areEqual( double x, double y, double epsilon ) String FloatUtils::doubleToString( double x, unsigned precision ) { std::ostringstream strout; - strout << std::fixed << std::setprecision(precision) << x; + strout << std::fixed << std::setprecision( precision ) << x; std::string str = strout.str(); size_t end = str.find_last_not_of( '0' ) + 1; str.erase( end ); if ( str[str.size() - 1] == '.' ) - str = str.substr(0, str.size() - 1); + str = str.substr( 0, str.size() - 1 ); return str; } diff --git a/src/common/FloatUtils.h b/src/common/FloatUtils.h index 7a32b3cd23..a5c3e6cee6 100644 --- a/src/common/FloatUtils.h +++ b/src/common/FloatUtils.h @@ -31,31 +31,37 @@ class FloatUtils { public: - static bool areEqual( double x, double y, double epsilon = GlobalConfiguration::DEFAULT_EPSILON_FOR_COMPARISONS ); - static String doubleToString( double x, - unsigned precision = GlobalConfiguration::DEFAULT_DOUBLE_TO_STRING_PRECISION ); + static bool areEqual( double x, + double y, + double epsilon = GlobalConfiguration::DEFAULT_EPSILON_FOR_COMPARISONS ); + static String + doubleToString( double x, + unsigned precision = GlobalConfiguration::DEFAULT_DOUBLE_TO_STRING_PRECISION ); static bool isNan( double x ); static bool isInf( double x ); - static bool isZero( double x, double epsilon = GlobalConfiguration::DEFAULT_EPSILON_FOR_COMPARISONS ) + static bool isZero( double x, + double epsilon = GlobalConfiguration::DEFAULT_EPSILON_FOR_COMPARISONS ) { - ASSERT( epsilon > 0 ); - double lower = -epsilon; - double upper = epsilon; + ASSERT( epsilon > 0 ); + double lower = -epsilon; + double upper = epsilon; return ( x - upper ) * ( x - lower ) <= 0; } - static bool isPositive( double x, double epsilon = GlobalConfiguration::DEFAULT_EPSILON_FOR_COMPARISONS ) + static bool isPositive( double x, + double epsilon = GlobalConfiguration::DEFAULT_EPSILON_FOR_COMPARISONS ) { - ASSERT( epsilon > 0 ); + ASSERT( epsilon > 0 ); return x > epsilon; } - static bool isNegative( double x, double epsilon = GlobalConfiguration::DEFAULT_EPSILON_FOR_COMPARISONS ) + static bool isNegative( double x, + double epsilon = GlobalConfiguration::DEFAULT_EPSILON_FOR_COMPARISONS ) { - ASSERT( epsilon > 0 ); + ASSERT( epsilon > 0 ); return x < -epsilon; } @@ -71,50 +77,57 @@ class FloatUtils return !areEqual( x, y, epsilon ); } - static double roundToZero( double x, double epsilon = GlobalConfiguration::DEFAULT_EPSILON_FOR_COMPARISONS ) + static double + roundToZero( double x, double epsilon = GlobalConfiguration::DEFAULT_EPSILON_FOR_COMPARISONS ) { return isZero( x, epsilon ) ? 0.0 : x; } - static bool gt( double x, double y, double epsilon = GlobalConfiguration::DEFAULT_EPSILON_FOR_COMPARISONS ) + static bool + gt( double x, double y, double epsilon = GlobalConfiguration::DEFAULT_EPSILON_FOR_COMPARISONS ) { return isPositive( x - y, epsilon ); } - static bool gte( double x, double y, double epsilon = GlobalConfiguration::DEFAULT_EPSILON_FOR_COMPARISONS ) + static bool + gte( double x, double y, double epsilon = GlobalConfiguration::DEFAULT_EPSILON_FOR_COMPARISONS ) { return !isNegative( x - y, epsilon ); } - static bool lt( double x, double y, double epsilon = GlobalConfiguration::DEFAULT_EPSILON_FOR_COMPARISONS ) + static bool + lt( double x, double y, double epsilon = GlobalConfiguration::DEFAULT_EPSILON_FOR_COMPARISONS ) { return gt( y, x, epsilon ); } - static bool lte( double x, double y, double epsilon = GlobalConfiguration::DEFAULT_EPSILON_FOR_COMPARISONS ) + static bool + lte( double x, double y, double epsilon = GlobalConfiguration::DEFAULT_EPSILON_FOR_COMPARISONS ) { return gte( y, x, epsilon ); } - static double min( double x, double y, double epsilon = GlobalConfiguration::DEFAULT_EPSILON_FOR_COMPARISONS ) + static double + min( double x, double y, double epsilon = GlobalConfiguration::DEFAULT_EPSILON_FOR_COMPARISONS ) { return lt( x, y, epsilon ) ? x : y; } - static double max( double x, double y, double epsilon = GlobalConfiguration::DEFAULT_EPSILON_FOR_COMPARISONS ) + static double + max( double x, double y, double epsilon = GlobalConfiguration::DEFAULT_EPSILON_FOR_COMPARISONS ) { return gt( x, y, epsilon ) ? x : y; } - static double round( double x, double epsilon = GlobalConfiguration::DEFAULT_EPSILON_FOR_COMPARISONS ) + static double round( double x, + double epsilon = GlobalConfiguration::DEFAULT_EPSILON_FOR_COMPARISONS ) { // # Implement pytorch round https://pytorch.org/docs/stable/generated/torch.round.html // "Values equidistant from two integers are rounded towards the nearest even value" // i.e., round(2.5) == round(1.5) == 2 double f = floor( x ); double c = ceil( x ); - if ( areEqual( x - f, 0.5, epsilon ) && - areEqual( c - x, 0.5, epsilon ) ) + if ( areEqual( x - f, 0.5, epsilon ) && areEqual( c - x, 0.5, epsilon ) ) return ( (int)c % 2 == 0 ) ? c : f; else return gt( x - f, 0.5, epsilon ) ? c : f; @@ -139,7 +152,6 @@ class FloatUtils { return !isNan( x ) && !isInf( x ); } - }; #endif // __FloatUtils_h__ diff --git a/src/common/GetCPUData.h b/src/common/GetCPUData.h index 34ac5590b4..a08e329576 100644 --- a/src/common/GetCPUData.h +++ b/src/common/GetCPUData.h @@ -18,23 +18,30 @@ #if defined( __linux__ ) #include -#define getCPUId( cpu ) { cpu = sched_getcpu(); } -#elif __APPLE__ && (!defined(__arm64__)) +#define getCPUId( cpu ) \ + { \ + cpu = sched_getcpu(); \ + } +#elif __APPLE__ && ( !defined( __arm64__ ) ) #include -#define CPUId( INFO, LEAF, SUBLEAF ) __cpuid_count( LEAF, SUBLEAF, INFO[0], \ - INFO[1], INFO[2], INFO[3] ) -#define getCPUId( cpu ) { \ - uint32_t CPUInfo[4]; \ - CPUId( CPUInfo, 1, 0 ); \ - if ( ( CPUInfo[3] & ( 1 << 9 ) ) == 0) { \ - cpu = -1; \ - } \ - else { \ - cpu = ( unsigned )CPUInfo[1] >> 24; \ - } \ - if ( cpu < 0 ) cpu = 0; \ - } +#define CPUId( INFO, LEAF, SUBLEAF ) \ + __cpuid_count( LEAF, SUBLEAF, INFO[0], INFO[1], INFO[2], INFO[3] ) +#define getCPUId( cpu ) \ + { \ + uint32_t CPUInfo[4]; \ + CPUId( CPUInfo, 1, 0 ); \ + if ( ( CPUInfo[3] & ( 1 << 9 ) ) == 0 ) \ + { \ + cpu = -1; \ + } \ + else \ + { \ + cpu = (unsigned)CPUInfo[1] >> 24; \ + } \ + if ( cpu < 0 ) \ + cpu = 0; \ + } #else #define getCPUId( cpu ) "#" #endif diff --git a/src/common/GurobiWrapper.cpp b/src/common/GurobiWrapper.cpp index 5c645f3914..f0a21557cd 100644 --- a/src/common/GurobiWrapper.cpp +++ b/src/common/GurobiWrapper.cpp @@ -15,10 +15,11 @@ #ifdef ENABLE_GUROBI +#include "GurobiWrapper.h" + #include "Debug.h" #include "FloatUtils.h" #include "GlobalConfiguration.h" -#include "GurobiWrapper.h" #include "MStringf.h" #include "Options.h" #include "gurobi_c.h" @@ -77,19 +78,14 @@ void GurobiWrapper::resetModel() _model->getEnv().set( GRB_IntParam_OutputFlag, 0 ); // Thread number - _model->getEnv().set( GRB_IntParam_Threads, - GlobalConfiguration::GUROBI_NUMBER_OF_THREADS ); + _model->getEnv().set( GRB_IntParam_Threads, GlobalConfiguration::GUROBI_NUMBER_OF_THREADS ); // Numeral parameters - _model->getEnv().set - ( GRB_DoubleParam_FeasibilityTol, - std::max - ( GlobalConfiguration::DEFAULT_EPSILON_FOR_COMPARISONS, 1e-9 ) ); + _model->getEnv().set( GRB_DoubleParam_FeasibilityTol, + std::max( GlobalConfiguration::DEFAULT_EPSILON_FOR_COMPARISONS, 1e-9 ) ); - _model->getEnv().set - ( GRB_DoubleParam_IntFeasTol, - std::max - ( GlobalConfiguration::CONSTRAINT_COMPARISON_TOLERANCE, 1e-8 ) ); + _model->getEnv().set( GRB_DoubleParam_IntFeasTol, + std::max( GlobalConfiguration::CONSTRAINT_COMPARISON_TOLERANCE, 1e-8 ) ); // Timeout setTimeLimit( _timeoutInSeconds ); @@ -128,11 +124,7 @@ void GurobiWrapper::addVariable( String name, double lb, double ub, VariableType { GRBVar *newVar = new GRBVar; double objectiveValue = 0; - *newVar = _model->addVar( lb, - ub, - objectiveValue, - variableType, - name.ascii() ); + *newVar = _model->addVar( lb, ub, objectiveValue, variableType, name.ascii() ); _nameToVariable[name] = newVar; } @@ -141,7 +133,8 @@ void GurobiWrapper::addVariable( String name, double lb, double ub, VariableType throw CommonError( CommonError::GUROBI_EXCEPTION, Stringf( "Gurobi exception. Gurobi Code: %u, message: %s\n", e.getErrorCode(), - e.getMessage().c_str() ).ascii() ); + e.getMessage().c_str() ) + .ascii() ); } } @@ -197,7 +190,8 @@ void GurobiWrapper::addConstraint( const List &terms, double scalar, char throw CommonError( CommonError::GUROBI_EXCEPTION, Stringf( "Gurobi exception. Gurobi Code: %u, message: %s\n", e.getErrorCode(), - e.getMessage().c_str() ).ascii() ); + e.getMessage().c_str() ) + .ascii() ); } } @@ -215,31 +209,45 @@ void GurobiWrapper::addPiecewiseLinearConstraint( String sourceVariable, xPoints, yPoints ); } - catch (GRBException e ) + catch ( GRBException e ) { throw CommonError( CommonError::GUROBI_EXCEPTION, Stringf( "Gurobi exception. Gurobi Code: %u, message: %s\n", e.getErrorCode(), - e.getMessage().c_str() ).ascii() ); + e.getMessage().c_str() ) + .ascii() ); } } -void GurobiWrapper::addLeqIndicatorConstraint( const String binVarName, const int binVal, const List &terms, double scalar ) +void GurobiWrapper::addLeqIndicatorConstraint( const String binVarName, + const int binVal, + const List &terms, + double scalar ) { addIndicatorConstraint( binVarName, binVal, terms, scalar, GRB_LESS_EQUAL ); } -void GurobiWrapper::addGeqIndicatorConstraint( const String binVarName, const int binVal, const List &terms, double scalar ) +void GurobiWrapper::addGeqIndicatorConstraint( const String binVarName, + const int binVal, + const List &terms, + double scalar ) { addIndicatorConstraint( binVarName, binVal, terms, scalar, GRB_GREATER_EQUAL ); } -void GurobiWrapper::addEqIndicatorConstraint( const String binVarName, const int binVal, const List &terms, double scalar ) +void GurobiWrapper::addEqIndicatorConstraint( const String binVarName, + const int binVal, + const List &terms, + double scalar ) { addIndicatorConstraint( binVarName, binVal, terms, scalar, GRB_EQUAL ); } -void GurobiWrapper::addIndicatorConstraint( const String binVarName, const int binVal, const List &terms, double scalar, char sense ) +void GurobiWrapper::addIndicatorConstraint( const String binVarName, + const int binVal, + const List &terms, + double scalar, + char sense ) { try { @@ -252,20 +260,25 @@ void GurobiWrapper::addIndicatorConstraint( const String binVarName, const int b } ASSERT( _nameToVariable.exists( binVarName ) ); - _model->addGenConstrIndicator( *_nameToVariable[binVarName], binVal, constraint, sense, scalar ); + _model->addGenConstrIndicator( + *_nameToVariable[binVarName], binVal, constraint, sense, scalar ); } catch ( GRBException e ) { throw CommonError( CommonError::GUROBI_EXCEPTION, Stringf( "Gurobi exception. Gurobi Code: %u, message: %s\n", e.getErrorCode(), - e.getMessage().c_str() ).ascii() ); + e.getMessage().c_str() ) + .ascii() ); } } -void GurobiWrapper::addBilinearConstraint( const String input1, const String input2, const String output ) +void GurobiWrapper::addBilinearConstraint( const String input1, + const String input2, + const String output ) { - _model->addQConstr( ( *_nameToVariable[output] ) == ( *_nameToVariable[input1] ) * ( *_nameToVariable[input2] ) ); + _model->addQConstr( ( *_nameToVariable[output] ) == + ( *_nameToVariable[input1] ) * ( *_nameToVariable[input2] ) ); } void GurobiWrapper::setCost( const List &terms, double constant ) @@ -289,7 +302,8 @@ void GurobiWrapper::setCost( const List &terms, double constant ) throw CommonError( CommonError::GUROBI_EXCEPTION, Stringf( "Gurobi exception. Gurobi Code: %u, message: %s\n", e.getErrorCode(), - e.getMessage().c_str() ).ascii() ); + e.getMessage().c_str() ) + .ascii() ); } } @@ -314,7 +328,8 @@ void GurobiWrapper::setObjective( const List &terms, double constant ) throw CommonError( CommonError::GUROBI_EXCEPTION, Stringf( "Gurobi exception. Gurobi Code: %u, message: %s\n", e.getErrorCode(), - e.getMessage().c_str() ).ascii() ); + e.getMessage().c_str() ) + .ascii() ); } } @@ -335,7 +350,8 @@ void GurobiWrapper::solve() throw CommonError( CommonError::GUROBI_EXCEPTION, Stringf( "Gurobi exception. Gurobi Code: %u, message: %s\n", e.getErrorCode(), - e.getMessage().c_str() ).ascii() ); + e.getMessage().c_str() ) + .ascii() ); } } @@ -380,7 +396,8 @@ void GurobiWrapper::extractSolution( Map &values, double &costOr throw CommonError( CommonError::GUROBI_EXCEPTION, Stringf( "Gurobi exception. Gurobi Code: %u, message: %s\n", e.getErrorCode(), - e.getMessage().c_str() ).ascii() ); + e.getMessage().c_str() ) + .ascii() ); } } @@ -411,7 +428,8 @@ double GurobiWrapper::getObjectiveBound() throw CommonError( CommonError::GUROBI_EXCEPTION, Stringf( "Gurobi exception. Gurobi Code: %u, message: %s\n", e.getErrorCode(), - e.getMessage().c_str() ).ascii() ); + e.getMessage().c_str() ) + .ascii() ); } } diff --git a/src/common/GurobiWrapper.h b/src/common/GurobiWrapper.h index dfd0f49696..466970f9a2 100644 --- a/src/common/GurobiWrapper.h +++ b/src/common/GurobiWrapper.h @@ -20,7 +20,6 @@ #include "MString.h" #include "Map.h" - #include "gurobi_c++.h" class GurobiWrapper @@ -86,16 +85,26 @@ class GurobiWrapper void addPiecewiseLinearConstraint( String sourceVariable, String targetVariable, unsigned numPoints, - const double *xPoints, const double *yPoints ); + const double *xPoints, + const double *yPoints ); // Add a new LEQ indicator constraint - void addLeqIndicatorConstraint( const String binVarName, const int binVal, const List &terms, double scalar ); + void addLeqIndicatorConstraint( const String binVarName, + const int binVal, + const List &terms, + double scalar ); // Add a new GEQ indicator constraint - void addGeqIndicatorConstraint( const String binVarName, const int binVal, const List &terms, double scalar ); + void addGeqIndicatorConstraint( const String binVarName, + const int binVal, + const List &terms, + double scalar ); // Add a new EQ indicator constraint - void addEqIndicatorConstraint( const String binVarName, const int binVal, const List &terms, double scalar ); + void addEqIndicatorConstraint( const String binVarName, + const int binVal, + const List &terms, + double scalar ); // Add a bilinear constraint void addBilinearConstraint( const String input1, const String input2, const String output ); @@ -164,8 +173,7 @@ class GurobiWrapper // Check if the assignment exists or not. inline bool existsAssignment( const String &variable ) { - return _nameToVariable.exists( variable ) && - _model->get( GRB_IntAttr_SolCount ) > 0; + return _nameToVariable.exists( variable ) && _model->get( GRB_IntAttr_SolCount ) > 0; } inline unsigned getNumberOfSimplexIterations() @@ -207,7 +215,11 @@ class GurobiWrapper void addConstraint( const List &terms, double scalar, char sense ); // Add a new indicator constraint - void addIndicatorConstraint( const String binVarName, const int binVal, const List &terms, double scalar, char sense ); + void addIndicatorConstraint( const String binVarName, + const int binVal, + const List &terms, + double scalar, + char sense ); void freeModelIfNeeded(); void freeMemoryIfNeeded(); @@ -235,55 +247,135 @@ class GurobiWrapper struct Term { - Term( double, String ) {} - Term() {} + Term( double, String ) + { + } + Term() + { + } + }; + + GurobiWrapper() + { + } + ~GurobiWrapper() + { + } + + void addVariable( String, double, double, VariableType type = CONTINUOUS ) + { + (void)type; + } + void setLowerBound( String, double ){}; + void setUpperBound( String, double ){}; + double getLowerBound( const String & ) + { + return 0; + }; + double getUpperBound( const String & ) + { + return 0; + }; + void addLeqConstraint( const List &, double ) + { + } + void addGeqConstraint( const List &, double ) + { + } + void addEqConstraint( const List &, double ) + { + } + void addPiecewiseLinearConstraint( String, String, unsigned, const double *, const double * ) + { + } + void addLeqIndicatorConstraint( const String, const int, const List &, double ) + { + } + void addGeqIndicatorConstraint( const String, const int, const List &, double ) + { + } + void addEqIndicatorConstraint( const String, const int, const List &, double ) + { + } + void addBilinearConstraint( const String, const String, const String ) + { + } + void setCost( const List &, double /* constant */ = 0 ) + { + } + void setObjective( const List &, double /* constant */ = 0 ) + { + } + double getOptimalCostOrObjective() + { + return 0; + }; + void setCutoff( double ){}; + void solve() + { + } + void extractSolution( Map &, double & ) + { + } + void reset() + { + } + void resetModel() + { + } + bool optimal() + { + return true; + } + bool cutoffOccurred() + { + return false; + }; + bool infeasible() + { + return false; + }; + bool timeout() + { + return false; + }; + bool haveFeasibleSolution() + { + return true; + }; + void setTimeLimit( double ){}; + void setVerbosity( unsigned ){}; + void setNumberOfThreads( unsigned ){}; + void nonConvex(){}; + double getObjectiveBound() + { + return 0; + }; + double getAssignment( const String & ) + { + return 0; + }; + unsigned getNumberOfSimplexIterations() + { + return 0; + }; + unsigned getNumberOfNodes() + { + return 0; + }; + unsigned getStatusCode() + { + return 0; + }; + void updateModel(){}; + bool existsAssignment( const String & ) + { + return false; }; - GurobiWrapper() {} - ~GurobiWrapper() {} - - void addVariable( String, double, double, VariableType type = CONTINUOUS ) { (void)type; } - void setLowerBound( String, double ) {}; - void setUpperBound( String, double ) {}; - double getLowerBound( const String & ) { return 0; }; - double getUpperBound( const String & ) { return 0; }; - void addLeqConstraint( const List &, double ) {} - void addGeqConstraint( const List &, double ) {} - void addEqConstraint( const List &, double ) {} - void addPiecewiseLinearConstraint( String, - String, - unsigned, - const double *, const double * ) {} - void addLeqIndicatorConstraint( const String, const int, const List &, double ) {} - void addGeqIndicatorConstraint( const String, const int, const List &, double ) {} - void addEqIndicatorConstraint( const String, const int, const List &, double ) {} - void addBilinearConstraint( const String, const String, const String ) {} - void setCost( const List &, double /* constant */=0 ) {} - void setObjective( const List &, double /* constant */=0 ) {} - double getOptimalCostOrObjective() { return 0; }; - void setCutoff( double ) {}; - void solve() {} - void extractSolution( Map &, double & ) {} - void reset() {} - void resetModel() {} - bool optimal() { return true; } - bool cutoffOccurred() { return false; }; - bool infeasible() { return false; }; - bool timeout() { return false; }; - bool haveFeasibleSolution() { return true; }; - void setTimeLimit( double ) {}; - void setVerbosity( unsigned ) {}; - void setNumberOfThreads( unsigned ) {}; - void nonConvex() {}; - double getObjectiveBound() { return 0; }; - double getAssignment( const String & ){ return 0; }; - unsigned getNumberOfSimplexIterations() { return 0; }; - unsigned getNumberOfNodes() { return 0; }; - unsigned getStatusCode() { return 0; }; - void updateModel() {}; - bool existsAssignment( const String & ){ return false; }; - - void dump() {} + void dump() + { + } static void log( const String & ); }; diff --git a/src/common/HashMap.h b/src/common/HashMap.h index f7387a1ac4..887fdd1a9b 100644 --- a/src/common/HashMap.h +++ b/src/common/HashMap.h @@ -19,12 +19,13 @@ #include "CommonError.h" #include "List.h" #include "Set.h" + #include -template -class HashMap +template class HashMap { - typedef std::unordered_map Super; + typedef std::unordered_map Super; + public: typedef typename Super::iterator iterator; typedef typename Super::const_iterator const_iterator; @@ -95,12 +96,12 @@ class HashMap _container[key] = value; } - bool operator==( const HashMap &other ) const + bool operator==( const HashMap &other ) const { return _container == other._container; } - bool operator!=( const HashMap &other ) const + bool operator!=( const HashMap &other ) const { return _container != other._container; } diff --git a/src/common/HashSet.h b/src/common/HashSet.h index 07f5e0beb7..8372fb4a70 100644 --- a/src/common/HashSet.h +++ b/src/common/HashSet.h @@ -17,14 +17,15 @@ #define __HashSet_h__ #include "T/stdlib.h" + #include #include #include -template -class HashSet +template class HashSet { typedef std::unordered_set Super; + public: typedef typename Super::iterator iterator; typedef typename Super::const_iterator const_iterator; @@ -33,7 +34,8 @@ class HashSet { } - HashSet( const std::initializer_list &initializerList ) : _container( initializerList ) + HashSet( const std::initializer_list &initializerList ) + : _container( initializerList ) { } diff --git a/src/common/HeapData.cpp b/src/common/HeapData.cpp index 29755fbdba..4970c2e674 100644 --- a/src/common/HeapData.cpp +++ b/src/common/HeapData.cpp @@ -13,25 +13,33 @@ **/ +#include "HeapData.h" + #include "CommonError.h" #include "ConstSimpleData.h" -#include "HeapData.h" #include "T/stdlib.h" + #include -HeapData::HeapData() : _data( 0 ), _size( 0 ) +HeapData::HeapData() + : _data( 0 ) + , _size( 0 ) { } -HeapData::HeapData( void *data, unsigned size ) : _data( 0 ), _size( 0 ) +HeapData::HeapData( void *data, unsigned size ) + : _data( 0 ) + , _size( 0 ) { allocateMemory( size ); memcpy( _data, data, size ); } -HeapData::HeapData( HeapData &other ) : _data( 0 ), _size( 0 ) +HeapData::HeapData( HeapData &other ) + : _data( 0 ) + , _size( 0 ) { - ( *this )+=other; + ( *this ) += other; } HeapData::HeapData( const ConstSimpleData &constSimpleData ) @@ -78,7 +86,7 @@ HeapData &HeapData::operator+=( const ConstSimpleData &data ) HeapData &HeapData::operator+=( const HeapData &data ) { - ( *this )+=( ConstSimpleData( data ) ); + ( *this ) += ( ConstSimpleData( data ) ); return *this; } @@ -97,9 +105,8 @@ bool HeapData::operator!=( const HeapData &other ) const bool HeapData::operator<( const HeapData &other ) const { - return - ( _size < other._size ) || - ( ( _size == other._size ) && ( memcmp( _data, other._data, _size ) < 0 ) ); + return ( _size < other._size ) || + ( ( _size == other._size ) && ( memcmp( _data, other._data, _size ) < 0 ) ); } void *HeapData::data() diff --git a/src/common/HeapData.h b/src/common/HeapData.h index 5940d7bdbe..c52aedb735 100644 --- a/src/common/HeapData.h +++ b/src/common/HeapData.h @@ -21,8 +21,8 @@ class ConstSimpleData; class HeapData { public: - HeapData(); - HeapData( void *data, unsigned size ); + HeapData(); + HeapData( void *data, unsigned size ); HeapData( HeapData &other ); HeapData( const ConstSimpleData &constSimpleData ); @@ -30,27 +30,27 @@ class HeapData HeapData( const HeapData &other ); - HeapData &operator=( const ConstSimpleData &data ); - HeapData &operator=( const HeapData &other ); + HeapData &operator=( const ConstSimpleData &data ); + HeapData &operator=( const HeapData &other ); HeapData &operator+=( const ConstSimpleData &data ); HeapData &operator+=( const HeapData &data ); bool operator==( const HeapData &other ) const; bool operator!=( const HeapData &other ) const; bool operator<( const HeapData &other ) const; - void *data(); - const void *data() const; - unsigned size() const; + void *data(); + const void *data() const; + unsigned size() const; void clear(); const char *asChar() const; private: - void *_data; - unsigned _size; + void *_data; + unsigned _size; - bool allocated() const; - void freeMemory(); - void freeMemoryIfNeeded(); - void allocateMemory( unsigned size ); + bool allocated() const; + void freeMemory(); + void freeMemoryIfNeeded(); + void allocateMemory( unsigned size ); void addMemory( unsigned size ); void copyNewData( const void *newData, unsigned size ); void adjustSize( unsigned size ); diff --git a/src/common/IFile.cpp b/src/common/IFile.cpp index e42be42386..9e3c6f4078 100644 --- a/src/common/IFile.cpp +++ b/src/common/IFile.cpp @@ -14,6 +14,7 @@ **/ #include "IFile.h" + #include "MString.h" #include "T/sys/stat.h" #include "T/unistd.h" diff --git a/src/common/IFile.h b/src/common/IFile.h index 8c0774ae1f..5d26f39231 100644 --- a/src/common/IFile.h +++ b/src/common/IFile.h @@ -36,7 +36,9 @@ class IFile static bool exists( const String &path ); - virtual ~IFile() {} + virtual ~IFile() + { + } }; #endif // __IFile_h__ diff --git a/src/common/LPSolverType.h b/src/common/LPSolverType.h index cf2b117d8a..e486e3167b 100644 --- a/src/common/LPSolverType.h +++ b/src/common/LPSolverType.h @@ -16,8 +16,7 @@ #ifndef __LPSolverType_h__ #define __LPSolverType_h__ -enum class LPSolverType -{ +enum class LPSolverType { // Native simplex implementation. Open-sourced, more agressive // bound derivation, and will support proof-production. NATIVE, diff --git a/src/common/LinearExpression.cpp b/src/common/LinearExpression.cpp index a287e4453c..becd2ef698 100644 --- a/src/common/LinearExpression.cpp +++ b/src/common/LinearExpression.cpp @@ -14,32 +14,30 @@ **/ #include "LinearExpression.h" + #include "FloatUtils.h" #include "MStringf.h" LinearExpression::LinearExpression() - : _constant( 0 ) + : _constant( 0 ) { } LinearExpression::LinearExpression( Map &addends ) - : _addends( addends ) - , _constant( 0 ) + : _addends( addends ) + , _constant( 0 ) { } -LinearExpression::LinearExpression( Map &addends, - double constant ) - : _addends( addends ) - , _constant( constant ) +LinearExpression::LinearExpression( Map &addends, double constant ) + : _addends( addends ) + , _constant( constant ) { } bool LinearExpression::operator==( const LinearExpression &other ) const { - return - ( _addends == other._addends ) && - ( _constant == other._constant ); + return ( _addends == other._addends ) && ( _constant == other._constant ); } double LinearExpression::evaluate( const Map &assignment ) diff --git a/src/common/LinearExpression.h b/src/common/LinearExpression.h index 86f753d752..a515602930 100644 --- a/src/common/LinearExpression.h +++ b/src/common/LinearExpression.h @@ -17,8 +17,8 @@ #define __LinearExpression_h__ #include "FloatUtils.h" -#include "Map.h" #include "MStringf.h" +#include "Map.h" /* A class representing a single linear expression. @@ -30,7 +30,6 @@ class LinearExpression { public: - LinearExpression(); LinearExpression( Map &addends ); LinearExpression( Map &addends, double constant ); diff --git a/src/common/List.h b/src/common/List.h index 0598c6402f..362dfd83c9 100644 --- a/src/common/List.h +++ b/src/common/List.h @@ -20,10 +20,10 @@ #include -template -class List +template class List { typedef std::list Super; + public: typedef typename Super::iterator iterator; typedef typename Super::const_iterator const_iterator; @@ -35,11 +35,13 @@ class List { } - List( const std::initializer_list &initializerList ) : _container( initializerList ) + List( const std::initializer_list &initializerList ) + : _container( initializerList ) { } - List( unsigned size, T value ) : _container( size, value ) + List( unsigned size, T value ) + : _container( size, value ) { } @@ -181,11 +183,10 @@ class List _container.pop_back(); } - template - void removeIf( Predicate p ) - { - _container.remove_if( p ); - } + template void removeIf( Predicate p ) + { + _container.remove_if( p ); + } bool operator==( const List &other ) const { diff --git a/src/common/MString.cpp b/src/common/MString.cpp index 815309165d..02fb43a6d8 100644 --- a/src/common/MString.cpp +++ b/src/common/MString.cpp @@ -14,9 +14,11 @@ **/ #include "MString.h" + #include "Vector.h" -String::String( Super super ) : _super( super ) +String::String( Super super ) + : _super( super ) { } @@ -24,11 +26,13 @@ String::String() { } -String::String( const char *string, unsigned length ) : _super( string, length ) +String::String( const char *string, unsigned length ) + : _super( string, length ) { } -String::String( const char *string ) : _super( string ) +String::String( const char *string ) + : _super( string ) { } @@ -110,7 +114,7 @@ List String::tokenize( String delimiter ) const Vector copyVector( length() + 1 ); char *copy( copyVector.data() ); - memcpy( copy, ascii(), sizeof(char) * ( length() + 1 ) ); + memcpy( copy, ascii(), sizeof( char ) * ( length() + 1 ) ); char *token = strtok( copy, delimiter.ascii() ); @@ -155,7 +159,8 @@ String String::trim() const for ( unsigned i = 0; i < length(); ++i ) { - if ( ( !firstNonSpaceFound ) && ( _super[i] != ' ' ) && ( _super[i] != '\n' ) && ( _super[i] != '\r' ) ) + if ( ( !firstNonSpaceFound ) && ( _super[i] != ' ' ) && ( _super[i] != '\n' ) && + ( _super[i] != '\r' ) ) { firstNonSpace = i; firstNonSpaceFound = true; @@ -208,7 +213,7 @@ bool String::endsWith( const String &suffix ) { unsigned int l1 = length(); unsigned int l2 = suffix.length(); - return l1 >= l2 && _super.compare(l1 - l2, l2, suffix._super) == 0; + return l1 >= l2 && _super.compare( l1 - l2, l2, suffix._super ) == 0; } std::ostream &operator<<( std::ostream &stream, const String &string ); diff --git a/src/common/MString.h b/src/common/MString.h index 790ad0ec06..f90ed1699d 100644 --- a/src/common/MString.h +++ b/src/common/MString.h @@ -17,6 +17,7 @@ #define __String_h__ #include "List.h" + #include #include @@ -30,7 +31,7 @@ class String String( const char *string, unsigned length ); String( const char *string ); - String(const String &rhs) = default; + String( const String &rhs ) = default; unsigned length() const; const char *ascii() const; @@ -57,7 +58,7 @@ class String void replaceAll( const String &toReplace, const String &replaceWith ); protected: - Super _super; + Super _super; }; std::ostream &operator<<( std::ostream &stream, const String &string ); @@ -65,25 +66,25 @@ std::ostream &operator<<( std::ostream &stream, const String &string ); #ifdef CXXTEST_RUNNING #include #include -namespace CxxTest +namespace CxxTest { +CXXTEST_TEMPLATE_INSTANTIATION +class ValueTraits { - CXXTEST_TEMPLATE_INSTANTIATION - class ValueTraits +public: + ValueTraits( const String &string ) + : _string( string ) + { + } + + const char *asString() const { - public: - ValueTraits( const String &string ) : _string( string ) - { - } - - const char *asString() const - { - return _string.ascii(); - } - - private: - const String &_string; - }; -} + return _string.ascii(); + } + +private: + const String &_string; +}; +} // namespace CxxTest #endif // CXXTEST_RUNNING diff --git a/src/common/MStringf.h b/src/common/MStringf.h index 45db63029a..c4b3fcf49b 100644 --- a/src/common/MStringf.h +++ b/src/common/MStringf.h @@ -46,25 +46,25 @@ class Stringf : public String #ifdef CXXTEST_RUNNING #include #include -namespace CxxTest +namespace CxxTest { +CXXTEST_TEMPLATE_INSTANTIATION +class ValueTraits { - CXXTEST_TEMPLATE_INSTANTIATION - class ValueTraits +public: + ValueTraits( const Stringf &stringf ) + : _stringf( stringf ) { - public: - ValueTraits( const Stringf &stringf ) : _stringf( stringf ) - { - } - - const char *asString() const - { - return _stringf.ascii(); - } - - private: - const Stringf &_stringf; - }; -} + } + + const char *asString() const + { + return _stringf.ascii(); + } + +private: + const Stringf &_stringf; +}; +} // namespace CxxTest #endif // CXXTEST_RUNNING diff --git a/src/common/Map.h b/src/common/Map.h index d89a08b001..cc6f3b92e5 100644 --- a/src/common/Map.h +++ b/src/common/Map.h @@ -19,12 +19,13 @@ #include "CommonError.h" #include "List.h" #include "Set.h" + #include -template -class Map +template class Map { - typedef std::map Super; + typedef std::map Super; + public: typedef typename Super::iterator iterator; typedef typename Super::const_iterator const_iterator; @@ -86,17 +87,17 @@ class Map return _container.at( key ); } - bool operator==( const Map &other ) const + bool operator==( const Map &other ) const { return _container == other._container; } - bool operator!=( const Map &other ) const + bool operator!=( const Map &other ) const { return _container != other._container; } - bool operator<( const Map &other ) const + bool operator<( const Map &other ) const { return _container < other._container; } diff --git a/src/common/MatrixMultiplication.cpp b/src/common/MatrixMultiplication.cpp index 909467e611..14c6e8959c 100644 --- a/src/common/MatrixMultiplication.cpp +++ b/src/common/MatrixMultiplication.cpp @@ -17,8 +17,11 @@ #ifdef ENABLE_OPENBLAS #include "cblas.h" -void matrixMultiplication( const double *matA, const double *matB, double *matC, - unsigned rowsA, unsigned columnsA, +void matrixMultiplication( const double *matA, + const double *matB, + double *matC, + unsigned rowsA, + unsigned columnsA, unsigned columnsB ) { double alpha = 1; @@ -27,12 +30,27 @@ void matrixMultiplication( const double *matA, const double *matB, double *matC, // See https://developer.apple.com/documentation/accelerate/1513282-cblas_dgemm?language=objc // for the documentation of cblas_dgemm. - cblas_dgemm( CblasRowMajor, CblasNoTrans, CblasNoTrans, rowsA, columnsB, - columnsA, alpha, matA, columnsA, matB, columnsB, beta, matC, columnsB); + cblas_dgemm( CblasRowMajor, + CblasNoTrans, + CblasNoTrans, + rowsA, + columnsB, + columnsA, + alpha, + matA, + columnsA, + matB, + columnsB, + beta, + matC, + columnsB ); } #else -void matrixMultiplication( const double *matA, const double *matB, double *matC, - unsigned rowsA, unsigned columnsA, +void matrixMultiplication( const double *matA, + const double *matB, + double *matC, + unsigned rowsA, + unsigned columnsA, unsigned columnsB ) { for ( unsigned i = 0; i < rowsA; ++i ) @@ -41,8 +59,7 @@ void matrixMultiplication( const double *matA, const double *matB, double *matC, { for ( unsigned k = 0; k < columnsA; ++k ) { - matC[i * columnsB + j] += matA[i * columnsA + k] - * matB[k * columnsB + j]; + matC[i * columnsB + j] += matA[i * columnsA + k] * matB[k * columnsB + j]; } } } diff --git a/src/common/MatrixMultiplication.h b/src/common/MatrixMultiplication.h index 0ee81714c6..25ca609757 100644 --- a/src/common/MatrixMultiplication.h +++ b/src/common/MatrixMultiplication.h @@ -7,8 +7,11 @@ and the size of matB is columnsA x columnsB. Compute matA * matB + matC and store the result in matC */ -void matrixMultiplication( const double *matA, const double *matB, double *matC, - unsigned rowsA, unsigned columnsA, +void matrixMultiplication( const double *matA, + const double *matB, + double *matC, + unsigned rowsA, + unsigned columnsA, unsigned columnsB ); #endif // __MatrixMultiplication_h__ diff --git a/src/common/Pair.h b/src/common/Pair.h index bf8065d26d..c8ce95245e 100644 --- a/src/common/Pair.h +++ b/src/common/Pair.h @@ -19,16 +19,17 @@ #include #include -template -class Pair +template class Pair { - typedef std::pair Super; + typedef std::pair Super; + public: Pair() { } - Pair( const L &first, const R &second ) : _container( first, second ) + Pair( const L &first, const R &second ) + : _container( first, second ) { } @@ -52,21 +53,21 @@ class Pair return _container.second; } - Pair &operator=( const Pair &other ) - { - _container = other._container; - return *this; - } + Pair &operator=( const Pair &other ) + { + _container = other._container; + return *this; + } bool operator==( const Pair &other ) const - { - return _container == other._container; - } + { + return _container == other._container; + } bool operator!=( const Pair &other ) const - { - return _container != other._container; - } + { + return _container != other._container; + } bool operator<( const Pair &other ) const { @@ -77,8 +78,7 @@ class Pair Super _container; }; -template -std::ostream &operator<<( std::ostream &stream, const Pair &pair ) +template std::ostream &operator<<( std::ostream &stream, const Pair &pair ) { return stream << pair.first() << "," << pair.second(); } diff --git a/src/common/Queue.h b/src/common/Queue.h index e9a7a627f9..4f4a19af54 100644 --- a/src/common/Queue.h +++ b/src/common/Queue.h @@ -17,10 +17,10 @@ #define __Queue_h__ #include "CommonError.h" + #include -template -class Queue +template class Queue { typedef std::queue Super; diff --git a/src/common/Set.h b/src/common/Set.h index 6011ec2fa0..7df6f7f5c4 100644 --- a/src/common/Set.h +++ b/src/common/Set.h @@ -17,6 +17,7 @@ #define __Set_h__ #include "T/stdlib.h" + #include #include #include @@ -25,10 +26,10 @@ #include #endif -template -class Set +template class Set { typedef std::set Super; + public: typedef typename Super::iterator iterator; typedef typename Super::const_iterator const_iterator; @@ -38,7 +39,8 @@ class Set { } - Set( const std::initializer_list &initializerList ) : _container( initializerList ) + Set( const std::initializer_list &initializerList ) + : _container( initializerList ) { } diff --git a/src/common/SignalHandler.cpp b/src/common/SignalHandler.cpp index 22e3114346..b8880648ca 100644 --- a/src/common/SignalHandler.cpp +++ b/src/common/SignalHandler.cpp @@ -15,6 +15,7 @@ **/ #include "SignalHandler.h" + #include #include @@ -36,20 +37,18 @@ void SignalHandler::registerClient( Signalable *client ) void SignalHandler::initialize() { - #ifdef _WIN32 signal( SIGINT, got_signal ); signal( SIGTERM, got_signal ); signal( SIGABRT, got_signal ); #else struct sigaction sa; - memset( &sa, 0, sizeof(sa) ); + memset( &sa, 0, sizeof( sa ) ); sa.sa_handler = got_signal; sigfillset( &sa.sa_mask ); sigaction( SIGQUIT, &sa, NULL ); sigaction( SIGTERM, &sa, NULL ); #endif - } void SignalHandler::signalReceived( unsigned /* signalNumber */ ) diff --git a/src/common/SignalHandler.h b/src/common/SignalHandler.h index 94e95baf29..4e9e37d9e8 100644 --- a/src/common/SignalHandler.h +++ b/src/common/SignalHandler.h @@ -53,8 +53,12 @@ class SignalHandler /* Prevent additional instantiations of the class */ - SignalHandler() {} - SignalHandler( const SignalHandler & ) {} + SignalHandler() + { + } + SignalHandler( const SignalHandler & ) + { + } }; #endif // __SignalHandler_h__ diff --git a/src/common/Stack.h b/src/common/Stack.h index 96d593742b..437e27afe3 100644 --- a/src/common/Stack.h +++ b/src/common/Stack.h @@ -17,14 +17,14 @@ #define __Stack_h__ #include "CommonError.h" + #include -template -class Stack +template class Stack { typedef std::stack Super; -public: +public: void push( T value ) { _container.push( value ); diff --git a/src/common/Statistics.cpp b/src/common/Statistics.cpp index c2ee90d166..7188667d60 100644 --- a/src/common/Statistics.cpp +++ b/src/common/Statistics.cpp @@ -13,8 +13,9 @@ **/ -#include "FloatUtils.h" #include "Statistics.h" + +#include "FloatUtils.h" #include "TimeUtils.h" Statistics::Statistics() @@ -118,22 +119,31 @@ void Statistics::print() printf( "\t--- Time Statistics ---\n" ); printf( "\tTotal time elapsed: %llu milli (%02u:%02u:%02u)\n", - totalElapsed / 1000, hours, minutes - ( hours * 60 ), seconds - ( minutes * 60 ) ); + totalElapsed / 1000, + hours, + minutes - ( hours * 60 ), + seconds - ( minutes * 60 ) ); unsigned long long timeMainLoopMicro = getLongAttribute( Statistics::TIME_MAIN_LOOP_MICRO ); seconds = timeMainLoopMicro / 1000000; minutes = seconds / 60; hours = minutes / 60; printf( "\t\tMain loop: %llu milli (%02u:%02u:%02u)\n", - timeMainLoopMicro / 1000, hours, minutes - ( hours * 60 ), seconds - ( minutes * 60 ) ); + timeMainLoopMicro / 1000, + hours, + minutes - ( hours * 60 ), + seconds - ( minutes * 60 ) ); - unsigned long long preprocessingTimeMicro = getLongAttribute - ( Statistics::PREPROCESSING_TIME_MICRO ); + unsigned long long preprocessingTimeMicro = + getLongAttribute( Statistics::PREPROCESSING_TIME_MICRO ); seconds = preprocessingTimeMicro / 1000000; minutes = seconds / 60; hours = minutes / 60; printf( "\t\tPreprocessing time: %llu milli (%02u:%02u:%02u)\n", - preprocessingTimeMicro / 1000, hours, minutes - ( hours * 60 ), seconds - ( minutes * 60 ) ); + preprocessingTimeMicro / 1000, + hours, + minutes - ( hours * 60 ), + seconds - ( minutes * 60 ) ); unsigned long long totalUnknown = totalElapsed - timeMainLoopMicro - preprocessingTimeMicro; @@ -141,110 +151,93 @@ void Statistics::print() minutes = seconds / 60; hours = minutes / 60; printf( "\t\tUnknown: %llu milli (%02u:%02u:%02u)\n", - totalUnknown / 1000, hours, minutes - ( hours * 60 ), seconds - ( minutes * 60 ) ); + totalUnknown / 1000, + hours, + minutes - ( hours * 60 ), + seconds - ( minutes * 60 ) ); printf( "\tBreakdown for main loop:\n" ); unsigned long long timeSimplexStepsMicro = getLongAttribute( Statistics::TIME_SIMPLEX_STEPS_MICRO ); - printf( "\t\t[%.2lf%%] Simplex steps: %llu milli\n" - , printPercents( timeSimplexStepsMicro, timeMainLoopMicro ) - , timeSimplexStepsMicro / 1000 - ); + printf( "\t\t[%.2lf%%] Simplex steps: %llu milli\n", + printPercents( timeSimplexStepsMicro, timeMainLoopMicro ), + timeSimplexStepsMicro / 1000 ); unsigned long long totalTimeExplicitBasisBoundTighteningMicro = - getLongAttribute(TOTAL_TIME_EXPLICIT_BASIS_BOUND_TIGHTENING_MICRO ); - printf( "\t\t[%.2lf%%] Explicit-basis bound tightening: %llu milli\n" - , printPercents( totalTimeExplicitBasisBoundTighteningMicro, timeMainLoopMicro ) - , totalTimeExplicitBasisBoundTighteningMicro / 1000 - ); + getLongAttribute( TOTAL_TIME_EXPLICIT_BASIS_BOUND_TIGHTENING_MICRO ); + printf( "\t\t[%.2lf%%] Explicit-basis bound tightening: %llu milli\n", + printPercents( totalTimeExplicitBasisBoundTighteningMicro, timeMainLoopMicro ), + totalTimeExplicitBasisBoundTighteningMicro / 1000 ); unsigned long long totalTimeConstraintMatrixBoundTighteningMicro = - getLongAttribute(TOTAL_TIME_CONSTRAINT_MATRIX_BOUND_TIGHTENING_MICRO ); - printf( "\t\t[%.2lf%%] Constraint-matrix bound tightening: %llu milli\n" - , printPercents( totalTimeConstraintMatrixBoundTighteningMicro, timeMainLoopMicro ) - , totalTimeConstraintMatrixBoundTighteningMicro / 1000 - ); + getLongAttribute( TOTAL_TIME_CONSTRAINT_MATRIX_BOUND_TIGHTENING_MICRO ); + printf( "\t\t[%.2lf%%] Constraint-matrix bound tightening: %llu milli\n", + printPercents( totalTimeConstraintMatrixBoundTighteningMicro, timeMainLoopMicro ), + totalTimeConstraintMatrixBoundTighteningMicro / 1000 ); unsigned long long totalTimeDegradationChecking = getLongAttribute( Statistics::TOTAL_TIME_DEGRADATION_CHECKING ); - printf( "\t\t[%.2lf%%] Degradation checking: %llu milli\n" - , printPercents( totalTimeDegradationChecking, timeMainLoopMicro ) - , totalTimeDegradationChecking / 1000 - ); + printf( "\t\t[%.2lf%%] Degradation checking: %llu milli\n", + printPercents( totalTimeDegradationChecking, timeMainLoopMicro ), + totalTimeDegradationChecking / 1000 ); unsigned long long totalTimePrecisionRestoration = getLongAttribute( Statistics::TOTAL_TIME_PRECISION_RESTORATION ); - printf( "\t\t[%.2lf%%] Precision restoration: %llu milli\n" - , printPercents( totalTimePrecisionRestoration, timeMainLoopMicro ) - , totalTimePrecisionRestoration / 1000 - ); + printf( "\t\t[%.2lf%%] Precision restoration: %llu milli\n", + printPercents( totalTimePrecisionRestoration, timeMainLoopMicro ), + totalTimePrecisionRestoration / 1000 ); unsigned long long totalTimeHandlingStatisticsMicro = getLongAttribute( Statistics::TOTAL_TIME_HANDLING_STATISTICS_MICRO ); - printf( "\t\t[%.2lf%%] Statistics handling: %llu milli\n" - , printPercents( totalTimeHandlingStatisticsMicro, timeMainLoopMicro ) - , totalTimeHandlingStatisticsMicro / 1000 - ); + printf( "\t\t[%.2lf%%] Statistics handling: %llu milli\n", + printPercents( totalTimeHandlingStatisticsMicro, timeMainLoopMicro ), + totalTimeHandlingStatisticsMicro / 1000 ); unsigned long long timeConstraintFixingStepsMicro = getLongAttribute( Statistics::TIME_CONSTRAINT_FIXING_STEPS_MICRO ); - printf( "\t\t[%.2lf%%] Constraint-fixing steps: %llu milli\n" - , printPercents( timeConstraintFixingStepsMicro, timeMainLoopMicro ) - , timeConstraintFixingStepsMicro / 1000 - ); + printf( "\t\t[%.2lf%%] Constraint-fixing steps: %llu milli\n", + printPercents( timeConstraintFixingStepsMicro, timeMainLoopMicro ), + timeConstraintFixingStepsMicro / 1000 ); unsigned long long totalTimePerformingValidCaseSplitsMicro = getLongAttribute( Statistics::TOTAL_TIME_PERFORMING_VALID_CASE_SPLITS_MICRO ); unsigned totalNumberOfValidCaseSplits = getUnsignedAttribute( Statistics::TOTAL_NUMBER_OF_VALID_CASE_SPLITS ); - printf( "\t\t[%.2lf%%] Valid case splits: %llu milli. Average per split: %.2lf milli\n" - , printPercents( totalTimePerformingValidCaseSplitsMicro, timeMainLoopMicro ) - , totalTimePerformingValidCaseSplitsMicro / 1000 - , printAverage( totalTimePerformingValidCaseSplitsMicro / 1000, - totalNumberOfValidCaseSplits ) - ); + printf( "\t\t[%.2lf%%] Valid case splits: %llu milli. Average per split: %.2lf milli\n", + printPercents( totalTimePerformingValidCaseSplitsMicro, timeMainLoopMicro ), + totalTimePerformingValidCaseSplitsMicro / 1000, + printAverage( totalTimePerformingValidCaseSplitsMicro / 1000, + totalNumberOfValidCaseSplits ) ); unsigned long long totalTimeApplyingStoredTighteningsMicro = getLongAttribute( Statistics::TOTAL_TIME_APPLYING_STORED_TIGHTENINGS_MICRO ); - printf( "\t\t[%.2lf%%] Applying stored bound-tightening: %llu milli\n" - , printPercents( totalTimeApplyingStoredTighteningsMicro, timeMainLoopMicro ) - , totalTimeApplyingStoredTighteningsMicro / 1000 - ); + printf( "\t\t[%.2lf%%] Applying stored bound-tightening: %llu milli\n", + printPercents( totalTimeApplyingStoredTighteningsMicro, timeMainLoopMicro ), + totalTimeApplyingStoredTighteningsMicro / 1000 ); unsigned long long totalTimeSmtCoreMicro = getLongAttribute( Statistics::TOTAL_TIME_SMT_CORE_MICRO ); - printf( "\t\t[%.2lf%%] SMT core: %llu milli\n" - , printPercents( totalTimeSmtCoreMicro, timeMainLoopMicro ) - , totalTimeSmtCoreMicro / 1000 - ); + printf( "\t\t[%.2lf%%] SMT core: %llu milli\n", + printPercents( totalTimeSmtCoreMicro, timeMainLoopMicro ), + totalTimeSmtCoreMicro / 1000 ); unsigned long long totalTimePerformingSymbolicBoundTightening = getLongAttribute( Statistics::TOTAL_TIME_PERFORMING_SYMBOLIC_BOUND_TIGHTENING ); - printf( "\t\t[%.2lf%%] Symbolic Bound Tightening: %llu milli\n" - , printPercents( totalTimePerformingSymbolicBoundTightening, timeMainLoopMicro ) - , totalTimePerformingSymbolicBoundTightening / 1000 - ); + printf( "\t\t[%.2lf%%] Symbolic Bound Tightening: %llu milli\n", + printPercents( totalTimePerformingSymbolicBoundTightening, timeMainLoopMicro ), + totalTimePerformingSymbolicBoundTightening / 1000 ); unsigned long long totalTimePerformingLocalSearch = getLongAttribute( Statistics::TOTAL_TIME_LOCAL_SEARCH_MICRO ); - printf( "\t\t[%.2lf%%] SoI-based local search: %llu milli\n" - , printPercents( totalTimePerformingLocalSearch, timeMainLoopMicro ) - , totalTimePerformingLocalSearch / 1000 - ); + printf( "\t\t[%.2lf%%] SoI-based local search: %llu milli\n", + printPercents( totalTimePerformingLocalSearch, timeMainLoopMicro ), + totalTimePerformingLocalSearch / 1000 ); unsigned long long totalTimeAddingConstraintsToMILPSolver = getLongAttribute( Statistics::TIME_ADDING_CONSTRAINTS_TO_MILP_SOLVER_MICRO ); - printf( "\t\t[%.2lf%%] SoI-based local search: %llu milli\n" - , printPercents( totalTimeAddingConstraintsToMILPSolver, - timeMainLoopMicro ) - , totalTimeAddingConstraintsToMILPSolver / 1000 - ); + printf( "\t\t[%.2lf%%] SoI-based local search: %llu milli\n", + printPercents( totalTimeAddingConstraintsToMILPSolver, timeMainLoopMicro ), + totalTimeAddingConstraintsToMILPSolver / 1000 ); unsigned long long total = - timeSimplexStepsMicro + - timeConstraintFixingStepsMicro + - totalTimePerformingValidCaseSplitsMicro + - totalTimeHandlingStatisticsMicro + - totalTimeExplicitBasisBoundTighteningMicro + - totalTimeDegradationChecking + - totalTimePrecisionRestoration + - totalTimeConstraintMatrixBoundTighteningMicro + - totalTimeApplyingStoredTighteningsMicro + - totalTimeSmtCoreMicro + + timeSimplexStepsMicro + timeConstraintFixingStepsMicro + + totalTimePerformingValidCaseSplitsMicro + totalTimeHandlingStatisticsMicro + + totalTimeExplicitBasisBoundTighteningMicro + totalTimeDegradationChecking + + totalTimePrecisionRestoration + totalTimeConstraintMatrixBoundTighteningMicro + + totalTimeApplyingStoredTighteningsMicro + totalTimeSmtCoreMicro + totalTimePerformingSymbolicBoundTightening; - printf( "\t\t[%.2lf%%] Unaccounted for: %llu milli\n" - , printPercents( timeMainLoopMicro - total, timeMainLoopMicro ) - , timeMainLoopMicro > total ? ( timeMainLoopMicro - total ) / 1000 : 0 - ); + printf( "\t\t[%.2lf%%] Unaccounted for: %llu milli\n", + printPercents( timeMainLoopMicro - total, timeMainLoopMicro ), + timeMainLoopMicro > total ? ( timeMainLoopMicro - total ) / 1000 : 0 ); printf( "\t--- Preprocessor Statistics ---\n" ); printf( "\tNumber of preprocessor bound-tightening loop iterations: %u\n", @@ -256,59 +249,55 @@ void Statistics::print() printf( "\tNumber of equations removed due to variable elimination: %u\n", getUnsignedAttribute( Statistics::PP_NUM_EQUATIONS_REMOVED ) ); - unsigned long long numSimplexSteps = - getLongAttribute( Statistics::NUM_SIMPLEX_STEPS ); + unsigned long long numSimplexSteps = getLongAttribute( Statistics::NUM_SIMPLEX_STEPS ); unsigned long long numConstraintFixingSteps = getLongAttribute( Statistics::NUM_CONSTRAINT_FIXING_STEPS ); printf( "\t--- Engine Statistics ---\n" ); - printf( "\tNumber of main loop iterations: %llu\n" - "\t\t%llu iterations were simplex steps. Total time: %llu milli. Average: %.2lf milli.\n" - "\t\t%llu iterations were constraint-fixing steps. " - "Total time: %llu milli. Average: %.2lf milli\n" - , getLongAttribute( Statistics::NUM_MAIN_LOOP_ITERATIONS ) - , numSimplexSteps - , timeSimplexStepsMicro / 1000 - , printAverage( timeSimplexStepsMicro / 1000, numSimplexSteps ) - , numConstraintFixingSteps - , timeConstraintFixingStepsMicro / 1000 - , printAverage( timeConstraintFixingStepsMicro / 1000, - numConstraintFixingSteps ) - ); + printf( + "\tNumber of main loop iterations: %llu\n" + "\t\t%llu iterations were simplex steps. Total time: %llu milli. Average: %.2lf milli.\n" + "\t\t%llu iterations were constraint-fixing steps. " + "Total time: %llu milli. Average: %.2lf milli\n", + getLongAttribute( Statistics::NUM_MAIN_LOOP_ITERATIONS ), + numSimplexSteps, + timeSimplexStepsMicro / 1000, + printAverage( timeSimplexStepsMicro / 1000, numSimplexSteps ), + numConstraintFixingSteps, + timeConstraintFixingStepsMicro / 1000, + printAverage( timeConstraintFixingStepsMicro / 1000, numConstraintFixingSteps ) ); printf( "\tNumber of active piecewise-linear constraints: %u / %u\n" "\t\tConstraints disabled by valid splits: %u. " - "By SMT-originated splits: %u\n" - , getUnsignedAttribute( Statistics::NUM_ACTIVE_PL_CONSTRAINTS ) - , getUnsignedAttribute( Statistics::NUM_PL_CONSTRAINTS ) - , getUnsignedAttribute( Statistics::NUM_PL_VALID_SPLITS ) - , getUnsignedAttribute( Statistics::NUM_PL_SMT_ORIGINATED_SPLITS ) - ); + "By SMT-originated splits: %u\n", + getUnsignedAttribute( Statistics::NUM_ACTIVE_PL_CONSTRAINTS ), + getUnsignedAttribute( Statistics::NUM_PL_CONSTRAINTS ), + getUnsignedAttribute( Statistics::NUM_PL_VALID_SPLITS ), + getUnsignedAttribute( Statistics::NUM_PL_SMT_ORIGINATED_SPLITS ) ); printf( "\tLast reported degradation: %.10lf. Max degradation so far: %.10lf. " - "Restorations so far: %u\n" - , getDoubleAttribute( Statistics::CURRENT_DEGRADATION ) - , getDoubleAttribute( Statistics::MAX_DEGRADATION ) - , getUnsignedAttribute( Statistics::NUM_PRECISION_RESTORATIONS ) - ); + "Restorations so far: %u\n", + getDoubleAttribute( Statistics::CURRENT_DEGRADATION ), + getDoubleAttribute( Statistics::MAX_DEGRADATION ), + getUnsignedAttribute( Statistics::NUM_PRECISION_RESTORATIONS ) ); printf( "\tNumber of simplex pivots we attempted to skip because of instability: %llu.\n" - "\tUnstable pivots performed anyway: %llu\n" - , getLongAttribute( Statistics::NUM_SIMPLEX_PIVOT_SELECTIONS_IGNORED_FOR_STABILITY ) - , getLongAttribute( Statistics::NUM_SIMPLEX_UNSTABLE_PIVOTS ) ); + "\tUnstable pivots performed anyway: %llu\n", + getLongAttribute( Statistics::NUM_SIMPLEX_PIVOT_SELECTIONS_IGNORED_FOR_STABILITY ), + getLongAttribute( Statistics::NUM_SIMPLEX_UNSTABLE_PIVOTS ) ); - unsigned long long numTableauPivots = getLongAttribute(NUM_TABLEAU_PIVOTS ); + unsigned long long numTableauPivots = getLongAttribute( NUM_TABLEAU_PIVOTS ); unsigned long long numTableauDegeneratePivots = - getLongAttribute(NUM_TABLEAU_DEGENERATE_PIVOTS ); + getLongAttribute( NUM_TABLEAU_DEGENERATE_PIVOTS ); printf( "\t--- Tableau Statistics ---\n" ); printf( "\tTotal number of pivots performed: %llu\n", numTableauPivots ); - printf( "\t\tReal pivots: %llu. Degenerate: %llu (%.2lf%%)\n" - , numTableauPivots - numTableauDegeneratePivots - , numTableauDegeneratePivots - , printPercents( numTableauDegeneratePivots, numTableauPivots ) ); + printf( "\t\tReal pivots: %llu. Degenerate: %llu (%.2lf%%)\n", + numTableauPivots - numTableauDegeneratePivots, + numTableauDegeneratePivots, + printPercents( numTableauDegeneratePivots, numTableauPivots ) ); unsigned long long numTableauDegeneratePivotsByRequest = - getLongAttribute(NUM_TABLEAU_DEGENERATE_PIVOTS_BY_REQUEST ); - printf( "\t\tDegenerate pivots by request (e.g., to fix a PL constraint): %llu (%.2lf%%)\n" - , numTableauDegeneratePivotsByRequest - , printPercents( numTableauDegeneratePivotsByRequest, numTableauDegeneratePivots ) ); + getLongAttribute( NUM_TABLEAU_DEGENERATE_PIVOTS_BY_REQUEST ); + printf( "\t\tDegenerate pivots by request (e.g., to fix a PL constraint): %llu (%.2lf%%)\n", + numTableauDegeneratePivotsByRequest, + printPercents( numTableauDegeneratePivotsByRequest, numTableauDegeneratePivots ) ); printf( "\t\tAverage time per pivot: %.2lf milli\n", printAverage( getLongAttribute( Statistics::TIME_PIVOTS_MICRO ) / 1000, @@ -316,41 +305,43 @@ void Statistics::print() printf( "\tTotal number of fake pivots performed: %llu\n", getLongAttribute( Statistics::NUM_TABLEAU_BOUND_HOPPING ) ); - printf( "\tTotal number of rows added: %llu. Number of merged columns: %llu\n" - , getLongAttribute( Statistics::NUM_ADDED_ROWS ) - , getLongAttribute( Statistics::NUM_MERGED_COLUMNS ) ); - printf( "\tCurrent tableau dimensions: M = %u, N = %u\n" - , getUnsignedAttribute( Statistics::CURRENT_TABLEAU_M ) - , getUnsignedAttribute( Statistics::CURRENT_TABLEAU_N ) ); + printf( "\tTotal number of rows added: %llu. Number of merged columns: %llu\n", + getLongAttribute( Statistics::NUM_ADDED_ROWS ), + getLongAttribute( Statistics::NUM_MERGED_COLUMNS ) ); + printf( "\tCurrent tableau dimensions: M = %u, N = %u\n", + getUnsignedAttribute( Statistics::CURRENT_TABLEAU_M ), + getUnsignedAttribute( Statistics::CURRENT_TABLEAU_N ) ); printf( "\t--- SMT Core Statistics ---\n" ); - printf( "\tTotal depth is %u. Total visited states: %u. Number of splits: %u. Number of pops: %u\n" - , getUnsignedAttribute( Statistics::CURRENT_DECISION_LEVEL ) - , getUnsignedAttribute( Statistics::NUM_VISITED_TREE_STATES ) - , getUnsignedAttribute( Statistics::NUM_SPLITS ) - , getUnsignedAttribute( Statistics::NUM_POPS ) ); - printf( "\tMax stack depth: %u\n" - , getUnsignedAttribute( Statistics::MAX_DECISION_LEVEL ) ); + printf( + "\tTotal depth is %u. Total visited states: %u. Number of splits: %u. Number of pops: %u\n", + getUnsignedAttribute( Statistics::CURRENT_DECISION_LEVEL ), + getUnsignedAttribute( Statistics::NUM_VISITED_TREE_STATES ), + getUnsignedAttribute( Statistics::NUM_SPLITS ), + getUnsignedAttribute( Statistics::NUM_POPS ) ); + printf( "\tMax stack depth: %u\n", getUnsignedAttribute( Statistics::MAX_DECISION_LEVEL ) ); printf( "\t--- Bound Tightening Statistics ---\n" ); printf( "\tNumber of tightened bounds: %llu.\n", getLongAttribute( Statistics::NUM_TIGHTENED_BOUNDS ) ); - printf( "\t\tNumber of rows examined by row tightener: %llu. Consequent tightenings: %llu\n" - , getLongAttribute( Statistics::NUM_ROWS_EXAMINED_BY_ROW_TIGHTENER ) - , getLongAttribute( Statistics::NUM_TIGHTENINGS_FROM_ROWS ) ); + printf( "\t\tNumber of rows examined by row tightener: %llu. Consequent tightenings: %llu\n", + getLongAttribute( Statistics::NUM_ROWS_EXAMINED_BY_ROW_TIGHTENER ), + getLongAttribute( Statistics::NUM_TIGHTENINGS_FROM_ROWS ) ); - printf( "\t\tNumber of explicit basis matrices examined by row tightener: %llu. Consequent tightenings: %llu\n" - , getLongAttribute( Statistics::NUM_BOUND_TIGHTENINGS_ON_EXPLICIT_BASIS ) - , getLongAttribute( Statistics::NUM_TIGHTENINGS_FROM_EXPLICIT_BASIS ) ); + printf( "\t\tNumber of explicit basis matrices examined by row tightener: %llu. Consequent " + "tightenings: %llu\n", + getLongAttribute( Statistics::NUM_BOUND_TIGHTENINGS_ON_EXPLICIT_BASIS ), + getLongAttribute( Statistics::NUM_TIGHTENINGS_FROM_EXPLICIT_BASIS ) ); printf( "\t\tNumber of bound tightening rounds on the entire constraint matrix: %llu. " - "Consequent tightenings: %llu\n" - , getLongAttribute( Statistics::NUM_BOUND_TIGHTENINGS_ON_CONSTRAINT_MATRIX ) - , getLongAttribute( Statistics::NUM_TIGHTENINGS_FROM_CONSTRAINT_MATRIX ) ); + "Consequent tightenings: %llu\n", + getLongAttribute( Statistics::NUM_BOUND_TIGHTENINGS_ON_CONSTRAINT_MATRIX ), + getLongAttribute( Statistics::NUM_TIGHTENINGS_FROM_CONSTRAINT_MATRIX ) ); - printf( "\t\tNumber of bound notifications sent to PL constraints: %llu. Tightenings proposed: %llu\n" - , getLongAttribute( Statistics::NUM_BOUND_NOTIFICATIONS_TO_PL_CONSTRAINTS ) - , getLongAttribute( Statistics::NUM_BOUNDS_PROPOSED_BY_PL_CONSTRAINTS ) ); + printf( "\t\tNumber of bound notifications sent to PL constraints: %llu. Tightenings proposed: " + "%llu\n", + getLongAttribute( Statistics::NUM_BOUND_NOTIFICATIONS_TO_PL_CONSTRAINTS ), + getLongAttribute( Statistics::NUM_BOUNDS_PROPOSED_BY_PL_CONSTRAINTS ) ); printf( "\t--- Basis Factorization statistics ---\n" ); printf( "\tNumber of basis refactorizations: %llu\n", @@ -361,10 +352,11 @@ void Statistics::print() getLongAttribute( Statistics::PSE_NUM_RESET_REFERENCE_SPACE ); printf( "\t--- Projected Steepest Edge Statistics ---\n" ); printf( "\tNumber of iterations: %llu.\n", pseNumIterations ); - printf( "\tNumber of resets to reference space: %llu. Avg. iterations per reset: %u\n" - , pseNumResetReferenceSpace - , pseNumResetReferenceSpace > 0 ? - (unsigned)((double)pseNumIterations / pseNumResetReferenceSpace) : 0 ); + printf( "\tNumber of resets to reference space: %llu. Avg. iterations per reset: %u\n", + pseNumResetReferenceSpace, + pseNumResetReferenceSpace > 0 + ? (unsigned)( (double)pseNumIterations / pseNumResetReferenceSpace ) + : 0 ); printf( "\t--- SBT ---\n" ); printf( "\tNumber of tightened bounds: %llu\n", @@ -376,78 +368,63 @@ void Statistics::print() unsigned long long num_accepted_phase_pattern_update = getLongAttribute( Statistics::NUM_ACCEPTED_PHASE_PATTERN_UPDATE ); printf( "\tNumber of proposed phase pattern update: %llu. " - "Number of accepted update: %llu [%.2lf%%]\n" - , num_proposed_phase_pattern_update - , num_accepted_phase_pattern_update - , printPercents( num_accepted_phase_pattern_update, - num_proposed_phase_pattern_update ) ); + "Number of accepted update: %llu [%.2lf%%]\n", + num_proposed_phase_pattern_update, + num_accepted_phase_pattern_update, + printPercents( num_accepted_phase_pattern_update, num_proposed_phase_pattern_update ) ); unsigned long long totalTimeUpdatingSoIPatternPattern = getLongAttribute( Statistics::TOTAL_TIME_UPDATING_SOI_PHASE_PATTERN_MICRO ); - printf( "\tTotal time (%% of local search time) updating SoI phase pattern : %llu milli [%.2lf%%]\n" - , totalTimeUpdatingSoIPatternPattern - , printPercents( totalTimeUpdatingSoIPatternPattern, - totalTimePerformingLocalSearch ) ); + printf( "\tTotal time (%% of local search time) updating SoI phase pattern : %llu milli " + "[%.2lf%%]\n", + totalTimeUpdatingSoIPatternPattern, + printPercents( totalTimeUpdatingSoIPatternPattern, totalTimePerformingLocalSearch ) ); unsigned long long totalTimeObtainCurrentAssignmentMicro = getLongAttribute( Statistics::TOTAL_TIME_OBTAIN_CURRENT_ASSIGNMENT_MICRO ); - printf( "\tTotal time obtaining current assignment: %llu milli [%.2lf%%]\n" - , totalTimeObtainCurrentAssignmentMicro - , printPercents( totalTimeObtainCurrentAssignmentMicro, - totalTimePerformingLocalSearch ) ); + printf( + "\tTotal time obtaining current assignment: %llu milli [%.2lf%%]\n", + totalTimeObtainCurrentAssignmentMicro, + printPercents( totalTimeObtainCurrentAssignmentMicro, totalTimePerformingLocalSearch ) ); unsigned long long totalTimeGettingSoIPhasePatternMicro = getLongAttribute( Statistics::TOTAL_TIME_GETTING_SOI_PHASE_PATTERN_MICRO ); - printf( "\tTotal time getting SoI phase pattern : %llu milli [%.2lf%%]\n" - , totalTimeGettingSoIPhasePatternMicro - , printPercents( totalTimeGettingSoIPhasePatternMicro, - timeMainLoopMicro ) ); + printf( "\tTotal time getting SoI phase pattern : %llu milli [%.2lf%%]\n", + totalTimeGettingSoIPhasePatternMicro, + printPercents( totalTimeGettingSoIPhasePatternMicro, timeMainLoopMicro ) ); printf( "\t--- Context dependent statistics ---\n" ); - printf( "\tNumber of pushes / pops: %u / %u\n" - , getUnsignedAttribute( Statistics::NUM_CONTEXT_PUSHES ) - , getUnsignedAttribute( Statistics::NUM_CONTEXT_POPS ) - ); - unsigned long long totalTimeContextPushHook = + printf( "\tNumber of pushes / pops: %u / %u\n", + getUnsignedAttribute( Statistics::NUM_CONTEXT_PUSHES ), + getUnsignedAttribute( Statistics::NUM_CONTEXT_POPS ) ); + unsigned long long totalTimeContextPushHook = getLongAttribute( Statistics::TIME_CONTEXT_PUSH_HOOK ); - printf( "\t\t[%.2lf%%] Pre-Push hook: %llu milli\n" - , printPercents( totalTimeContextPushHook, - timeMainLoopMicro ) - , totalTimeContextPushHook/ 1000 - ); - unsigned long long totalTimeContextPush = - getLongAttribute( Statistics::TIME_CONTEXT_PUSH ); - printf( "\t\t[%.2lf%%] Push : %llu milli\n" - , printPercents( totalTimeContextPush, - timeMainLoopMicro ) - , totalTimeContextPush/ 1000 - ); + printf( "\t\t[%.2lf%%] Pre-Push hook: %llu milli\n", + printPercents( totalTimeContextPushHook, timeMainLoopMicro ), + totalTimeContextPushHook / 1000 ); + unsigned long long totalTimeContextPush = getLongAttribute( Statistics::TIME_CONTEXT_PUSH ); + printf( "\t\t[%.2lf%%] Push : %llu milli\n", + printPercents( totalTimeContextPush, timeMainLoopMicro ), + totalTimeContextPush / 1000 ); unsigned long long totalTimeContextPopHook = getLongAttribute( Statistics::TIME_CONTEXT_POP_HOOK ); - printf( "\t\t[%.2lf%%] Post-Pop hook: %llu milli\n" - , printPercents( totalTimeContextPopHook, - timeMainLoopMicro ) - , totalTimeContextPopHook/ 1000 - ); - unsigned long long totalTimeContextPop = - getLongAttribute( Statistics::TIME_CONTEXT_POP ); - printf( "\t\t[%.2lf%%] Pop : %llu milli\n" - , printPercents( totalTimeContextPop, - timeMainLoopMicro ) - , totalTimeContextPop/ 1000 - ); - - unsigned long long totalContextTime = - totalTimeContextPop + - totalTimeContextPopHook + - totalTimeContextPush + - totalTimeContextPushHook; - - printf( "\t\t[%.2lf%%] Total context-switching time: %llu milli\n" - , printPercents( totalContextTime, timeMainLoopMicro ) - , totalContextTime / 1000 - ); + printf( "\t\t[%.2lf%%] Post-Pop hook: %llu milli\n", + printPercents( totalTimeContextPopHook, timeMainLoopMicro ), + totalTimeContextPopHook / 1000 ); + unsigned long long totalTimeContextPop = getLongAttribute( Statistics::TIME_CONTEXT_POP ); + printf( "\t\t[%.2lf%%] Pop : %llu milli\n", + printPercents( totalTimeContextPop, timeMainLoopMicro ), + totalTimeContextPop / 1000 ); + + unsigned long long totalContextTime = totalTimeContextPop + totalTimeContextPopHook + + totalTimeContextPush + totalTimeContextPushHook; + + printf( "\t\t[%.2lf%%] Total context-switching time: %llu milli\n", + printPercents( totalContextTime, timeMainLoopMicro ), + totalContextTime / 1000 ); printf( "\t--- Proof Certificate ---\n" ); - printf( "\tNumber of certified leaves: %u\n", getUnsignedAttribute( Statistics::NUM_CERTIFIED_LEAVES ) ); - printf( "\tNumber of leaves to delegate: %u\n", getUnsignedAttribute( Statistics::NUM_DELEGATED_LEAVES ) ); + printf( "\tNumber of certified leaves: %u\n", + getUnsignedAttribute( Statistics::NUM_CERTIFIED_LEAVES ) ); + printf( "\tNumber of leaves to delegate: %u\n", + getUnsignedAttribute( Statistics::NUM_DELEGATED_LEAVES ) ); } unsigned long long Statistics::getTotalTimeInMicro() const @@ -460,8 +437,7 @@ unsigned Statistics::getAveragePivotTimeInMicro() const if ( _longAttributes[NUM_TABLEAU_PIVOTS] == 0 ) return 0; - return _longAttributes[TIME_PIVOTS_MICRO] / - _longAttributes[NUM_TABLEAU_PIVOTS]; + return _longAttributes[TIME_PIVOTS_MICRO] / _longAttributes[NUM_TABLEAU_PIVOTS]; } void Statistics::timeout() @@ -498,9 +474,12 @@ double Statistics::printAverage( unsigned long long part, unsigned long long tot void Statistics::printLongAttributeAsTime( unsigned long long longAsNumber ) const { - unsigned int seconds = longAsNumber / 1000000; - unsigned int minutes = seconds / 60; - unsigned int hours = minutes / 60; - printf( "%llu milli (%02u:%02u:%02u)\n", - longAsNumber / 1000, hours, minutes - ( hours * 60 ), seconds - ( minutes * 60 ) ); + unsigned int seconds = longAsNumber / 1000000; + unsigned int minutes = seconds / 60; + unsigned int hours = minutes / 60; + printf( "%llu milli (%02u:%02u:%02u)\n", + longAsNumber / 1000, + hours, + minutes - ( hours * 60 ), + seconds - ( minutes * 60 ) ); } diff --git a/src/common/Statistics.h b/src/common/Statistics.h index f60123eee6..9c8cba6a1f 100644 --- a/src/common/Statistics.h +++ b/src/common/Statistics.h @@ -25,208 +25,205 @@ class Statistics public: Statistics(); - enum StatisticsUnsignedAttribute - { - // Number of piecewise linear constraints (active, total, and - // reason for split) - NUM_PL_CONSTRAINTS, - NUM_ACTIVE_PL_CONSTRAINTS, - NUM_PL_VALID_SPLITS, - NUM_PL_SMT_ORIGINATED_SPLITS, - - // Precision restoration - NUM_PRECISION_RESTORATIONS, - - // Current and max stack depth in the SMT core - CURRENT_DECISION_LEVEL, - MAX_DECISION_LEVEL, - - // Total number of splits so far - NUM_SPLITS, - - // Total number of pops so far - NUM_POPS, - - // Number of calls to context push and pop - NUM_CONTEXT_PUSHES, - NUM_CONTEXT_POPS, - - // Total number of states in the search tree visited so far - NUM_VISITED_TREE_STATES, - - // Current Tableau dimensions - CURRENT_TABLEAU_M, - CURRENT_TABLEAU_N, - - // Preprocessor counters - PP_NUM_ELIMINATED_VARS, - PP_NUM_TIGHTENING_ITERATIONS, - PP_NUM_CONSTRAINTS_REMOVED, - PP_NUM_EQUATIONS_REMOVED, - - // Total number of valid case splits performed so far (including in other - // branches of the search tree, that have since been popped) - TOTAL_NUMBER_OF_VALID_CASE_SPLITS, - - // Total number of delegated and certified leaves in the search tree - NUM_CERTIFIED_LEAVES, - NUM_DELEGATED_LEAVES, + enum StatisticsUnsignedAttribute { + // Number of piecewise linear constraints (active, total, and + // reason for split) + NUM_PL_CONSTRAINTS, + NUM_ACTIVE_PL_CONSTRAINTS, + NUM_PL_VALID_SPLITS, + NUM_PL_SMT_ORIGINATED_SPLITS, + + // Precision restoration + NUM_PRECISION_RESTORATIONS, + + // Current and max stack depth in the SMT core + CURRENT_DECISION_LEVEL, + MAX_DECISION_LEVEL, + + // Total number of splits so far + NUM_SPLITS, + + // Total number of pops so far + NUM_POPS, + + // Number of calls to context push and pop + NUM_CONTEXT_PUSHES, + NUM_CONTEXT_POPS, + + // Total number of states in the search tree visited so far + NUM_VISITED_TREE_STATES, + + // Current Tableau dimensions + CURRENT_TABLEAU_M, + CURRENT_TABLEAU_N, + + // Preprocessor counters + PP_NUM_ELIMINATED_VARS, + PP_NUM_TIGHTENING_ITERATIONS, + PP_NUM_CONSTRAINTS_REMOVED, + PP_NUM_EQUATIONS_REMOVED, + + // Total number of valid case splits performed so far (including in other + // branches of the search tree, that have since been popped) + TOTAL_NUMBER_OF_VALID_CASE_SPLITS, + + // Total number of delegated and certified leaves in the search tree + NUM_CERTIFIED_LEAVES, + NUM_DELEGATED_LEAVES, }; - enum StatisticsLongAttribute - { - // Preprocessing time - PREPROCESSING_TIME_MICRO, + enum StatisticsLongAttribute { + // Preprocessing time + PREPROCESSING_TIME_MICRO, - // Calculate output bounds time - CALCULATE_BOUNDS_TIME_MICRO, + // Calculate output bounds time + CALCULATE_BOUNDS_TIME_MICRO, - // Number of iterations of the main loop - NUM_MAIN_LOOP_ITERATIONS, + // Number of iterations of the main loop + NUM_MAIN_LOOP_ITERATIONS, - // Number of simplex steps, i.e. pivots (including degenerate - // pivots), performed by the main loop - NUM_SIMPLEX_STEPS, + // Number of simplex steps, i.e. pivots (including degenerate + // pivots), performed by the main loop + NUM_SIMPLEX_STEPS, - // Total time spent on performing simplex steps, in microseconds - TIME_SIMPLEX_STEPS_MICRO, + // Total time spent on performing simplex steps, in microseconds + TIME_SIMPLEX_STEPS_MICRO, - // Total time spent in the main loop, in microseconds - TIME_MAIN_LOOP_MICRO, + // Total time spent in the main loop, in microseconds + TIME_MAIN_LOOP_MICRO, - // Total time spent on performing constraint fixing steps, in microseconds - TIME_CONSTRAINT_FIXING_STEPS_MICRO, + // Total time spent on performing constraint fixing steps, in microseconds + TIME_CONSTRAINT_FIXING_STEPS_MICRO, - // performed by the main loop - NUM_CONSTRAINT_FIXING_STEPS, + // performed by the main loop + NUM_CONSTRAINT_FIXING_STEPS, - // degenerate and non-degenerate - NUM_TABLEAU_PIVOTS, + // degenerate and non-degenerate + NUM_TABLEAU_PIVOTS, - // Total number of degenerate tableau pivot operations performed - NUM_TABLEAU_DEGENERATE_PIVOTS, + // Total number of degenerate tableau pivot operations performed + NUM_TABLEAU_DEGENERATE_PIVOTS, - // by explicit request - NUM_TABLEAU_DEGENERATE_PIVOTS_BY_REQUEST, + // by explicit request + NUM_TABLEAU_DEGENERATE_PIVOTS_BY_REQUEST, - // Total time for performing pivots (both real and degenrate), in microseconds - TIME_PIVOTS_MICRO, + // Total time for performing pivots (both real and degenrate), in microseconds + TIME_PIVOTS_MICRO, - // element was too small - NUM_SIMPLEX_PIVOT_SELECTIONS_IGNORED_FOR_STABILITY, + // element was too small + NUM_SIMPLEX_PIVOT_SELECTIONS_IGNORED_FOR_STABILITY, - // no better option could be found. - NUM_SIMPLEX_UNSTABLE_PIVOTS, + // no better option could be found. + NUM_SIMPLEX_UNSTABLE_PIVOTS, - // Total number of rows added to the tableau - NUM_ADDED_ROWS, + // Total number of rows added to the tableau + NUM_ADDED_ROWS, - // Total number of merged columns in the tableau - NUM_MERGED_COLUMNS, + // Total number of merged columns in the tableau + NUM_MERGED_COLUMNS, - // opposite bound. - NUM_TABLEAU_BOUND_HOPPING, + // opposite bound. + NUM_TABLEAU_BOUND_HOPPING, - // This combines tightenings from all sources: rows, basis, PL constraints, etc. - NUM_TIGHTENED_BOUNDS, + // This combines tightenings from all sources: rows, basis, PL constraints, etc. + NUM_TIGHTENED_BOUNDS, - // The number of bounds tightened via symbolic bound tightening - NUM_TIGHTENINGS_FROM_SYMBOLIC_BOUND_TIGHTENING, + // The number of bounds tightened via symbolic bound tightening + NUM_TIGHTENINGS_FROM_SYMBOLIC_BOUND_TIGHTENING, - // Number of pivot rows examined by the row tightener, and consequent - // tightenings proposed. - NUM_ROWS_EXAMINED_BY_ROW_TIGHTENER, - NUM_TIGHTENINGS_FROM_ROWS, + // Number of pivot rows examined by the row tightener, and consequent + // tightenings proposed. + NUM_ROWS_EXAMINED_BY_ROW_TIGHTENER, + NUM_TIGHTENINGS_FROM_ROWS, - // Number of explicit basis matrices examined by the row tightener, and - // consequent tightenings proposed. - NUM_BOUND_TIGHTENINGS_ON_EXPLICIT_BASIS, - NUM_TIGHTENINGS_FROM_EXPLICIT_BASIS, + // Number of explicit basis matrices examined by the row tightener, and + // consequent tightenings proposed. + NUM_BOUND_TIGHTENINGS_ON_EXPLICIT_BASIS, + NUM_TIGHTENINGS_FROM_EXPLICIT_BASIS, - // Number of bound notifications sent to pl constraints - NUM_BOUND_NOTIFICATIONS_TO_PL_CONSTRAINTS, + // Number of bound notifications sent to pl constraints + NUM_BOUND_NOTIFICATIONS_TO_PL_CONSTRAINTS, - // Number of bound notification send to nonlinear constraints - NUM_BOUND_NOTIFICATIONS_TO_TRANSCENDENTAL_CONSTRAINTS, + // Number of bound notification send to nonlinear constraints + NUM_BOUND_NOTIFICATIONS_TO_TRANSCENDENTAL_CONSTRAINTS, - // Number of bound tightenings proposed by the pl constraints - NUM_BOUNDS_PROPOSED_BY_PL_CONSTRAINTS, + // Number of bound tightenings proposed by the pl constraints + NUM_BOUNDS_PROPOSED_BY_PL_CONSTRAINTS, - // Number of bound tightening rounds performed on the constraint matrix, - // and consequent tightenings proposed. - NUM_BOUND_TIGHTENINGS_ON_CONSTRAINT_MATRIX, - NUM_TIGHTENINGS_FROM_CONSTRAINT_MATRIX, + // Number of bound tightening rounds performed on the constraint matrix, + // and consequent tightenings proposed. + NUM_BOUND_TIGHTENINGS_ON_CONSTRAINT_MATRIX, + NUM_TIGHTENINGS_FROM_CONSTRAINT_MATRIX, - // Basis factorization statistics - NUM_BASIS_REFACTORIZATIONS, + // Basis factorization statistics + NUM_BASIS_REFACTORIZATIONS, - // Projected steepest edge statistics - PSE_NUM_ITERATIONS, - PSE_NUM_RESET_REFERENCE_SPACE, + // Projected steepest edge statistics + PSE_NUM_ITERATIONS, + PSE_NUM_RESET_REFERENCE_SPACE, - // Total amount of time spent performing valid case splits - TOTAL_TIME_PERFORMING_VALID_CASE_SPLITS_MICRO, - TOTAL_TIME_PERFORMING_SYMBOLIC_BOUND_TIGHTENING, + // Total amount of time spent performing valid case splits + TOTAL_TIME_PERFORMING_VALID_CASE_SPLITS_MICRO, + TOTAL_TIME_PERFORMING_SYMBOLIC_BOUND_TIGHTENING, - // Total amount of time handling statistics printing - TOTAL_TIME_HANDLING_STATISTICS_MICRO, + // Total amount of time handling statistics printing + TOTAL_TIME_HANDLING_STATISTICS_MICRO, - // Total amount of time spent performing explicit-basis bound tightening - TOTAL_TIME_EXPLICIT_BASIS_BOUND_TIGHTENING_MICRO, + // Total amount of time spent performing explicit-basis bound tightening + TOTAL_TIME_EXPLICIT_BASIS_BOUND_TIGHTENING_MICRO, - // Total amount of time spent on degradation checking - TOTAL_TIME_DEGRADATION_CHECKING, + // Total amount of time spent on degradation checking + TOTAL_TIME_DEGRADATION_CHECKING, - // Total amount of time spent on precision restoration - TOTAL_TIME_PRECISION_RESTORATION, + // Total amount of time spent on precision restoration + TOTAL_TIME_PRECISION_RESTORATION, - // Total amount of time spent performing constraint-matrix bound tightening - TOTAL_TIME_CONSTRAINT_MATRIX_BOUND_TIGHTENING_MICRO, + // Total amount of time spent performing constraint-matrix bound tightening + TOTAL_TIME_CONSTRAINT_MATRIX_BOUND_TIGHTENING_MICRO, - // Total amount of time spent applying previously stored bound tightenings - TOTAL_TIME_APPLYING_STORED_TIGHTENINGS_MICRO, + // Total amount of time spent applying previously stored bound tightenings + TOTAL_TIME_APPLYING_STORED_TIGHTENINGS_MICRO, - // Total amount of time spent within the SMT core - TOTAL_TIME_SMT_CORE_MICRO, + // Total amount of time spent within the SMT core + TOTAL_TIME_SMT_CORE_MICRO, - // Total time heuristically updating the SoI phase pattern - TOTAL_TIME_UPDATING_SOI_PHASE_PATTERN_MICRO, + // Total time heuristically updating the SoI phase pattern + TOTAL_TIME_UPDATING_SOI_PHASE_PATTERN_MICRO, - // Number of proposed/accepted update to the SoI phase pattern. - NUM_PROPOSED_PHASE_PATTERN_UPDATE, - NUM_ACCEPTED_PHASE_PATTERN_UPDATE, + // Number of proposed/accepted update to the SoI phase pattern. + NUM_PROPOSED_PHASE_PATTERN_UPDATE, + NUM_ACCEPTED_PHASE_PATTERN_UPDATE, - // Total time obtaining the current variable assignment from the tableau. - TOTAL_TIME_OBTAIN_CURRENT_ASSIGNMENT_MICRO, + // Total time obtaining the current variable assignment from the tableau. + TOTAL_TIME_OBTAIN_CURRENT_ASSIGNMENT_MICRO, - // Total time performing SoI-based local search - TOTAL_TIME_LOCAL_SEARCH_MICRO, + // Total time performing SoI-based local search + TOTAL_TIME_LOCAL_SEARCH_MICRO, - // Total time getting the SoI phase pattern - TOTAL_TIME_GETTING_SOI_PHASE_PATTERN_MICRO, + // Total time getting the SoI phase pattern + TOTAL_TIME_GETTING_SOI_PHASE_PATTERN_MICRO, - // Total time adding constraints to (MI)LP solver. - TIME_ADDING_CONSTRAINTS_TO_MILP_SOLVER_MICRO, + // Total time adding constraints to (MI)LP solver. + TIME_ADDING_CONSTRAINTS_TO_MILP_SOLVER_MICRO, - // Total time spent in context-switching - TIME_CONTEXT_PUSH, - TIME_CONTEXT_POP, - TIME_CONTEXT_PUSH_HOOK, - TIME_CONTEXT_POP_HOOK, + // Total time spent in context-switching + TIME_CONTEXT_PUSH, + TIME_CONTEXT_POP, + TIME_CONTEXT_PUSH_HOOK, + TIME_CONTEXT_POP_HOOK, - // Total Certification Time - TOTAL_CERTIFICATION_TIME, + // Total Certification Time + TOTAL_CERTIFICATION_TIME, }; - enum StatisticsDoubleAttribute - { - // Degradation and restorations - CURRENT_DEGRADATION, - MAX_DEGRADATION, + enum StatisticsDoubleAttribute { + // Degradation and restorations + CURRENT_DEGRADATION, + MAX_DEGRADATION, - // How close we are to the minimum of the SoI (0). - COST_OF_CURRENT_PHASE_PATTERN, - MIN_COST_OF_PHASE_PATTERN, + // How close we are to the minimum of the SoI (0). + COST_OF_CURRENT_PHASE_PATTERN, + MIN_COST_OF_PHASE_PATTERN, }; /* @@ -242,8 +239,7 @@ class Statistics /* Setters for unsigned, unsigned long long, and double attributes */ - inline void setUnsignedAttribute( StatisticsUnsignedAttribute attr, - unsigned value ) + inline void setUnsignedAttribute( StatisticsUnsignedAttribute attr, unsigned value ) { _unsignedAttributes[attr] = value; } @@ -253,14 +249,12 @@ class Statistics ++_unsignedAttributes[attr]; } - inline void incUnsignedAttribute( StatisticsUnsignedAttribute attr, - unsigned value ) + inline void incUnsignedAttribute( StatisticsUnsignedAttribute attr, unsigned value ) { _unsignedAttributes[attr] += value; } - inline void setLongAttribute( StatisticsLongAttribute attr, - unsigned long long value ) + inline void setLongAttribute( StatisticsLongAttribute attr, unsigned long long value ) { _longAttributes[attr] = value; } @@ -293,7 +287,7 @@ class Statistics return _unsignedAttributes[attr]; } - inline unsigned long long getLongAttribute( StatisticsLongAttribute attr ) const + inline unsigned long long getLongAttribute( StatisticsLongAttribute attr ) const { return _longAttributes[attr]; } diff --git a/src/common/T/Errno.h b/src/common/T/Errno.h index 72c0c50314..200443c247 100644 --- a/src/common/T/Errno.h +++ b/src/common/T/Errno.h @@ -19,17 +19,16 @@ #include -namespace T -{ - int errorNumber(); +namespace T { +int errorNumber(); } -CXXTEST_SUPPLY( errorNumber, /* => T::Base_AllocateIrp */ - int, /* Return type */ - errorNumber, /* Name of mock member */ - (), /* Prototype */ - T::errorNumber, /* Name of real function */ - () /* Parameter list */ ); +CXXTEST_SUPPLY( errorNumber, /* => T::Base_AllocateIrp */ + int, /* Return type */ + errorNumber, /* Name of mock member */ + (), /* Prototype */ + T::errorNumber, /* Name of real function */ + () /* Parameter list */ ); #endif // __T__Errno_h__ diff --git a/src/common/T/FileFactory.h b/src/common/T/FileFactory.h index 2a3e06f41d..c5cc4c073d 100644 --- a/src/common/T/FileFactory.h +++ b/src/common/T/FileFactory.h @@ -22,24 +22,23 @@ class IFile; class String; -namespace T -{ - IFile *createFile( const String &path ); - void discardFile( IFile *file ); -} - -CXXTEST_SUPPLY( createFile, /* => T::Base_AllocateIrp */ - IFile *, /* Return type */ - createFile, /* Name of mock member */ - ( const String &path ), /* Prototype */ - T::createFile, /* Name of real function */ - ( path ) /* Parameter list */ ); - -CXXTEST_SUPPLY_VOID( discardFile, /* => T::Base_AllocateIrp */ - discardFile, /* Name of mock member */ - ( IFile *file ), /* Prototype */ - T::discardFile, /* Name of real function */ - ( file ) /* Parameter list */ ); +namespace T { +IFile *createFile( const String &path ); +void discardFile( IFile *file ); +} // namespace T + +CXXTEST_SUPPLY( createFile, /* => T::Base_AllocateIrp */ + IFile *, /* Return type */ + createFile, /* Name of mock member */ + ( const String &path ), /* Prototype */ + T::createFile, /* Name of real function */ + ( path ) /* Parameter list */ ); + +CXXTEST_SUPPLY_VOID( discardFile, /* => T::Base_AllocateIrp */ + discardFile, /* Name of mock member */ + ( IFile *file ), /* Prototype */ + T::discardFile, /* Name of real function */ + ( file ) /* Parameter list */ ); #endif // __T__FileFactory_h__ diff --git a/src/common/T/stdlib.h b/src/common/T/stdlib.h index 35ee378ff0..5505e2f0a9 100644 --- a/src/common/T/stdlib.h +++ b/src/common/T/stdlib.h @@ -20,28 +20,15 @@ #include #include -CXXTEST_MOCK_GLOBAL( void *, - malloc, - ( size_t size ), - ( size ) ); - -CXXTEST_MOCK_VOID_GLOBAL( free, - ( void *ptr ), - ( ptr ) ); - -CXXTEST_MOCK_GLOBAL( void *, - realloc, - ( void *ptr, size_t size ), - ( ptr, size ) ); - -CXXTEST_MOCK_VOID_GLOBAL( srand, - ( unsigned seed ), - ( seed ) ); - -CXXTEST_MOCK_GLOBAL( int, - rand, - (), - () ); +CXXTEST_MOCK_GLOBAL( void *, malloc, ( size_t size ), ( size ) ); + +CXXTEST_MOCK_VOID_GLOBAL( free, ( void *ptr ), ( ptr ) ); + +CXXTEST_MOCK_GLOBAL( void *, realloc, ( void *ptr, size_t size ), ( ptr, size ) ); + +CXXTEST_MOCK_VOID_GLOBAL( srand, ( unsigned seed ), ( seed ) ); + +CXXTEST_MOCK_GLOBAL( int, rand, (), () ); #endif // __T__Stdlib_h__ diff --git a/src/common/T/sys/stat.h b/src/common/T/sys/stat.h index ce6896ea0c..d309d31d37 100644 --- a/src/common/T/sys/stat.h +++ b/src/common/T/sys/stat.h @@ -18,7 +18,6 @@ #define __T__sys__Stat_h__ #include - #include #include #include @@ -28,9 +27,9 @@ #endif CXXTEST_MOCK_GLOBAL( int, - open, - ( const char *pathname, int flags, mode_t mode ), - ( pathname, flags, mode ) ); + open, + ( const char *pathname, int flags, mode_t mode ), + ( pathname, flags, mode ) ); #endif // __T__sys__Stat_h__ diff --git a/src/common/T/unistd.h b/src/common/T/unistd.h index e8e5291ccb..c9d593f5fc 100644 --- a/src/common/T/unistd.h +++ b/src/common/T/unistd.h @@ -27,16 +27,10 @@ typedef struct stat StructStat; -CXXTEST_MOCK_GLOBAL( int, - close, - ( int fd ), - ( fd ) ); +CXXTEST_MOCK_GLOBAL( int, close, ( int fd ), ( fd ) ); #ifndef _WIN32 -CXXTEST_MOCK_GLOBAL( pid_t, - fork, - (), - () ); +CXXTEST_MOCK_GLOBAL( pid_t, fork, (), () ); #endif CXXTEST_MOCK_GLOBAL( ssize_t, @@ -44,41 +38,21 @@ CXXTEST_MOCK_GLOBAL( ssize_t, ( int fd, const void *buf, size_t count ), ( fd, buf, count ) ); -CXXTEST_MOCK_GLOBAL( ssize_t, - read, - ( int fd, void *buf, size_t count ), - ( fd, buf, count ) ); +CXXTEST_MOCK_GLOBAL( ssize_t, read, ( int fd, void *buf, size_t count ), ( fd, buf, count ) ); -CXXTEST_MOCK_VOID_GLOBAL( _exit, - ( int status ), - ( status ) ); +CXXTEST_MOCK_VOID_GLOBAL( _exit, ( int status ), ( status ) ); -CXXTEST_MOCK_GLOBAL( int, - stat, - ( const char *path, StructStat *buf ), - ( path, buf ) ); +CXXTEST_MOCK_GLOBAL( int, stat, ( const char *path, StructStat *buf ), ( path, buf ) ); #ifndef _WIN32 -CXXTEST_MOCK_GLOBAL( unsigned, - sleep, - ( unsigned seconds ), - ( seconds ) ); +CXXTEST_MOCK_GLOBAL( unsigned, sleep, ( unsigned seconds ), ( seconds ) ); -CXXTEST_MOCK_GLOBAL( int, - pipe, - ( int fildes[2] ), - ( fildes ) ); +CXXTEST_MOCK_GLOBAL( int, pipe, ( int fildes[2] ), ( fildes ) ); #endif -CXXTEST_MOCK_GLOBAL( int, - execvp, - ( const char *file, char *const argv[] ), - ( file, argv ) ); +CXXTEST_MOCK_GLOBAL( int, execvp, ( const char *file, char *const argv[] ), ( file, argv ) ); -CXXTEST_MOCK_GLOBAL( int, - dup2, - ( int oldfd, int newfd ), - ( oldfd, newfd ) ); +CXXTEST_MOCK_GLOBAL( int, dup2, ( int oldfd, int newfd ), ( oldfd, newfd ) ); #endif // __T__Unistd_h__ diff --git a/src/common/TimeUtils.cpp b/src/common/TimeUtils.cpp index e2eb32ef0d..21671dfe99 100644 --- a/src/common/TimeUtils.cpp +++ b/src/common/TimeUtils.cpp @@ -13,35 +13,37 @@ **/ -#include "MStringf.h" #include "TimeUtils.h" +#include "MStringf.h" + struct timespec TimeUtils::sampleMicro() { struct timespec now; #ifdef _WIN32 - LARGE_INTEGER count; + LARGE_INTEGER count; - if ( gFirstTime ) - { - gFirstTime = 0; + if ( gFirstTime ) + { + gFirstTime = 0; - if ( 0 == QueryPerformanceFrequency( &gCountsPerSec ) ) - { - gCountsPerSec.QuadPart = 0; - } - } - QueryPerformanceCounter( &count ); - now.tv_sec = count.QuadPart / gCountsPerSec.QuadPart; - now.tv_nsec = ( ( count.QuadPart % gCountsPerSec.QuadPart ) * static_cast( 1000000000 ) ) / gCountsPerSec.QuadPart; + if ( 0 == QueryPerformanceFrequency( &gCountsPerSec ) ) + { + gCountsPerSec.QuadPart = 0; + } + } + QueryPerformanceCounter( &count ); + now.tv_sec = count.QuadPart / gCountsPerSec.QuadPart; + now.tv_nsec = + ( ( count.QuadPart % gCountsPerSec.QuadPart ) * static_cast( 1000000000 ) ) / + gCountsPerSec.QuadPart; #else clock_gettime( CLOCK_MONOTONIC, &now ); #endif return now; } -unsigned long long TimeUtils::timePassed( const struct timespec &then, - const struct timespec &now ) +unsigned long long TimeUtils::timePassed( const struct timespec &then, const struct timespec &now ) { enum { MICROSECONDS_IN_SECOND = 1000000, @@ -57,9 +59,10 @@ unsigned long long TimeUtils::timePassed( const struct timespec &then, String TimeUtils::now() { time_t secondsSinceEpoch = time( NULL ); - struct tm *formattedTime = localtime( &secondsSinceEpoch); + struct tm *formattedTime = localtime( &secondsSinceEpoch ); - return Stringf( "%02u:%02u:%02u", formattedTime->tm_hour, formattedTime->tm_min, formattedTime->tm_sec ); + return Stringf( + "%02u:%02u:%02u", formattedTime->tm_hour, formattedTime->tm_min, formattedTime->tm_sec ); } // diff --git a/src/common/TimeUtils.h b/src/common/TimeUtils.h index eedf43a62f..0702333f13 100644 --- a/src/common/TimeUtils.h +++ b/src/common/TimeUtils.h @@ -32,8 +32,7 @@ class TimeUtils { public: static struct timespec sampleMicro(); - static unsigned long long timePassed( const struct timespec &then, - const struct timespec &now ); + static unsigned long long timePassed( const struct timespec &then, const struct timespec &now ); static String now(); }; diff --git a/src/common/Vector.h b/src/common/Vector.h index 39d04a8dee..a3121f6346 100644 --- a/src/common/Vector.h +++ b/src/common/Vector.h @@ -16,16 +16,16 @@ #ifndef __Vector_h__ #define __Vector_h__ +#include "CommonError.h" + #include #include - -#include "CommonError.h" #include -template -class Vector +template class Vector { typedef std::vector Super; + public: typedef typename Super::iterator iterator; typedef typename Super::const_iterator const_iterator; @@ -36,26 +36,30 @@ class Vector { } - Vector( const Vector &rhs) = default; + Vector( const Vector &rhs ) = default; - Vector( const std::initializer_list &initializerList ) : _container( initializerList ) + Vector( const std::initializer_list &initializerList ) + : _container( initializerList ) { } - Vector( unsigned size ) : _container( size ) + Vector( unsigned size ) + : _container( size ) { } - Vector( unsigned size, T value ) : _container( size, value ) + Vector( unsigned size, T value ) + : _container( size, value ) { } - template - Vector( InputIt begin, InputIt end) : _container( begin, end ) + template + Vector( InputIt begin, InputIt end ) + : _container( begin, end ) { } - virtual void assign ( unsigned size, T value ) + virtual void assign( unsigned size, T value ) { _container.assign( size, value ); } @@ -124,7 +128,7 @@ class Vector { for ( iterator it = _container.begin(); it != _container.end(); ++it ) { - if ( (*it) == value ) + if ( ( *it ) == value ) { _container.erase( it ); return; @@ -138,7 +142,7 @@ class Vector { for ( iterator it = _container.begin(); it != _container.end(); ++it ) { - if ( (*it) == value ) + if ( ( *it ) == value ) { _container.erase( it ); return; @@ -219,7 +223,7 @@ class Vector Vector &operator+=( const Vector &other ) { - (*this) = (*this) + other; + ( *this ) = ( *this ) + other; return *this; } diff --git a/src/common/real/Errno.cpp b/src/common/real/Errno.cpp index 8a7cb5d60f..caa37eb2ba 100644 --- a/src/common/real/Errno.cpp +++ b/src/common/real/Errno.cpp @@ -16,13 +16,12 @@ #include -namespace T +namespace T { +int errorNumber() { - int errorNumber() - { - return errno; - } + return errno; } +} // namespace T // // Local Variables: diff --git a/src/common/real/FileFactory.cpp b/src/common/real/FileFactory.cpp index 6aac31f7c8..1ca77f7b95 100644 --- a/src/common/real/FileFactory.cpp +++ b/src/common/real/FileFactory.cpp @@ -16,18 +16,17 @@ #include "File.h" -namespace T +namespace T { +IFile *createFile( const String &path ) { - IFile *createFile( const String &path ) - { - return new File( path ); - } + return new File( path ); +} - void discardFile( IFile *file ) - { - delete file; - } +void discardFile( IFile *file ) +{ + delete file; } +} // namespace T // // Local Variables: diff --git a/src/common/tests/MockErrno.h b/src/common/tests/MockErrno.h index 0b52dddb32..981d48eebb 100644 --- a/src/common/tests/MockErrno.h +++ b/src/common/tests/MockErrno.h @@ -19,21 +19,20 @@ #include "T/Errno.h" -class MockErrno : - public T::Base_errorNumber +class MockErrno : public T::Base_errorNumber { public: - MockErrno() - { + MockErrno() + { nextErrno = 28; - } + } int nextErrno; int errorNumber() - { + { return nextErrno; - } + } }; #endif // __MockErrno_h__ diff --git a/src/common/tests/MockFile.h b/src/common/tests/MockFile.h index 8e8b9c5ab0..acce8412a0 100644 --- a/src/common/tests/MockFile.h +++ b/src/common/tests/MockFile.h @@ -24,23 +24,23 @@ class MockFile : public IFile { public: - MockFile() - { - wasCreated = false; - wasDiscarded = false; + MockFile() + { + wasCreated = false; + wasDiscarded = false; } - bool wasCreated; - bool wasDiscarded; + bool wasCreated; + bool wasDiscarded; String lastPath; - void mockConstructor( const String &path ) - { - TS_ASSERT( !wasCreated ); + void mockConstructor( const String &path ) + { + TS_ASSERT( !wasCreated ); wasCreated = true; lastPath = path; - } + } void mockDestructor() { @@ -75,7 +75,7 @@ class MockFile : public IFile return result; } - void read( HeapData &/* buffer */, unsigned /* maxReadSize */ ) + void read( HeapData & /* buffer */, unsigned /* maxReadSize */ ) { } diff --git a/src/common/tests/MockFileFactory.h b/src/common/tests/MockFileFactory.h index d97f530046..bb4342b060 100644 --- a/src/common/tests/MockFileFactory.h +++ b/src/common/tests/MockFileFactory.h @@ -20,30 +20,30 @@ #include "MockFile.h" #include "T/FileFactory.h" -class MockFileFactory : - public T::Base_createFile, - public T::Base_discardFile +class MockFileFactory + : public T::Base_createFile + , public T::Base_discardFile { public: - MockFile mockFile; - - ~MockFileFactory() - { - if ( mockFile.wasCreated ) - { - TS_ASSERT( mockFile.wasDiscarded ); - } - } - - IFile *createFile( const String &path ) - { - mockFile.mockConstructor( path ); - return &mockFile; - } - - void discardFile( IFile *file ) - { - TS_ASSERT_EQUALS( file, &mockFile ); + MockFile mockFile; + + ~MockFileFactory() + { + if ( mockFile.wasCreated ) + { + TS_ASSERT( mockFile.wasDiscarded ); + } + } + + IFile *createFile( const String &path ) + { + mockFile.mockConstructor( path ); + return &mockFile; + } + + void discardFile( IFile *file ) + { + TS_ASSERT_EQUALS( file, &mockFile ); mockFile.mockDestructor(); } }; diff --git a/src/common/tests/RealMalloc.h b/src/common/tests/RealMalloc.h index 58ef927483..3f03891555 100644 --- a/src/common/tests/RealMalloc.h +++ b/src/common/tests/RealMalloc.h @@ -19,10 +19,10 @@ #include "T/stdlib.h" -class RealMalloc : - public T::Real_malloc, - public T::Real_free, - public T::Real_realloc +class RealMalloc + : public T::Real_malloc + , public T::Real_free + , public T::Real_realloc { }; diff --git a/src/common/tests/Test_ConstSimpleData.h b/src/common/tests/Test_ConstSimpleData.h index 466351df9e..6b1b01d105 100644 --- a/src/common/tests/Test_ConstSimpleData.h +++ b/src/common/tests/Test_ConstSimpleData.h @@ -14,57 +14,57 @@ ** [[ Add lengthier description here ]] **/ -#include - #include "ConstSimpleData.h" #include "HeapData.h" #include "RealMalloc.h" +#include + class ConstSimpleDataTestSuite : public CxxTest::TestSuite { public: void test_constructor() - { - char data[] = { 'a','b','c' }; + { + char data[] = { 'a', 'b', 'c' }; - ConstSimpleData *constSimpleData = NULL; + ConstSimpleData *constSimpleData = NULL; - TS_ASSERT( constSimpleData = new ConstSimpleData( data, sizeof(data) ) ); + TS_ASSERT( constSimpleData = new ConstSimpleData( data, sizeof( data ) ) ); - TS_ASSERT_EQUALS( constSimpleData->size(), 3U ); - TS_ASSERT_SAME_DATA( constSimpleData->data(), data, sizeof(data) ); + TS_ASSERT_EQUALS( constSimpleData->size(), 3U ); + TS_ASSERT_SAME_DATA( constSimpleData->data(), data, sizeof( data ) ); - data[1] = 'd'; + data[1] = 'd'; - TS_ASSERT_EQUALS( constSimpleData->size(), 3U ); - TS_ASSERT_SAME_DATA( constSimpleData->data(), data, sizeof(data) ); + TS_ASSERT_EQUALS( constSimpleData->size(), 3U ); + TS_ASSERT_SAME_DATA( constSimpleData->data(), data, sizeof( data ) ); - TS_ASSERT_THROWS_NOTHING( delete constSimpleData ); - } + TS_ASSERT_THROWS_NOTHING( delete constSimpleData ); + } - void test_constructor__heap_data() - { + void test_constructor__heap_data() + { RealMalloc realMalloc; - char data[] = { 'a','b','c' }; + char data[] = { 'a', 'b', 'c' }; - HeapData heapData( data, sizeof(data) ); + HeapData heapData( data, sizeof( data ) ); - ConstSimpleData *constSimpleData = NULL; + ConstSimpleData *constSimpleData = NULL; - TS_ASSERT( constSimpleData = new ConstSimpleData( heapData ) ); + TS_ASSERT( constSimpleData = new ConstSimpleData( heapData ) ); - TS_ASSERT_EQUALS( constSimpleData->size(), 3U ); - TS_ASSERT_SAME_DATA( constSimpleData->data(), data, sizeof(data) ); + TS_ASSERT_EQUALS( constSimpleData->size(), 3U ); + TS_ASSERT_SAME_DATA( constSimpleData->data(), data, sizeof( data ) ); TS_ASSERT_THROWS_NOTHING( delete constSimpleData ); - } + } void test_as_char() { char data[] = { 'a', 'b', 'c' }; - ConstSimpleData constSimpleData( data, sizeof(data) ); + ConstSimpleData constSimpleData( data, sizeof( data ) ); TS_ASSERT_EQUALS( constSimpleData.asChar(), data ); } diff --git a/src/common/tests/Test_Error.h b/src/common/tests/Test_Error.h index 9b591c8e10..7dcbde2b9e 100644 --- a/src/common/tests/Test_Error.h +++ b/src/common/tests/Test_Error.h @@ -14,35 +14,35 @@ ** [[ Add lengthier description here ]] **/ -#include - #include "Error.h" #include "MString.h" #include "MockErrno.h" +#include + class ErrorTestSuite : public CxxTest::TestSuite { public: - void test_code_and_errno() - { + void test_code_and_errno() + { MockErrno mockErrno; mockErrno.nextErrno = 21; const char *msg = "common error"; - Error error1( msg, 5 ); - TS_ASSERT_EQUALS( error1.getCode(), 5 ); + Error error1( msg, 5 ); + TS_ASSERT_EQUALS( error1.getCode(), 5 ); TS_ASSERT_EQUALS( error1.getErrno(), 21 ); TS_ASSERT_EQUALS( String( error1.getErrorClass() ), String( "common error" ) ); mockErrno.nextErrno = 23; - Error error2( "common error", 166, "user message" ); - TS_ASSERT_EQUALS( error2.getCode(), 166 ); + Error error2( "common error", 166, "user message" ); + TS_ASSERT_EQUALS( error2.getCode(), 166 ); TS_ASSERT_EQUALS( error2.getErrno(), 23 ); TS_ASSERT_EQUALS( String( error2.getErrorClass() ), String( "common error" ) ); TS_ASSERT_EQUALS( String( error2.getUserMessage() ), String( "user message" ) ); - } + } }; // diff --git a/src/common/tests/Test_File.h b/src/common/tests/Test_File.h index 613b432d95..6d2d090548 100644 --- a/src/common/tests/Test_File.h +++ b/src/common/tests/Test_File.h @@ -14,8 +14,6 @@ ** [[ Add lengthier description here ]] **/ -#include - #include "CommonError.h" #include "ConstSimpleData.h" #include "File.h" @@ -24,33 +22,34 @@ #include "MStringf.h" #include "MockErrno.h" #include "RealMalloc.h" - #include "T/sys/stat.h" #include "T/unistd.h" +#include + #ifdef _WIN32 #include #endif -class MockForFile : - public RealMalloc, - public MockErrno, - public T::Base_open, - public T::Base_write, - public T::Base_read, - public T::Base_close, - public T::Base_stat +class MockForFile + : public RealMalloc + , public MockErrno + , public T::Base_open + , public T::Base_write + , public T::Base_read + , public T::Base_close + , public T::Base_stat { public: - MockForFile() - { + MockForFile() + { nextDescriptor = 17; openWasCalled = false; writeShouldFail = false; closeWasCalled = false; readShouldFail = false; statShouldFail = false; - } + } String lastPathname; int lastFlags; @@ -115,7 +114,8 @@ class MockForFile : unsigned bytes = std::min( count, (size_t)nextReadData.size() ); memcpy( buf, nextReadData.data(), bytes ); - HeapData tempData = ConstSimpleData( (char *)(nextReadData.data()) + bytes, nextReadData.size() - bytes ); + HeapData tempData = + ConstSimpleData( (char *)( nextReadData.data() ) + bytes, nextReadData.size() - bytes ); nextReadData = tempData; return bytes; @@ -130,9 +130,9 @@ class MockForFile : { lastStatPath = path; - memset( buf, 0, sizeof(struct stat) ); + memset( buf, 0, sizeof( struct stat ) ); buf->st_size = (off_t)nextFileSize; - memcpy( &buf->st_mode, &nextFileMode, sizeof(mode_t) ); + memcpy( &buf->st_mode, &nextFileMode, sizeof( mode_t ) ); return statShouldFail ? -1 : 0; } @@ -141,17 +141,17 @@ class MockForFile : class FileTestSuite : public CxxTest::TestSuite { public: - MockForFile *mock; + MockForFile *mock; - void setUp() - { - TS_ASSERT( mock = new MockForFile ); - } + void setUp() + { + TS_ASSERT( mock = new MockForFile ); + } - void tearDown() - { - TS_ASSERT_THROWS_NOTHING( delete mock ); - } + void tearDown() + { + TS_ASSERT_THROWS_NOTHING( delete mock ); + } void test_todo() { @@ -264,10 +264,8 @@ class FileTestSuite : public CxxTest::TestSuite mock->writeShouldFail = true; - TS_ASSERT_THROWS_EQUALS( file.write( line1 ), - const CommonError &e, - e.getCode(), - CommonError::WRITE_FAILED ); + TS_ASSERT_THROWS_EQUALS( + file.write( line1 ), const CommonError &e, e.getCode(), CommonError::WRITE_FAILED ); } void xtest_read() @@ -278,7 +276,7 @@ class FileTestSuite : public CxxTest::TestSuite char toRead[] = "hello world, im a buffer"; - mock->nextReadData = ConstSimpleData( toRead, sizeof(toRead) ); + mock->nextReadData = ConstSimpleData( toRead, sizeof( toRead ) ); HeapData readData1; @@ -286,21 +284,21 @@ class FileTestSuite : public CxxTest::TestSuite TS_ASSERT_EQUALS( readData1.size(), 5U ); TS_ASSERT_SAME_DATA( readData1.data(), toRead, 5 ); - mock->nextReadData = ConstSimpleData( toRead, sizeof(toRead) ); + mock->nextReadData = ConstSimpleData( toRead, sizeof( toRead ) ); HeapData readData2; - file.read( readData2, sizeof(toRead) ); - TS_ASSERT_EQUALS( readData2.size(), sizeof(toRead) ); - TS_ASSERT_SAME_DATA( readData2.data(), toRead, sizeof(toRead) ); + file.read( readData2, sizeof( toRead ) ); + TS_ASSERT_EQUALS( readData2.size(), sizeof( toRead ) ); + TS_ASSERT_SAME_DATA( readData2.data(), toRead, sizeof( toRead ) ); - mock->nextReadData = ConstSimpleData( toRead, sizeof(toRead) ); + mock->nextReadData = ConstSimpleData( toRead, sizeof( toRead ) ); HeapData readData3; - file.read( readData3, sizeof(toRead) + 17 ); - TS_ASSERT_EQUALS( readData3.size(), sizeof(toRead) ); - TS_ASSERT_SAME_DATA( readData3.data(), toRead, sizeof(toRead) ); + file.read( readData3, sizeof( toRead ) + 17 ); + TS_ASSERT_EQUALS( readData3.size(), sizeof( toRead ) ); + TS_ASSERT_SAME_DATA( readData3.data(), toRead, sizeof( toRead ) ); mock->writeShouldFail = true; } @@ -364,10 +362,8 @@ class FileTestSuite : public CxxTest::TestSuite expectedLine = "Kittens, cats, sacks and wives, how many were going to St Ives?"; TS_ASSERT_EQUALS( line, expectedLine ); - TS_ASSERT_THROWS_EQUALS( file.readLine(), - const CommonError &e, - e.getCode(), - CommonError::READ_FAILED ); + TS_ASSERT_THROWS_EQUALS( + file.readLine(), const CommonError &e, e.getCode(), CommonError::READ_FAILED ); } void xtest_size() @@ -401,7 +397,7 @@ class FileTestSuite : public CxxTest::TestSuite void xtest_folder() { - memset( &mock->nextFileMode, 0, sizeof(mode_t) ); + memset( &mock->nextFileMode, 0, sizeof( mode_t ) ); mock->statShouldFail = false; diff --git a/src/common/tests/Test_FloatUtils.h b/src/common/tests/Test_FloatUtils.h index 1136d9c1ea..2153d8b938 100644 --- a/src/common/tests/Test_FloatUtils.h +++ b/src/common/tests/Test_FloatUtils.h @@ -14,9 +14,9 @@ ** [[ Add lengthier description here ]] **/ -#include - #include "FloatUtils.h" + +#include #include #ifdef _WIN32 diff --git a/src/common/tests/Test_GurobiWrapper.h b/src/common/tests/Test_GurobiWrapper.h index 52aa309487..905368e54f 100644 --- a/src/common/tests/Test_GurobiWrapper.h +++ b/src/common/tests/Test_GurobiWrapper.h @@ -14,13 +14,13 @@ ** [[ Add lengthier description here ]] **/ -#include - #include "FloatUtils.h" #include "GurobiWrapper.h" #include "MString.h" #include "MockErrno.h" +#include + class GurobiWrapperTestSuite : public CxxTest::TestSuite { public: diff --git a/src/common/tests/Test_HashMap.h b/src/common/tests/Test_HashMap.h index f3a283b633..d167c34a3d 100644 --- a/src/common/tests/Test_HashMap.h +++ b/src/common/tests/Test_HashMap.h @@ -14,13 +14,12 @@ ** [[ Add lengthier description here ]] **/ -#include - - #include "HashMap.h" #include "MString.h" #include "Map.h" #include "MockErrno.h" + +#include class HashMapTestSuite : public CxxTest::TestSuite { public: diff --git a/src/common/tests/Test_HashSet.h b/src/common/tests/Test_HashSet.h index 4ba0e60852..54e9e906af 100644 --- a/src/common/tests/Test_HashSet.h +++ b/src/common/tests/Test_HashSet.h @@ -14,13 +14,12 @@ ** [[ Add lengthier description here ]] **/ -#include - -#include "MockErrno.h" #include "HashSet.h" +#include "MockErrno.h" + +#include -class MockForHashSet : - public MockErrno +class MockForHashSet : public MockErrno { public: }; @@ -42,7 +41,7 @@ class HashSetTestSuite : public CxxTest::TestSuite void test_initializer_list() { - HashSet hashSet { 1, 2, 3 }; + HashSet hashSet{ 1, 2, 3 }; TS_ASSERT_EQUALS( hashSet.size(), 3U ); diff --git a/src/common/tests/Test_HeapData.h b/src/common/tests/Test_HeapData.h index ac7f16f5f5..878478f9ad 100644 --- a/src/common/tests/Test_HeapData.h +++ b/src/common/tests/Test_HeapData.h @@ -14,61 +14,61 @@ ** [[ Add lengthier description here ]] **/ -#include - #include "CommonError.h" #include "ConstSimpleData.h" #include "HeapData.h" #include "MockErrno.h" #include "RealMalloc.h" #include "T/stdlib.h" + +#include #include -class MockForHeapData : - public T::Base_malloc, - public T::Base_free, - public T::Base_realloc, - public MockErrno +class MockForHeapData + : public T::Base_malloc + , public T::Base_free + , public T::Base_realloc + , public MockErrno { public: - enum { - MAX_BUFFER_SIZE = 2048, - }; + enum { + MAX_BUFFER_SIZE = 2048, + }; - MockForHeapData() - { - allocated = false; - memset( buffer, 0, sizeof(buffer) ); - mallocShouldFail = false; - } + MockForHeapData() + { + allocated = false; + memset( buffer, 0, sizeof( buffer ) ); + mallocShouldFail = false; + } - char buffer[MAX_BUFFER_SIZE]; - bool allocated; - size_t lastMallocSize; - bool mallocShouldFail; + char buffer[MAX_BUFFER_SIZE]; + bool allocated; + size_t lastMallocSize; + bool mallocShouldFail; - void *malloc( size_t size ) - { - TS_ASSERT( !allocated ); - allocated = true; + void *malloc( size_t size ) + { + TS_ASSERT( !allocated ); + allocated = true; - lastMallocSize = size; + lastMallocSize = size; - if ( mallocShouldFail ) - return 0; + if ( mallocShouldFail ) + return 0; - return buffer; - } + return buffer; + } - void free( void *ptr ) - { - TS_ASSERT( allocated ); - allocated = false; + void free( void *ptr ) + { + TS_ASSERT( allocated ); + allocated = false; - TS_ASSERT_EQUALS( ptr, buffer ); + TS_ASSERT_EQUALS( ptr, buffer ); - memset( buffer, 0, sizeof(buffer) ); - } + memset( buffer, 0, sizeof( buffer ) ); + } void *realloc( void *ptr, size_t size ) { @@ -90,95 +90,95 @@ class MockForHeapData : class HeapDataTestSuite : public CxxTest::TestSuite { public: - MockForHeapData *mock; + MockForHeapData *mock; - void setUp() - { - TS_ASSERT( mock = new MockForHeapData ); - } + void setUp() + { + TS_ASSERT( mock = new MockForHeapData ); + } - void tearDown() - { - TS_ASSERT_THROWS_NOTHING( delete mock ); - } + void tearDown() + { + TS_ASSERT_THROWS_NOTHING( delete mock ); + } - void test_empty_data() - { - HeapData data; + void test_empty_data() + { + HeapData data; - TS_ASSERT_EQUALS( data.data(), (void *)0 ); - TS_ASSERT_EQUALS( data.size(), 0U ); - } + TS_ASSERT_EQUALS( data.data(), (void *)0 ); + TS_ASSERT_EQUALS( data.size(), 0U ); + } - void test_constructor() - { - char buffer[] = { 1, 2, 3, 4, 5 }; - char copyOfBuffer[sizeof(buffer)]; - memcpy( copyOfBuffer, buffer, sizeof(buffer) ); + void test_constructor() + { + char buffer[] = { 1, 2, 3, 4, 5 }; + char copyOfBuffer[sizeof( buffer )]; + memcpy( copyOfBuffer, buffer, sizeof( buffer ) ); - HeapData *data = NULL; + HeapData *data = NULL; - TS_ASSERT( data = new HeapData( buffer, sizeof(buffer) ) ); + TS_ASSERT( data = new HeapData( buffer, sizeof( buffer ) ) ); - TS_ASSERT( mock->allocated ); - TS_ASSERT_EQUALS( mock->lastMallocSize, sizeof(buffer) ); + TS_ASSERT( mock->allocated ); + TS_ASSERT_EQUALS( mock->lastMallocSize, sizeof( buffer ) ); - TS_ASSERT_EQUALS( data->size(), sizeof(buffer) ); - TS_ASSERT_DIFFERS( data->data(), buffer ); - TS_ASSERT_SAME_DATA( data->data(), buffer, sizeof(buffer) ); + TS_ASSERT_EQUALS( data->size(), sizeof( buffer ) ); + TS_ASSERT_DIFFERS( data->data(), buffer ); + TS_ASSERT_SAME_DATA( data->data(), buffer, sizeof( buffer ) ); - buffer[1]++; + buffer[1]++; - TS_ASSERT_EQUALS( data->size(), sizeof(buffer) ); - TS_ASSERT_SAME_DATA( data->data(), copyOfBuffer, sizeof(copyOfBuffer) ); + TS_ASSERT_EQUALS( data->size(), sizeof( buffer ) ); + TS_ASSERT_SAME_DATA( data->data(), copyOfBuffer, sizeof( copyOfBuffer ) ); - TS_ASSERT_THROWS_NOTHING( delete data ); + TS_ASSERT_THROWS_NOTHING( delete data ); - TS_ASSERT( !mock->allocated ); - } + TS_ASSERT( !mock->allocated ); + } - void test_constructor__new_fails() - { - mock->mallocShouldFail = true; + void test_constructor__new_fails() + { + mock->mallocShouldFail = true; - char buffer[] = { 1, 2, 3, 4, 5 }; + char buffer[] = { 1, 2, 3, 4, 5 }; - TS_ASSERT_THROWS_EQUALS( new HeapData( buffer, sizeof(buffer) ), - const CommonError &e, - e.getCode(), - CommonError::NOT_ENOUGH_MEMORY ); - } + TS_ASSERT_THROWS_EQUALS( new HeapData( buffer, sizeof( buffer ) ), + const CommonError &e, + e.getCode(), + CommonError::NOT_ENOUGH_MEMORY ); + } - void test_assignment_from_const_simple_data() - { - char buffer[] = { 1, 2, 3 }; + void test_assignment_from_const_simple_data() + { + char buffer[] = { 1, 2, 3 }; - HeapData heapData; - heapData = ConstSimpleData( buffer, sizeof(buffer) ); + HeapData heapData; + heapData = ConstSimpleData( buffer, sizeof( buffer ) ); - TS_ASSERT_EQUALS( mock->lastMallocSize, sizeof(buffer) ); - TS_ASSERT_EQUALS( heapData.size(), sizeof(buffer) ); - TS_ASSERT_SAME_DATA( heapData.data(), buffer, sizeof(buffer) ); + TS_ASSERT_EQUALS( mock->lastMallocSize, sizeof( buffer ) ); + TS_ASSERT_EQUALS( heapData.size(), sizeof( buffer ) ); + TS_ASSERT_SAME_DATA( heapData.data(), buffer, sizeof( buffer ) ); - char otherBuffer[] = { 'a', 'b', 'c', 'd', 'e' }; + char otherBuffer[] = { 'a', 'b', 'c', 'd', 'e' }; - heapData = ConstSimpleData( otherBuffer, sizeof(otherBuffer) ); + heapData = ConstSimpleData( otherBuffer, sizeof( otherBuffer ) ); - TS_ASSERT_EQUALS( heapData.size(), sizeof(otherBuffer) ); - TS_ASSERT_SAME_DATA( heapData.data(), otherBuffer, sizeof(otherBuffer) ); + TS_ASSERT_EQUALS( heapData.size(), sizeof( otherBuffer ) ); + TS_ASSERT_SAME_DATA( heapData.data(), otherBuffer, sizeof( otherBuffer ) ); - TS_ASSERT_EQUALS( mock->lastMallocSize, sizeof(otherBuffer) ); - } + TS_ASSERT_EQUALS( mock->lastMallocSize, sizeof( otherBuffer ) ); + } - void test_assignment_from_other_heap_data() - { - char buffer[] = { 1, 2, 3 }; + void test_assignment_from_other_heap_data() + { + char buffer[] = { 1, 2, 3 }; HeapData *other = NULL; { RealMalloc realMalloc; - other = new HeapData( buffer, sizeof(buffer) ); + other = new HeapData( buffer, sizeof( buffer ) ); } HeapData heapData; @@ -189,20 +189,20 @@ class HeapDataTestSuite : public CxxTest::TestSuite delete other; } - TS_ASSERT_EQUALS( mock->lastMallocSize, sizeof(buffer) ); - TS_ASSERT_EQUALS( heapData.size(), sizeof(buffer) ); - TS_ASSERT_SAME_DATA( heapData.data(), buffer, sizeof(buffer) ); - } + TS_ASSERT_EQUALS( mock->lastMallocSize, sizeof( buffer ) ); + TS_ASSERT_EQUALS( heapData.size(), sizeof( buffer ) ); + TS_ASSERT_SAME_DATA( heapData.data(), buffer, sizeof( buffer ) ); + } - void test_constructor_from_other_heap_data() - { - char buffer[] = { 1, 2, 3 }; + void test_constructor_from_other_heap_data() + { + char buffer[] = { 1, 2, 3 }; HeapData *other = NULL; { RealMalloc realMalloc; - other = new HeapData( buffer, sizeof(buffer) ); + other = new HeapData( buffer, sizeof( buffer ) ); } HeapData heapData( *other ); @@ -212,37 +212,37 @@ class HeapDataTestSuite : public CxxTest::TestSuite delete other; } - TS_ASSERT_EQUALS( mock->lastMallocSize, sizeof(buffer) ); - TS_ASSERT_EQUALS( heapData.size(), sizeof(buffer) ); - TS_ASSERT_SAME_DATA( heapData.data(), buffer, sizeof(buffer) ); + TS_ASSERT_EQUALS( mock->lastMallocSize, sizeof( buffer ) ); + TS_ASSERT_EQUALS( heapData.size(), sizeof( buffer ) ); + TS_ASSERT_SAME_DATA( heapData.data(), buffer, sizeof( buffer ) ); } - void test_concatenation() - { - char buffer1[] = { 1, 2, 3 }; + void test_concatenation() + { + char buffer1[] = { 1, 2, 3 }; char buffer2[] = { 'a', 'b', 'c' }; HeapData heapData; - heapData = ConstSimpleData( buffer1, sizeof(buffer1) ); + heapData = ConstSimpleData( buffer1, sizeof( buffer1 ) ); - TS_ASSERT_EQUALS( mock->lastMallocSize, sizeof(buffer1) ); - TS_ASSERT_EQUALS( heapData.size(), sizeof(buffer1) ); - TS_ASSERT_SAME_DATA( heapData.data(), buffer1, sizeof(buffer1) ); + TS_ASSERT_EQUALS( mock->lastMallocSize, sizeof( buffer1 ) ); + TS_ASSERT_EQUALS( heapData.size(), sizeof( buffer1 ) ); + TS_ASSERT_SAME_DATA( heapData.data(), buffer1, sizeof( buffer1 ) ); - TS_ASSERT_THROWS_NOTHING( heapData += ConstSimpleData( buffer2, sizeof(buffer2) ) ); + TS_ASSERT_THROWS_NOTHING( heapData += ConstSimpleData( buffer2, sizeof( buffer2 ) ) ); - char expectedData[] = { 1, 2, 3, 'a', 'b', 'c' }; + char expectedData[] = { 1, 2, 3, 'a', 'b', 'c' }; - TS_ASSERT_EQUALS( heapData.size(), sizeof(expectedData) ); - TS_ASSERT_SAME_DATA( heapData.data(), expectedData, sizeof(expectedData) ); + TS_ASSERT_EQUALS( heapData.size(), sizeof( expectedData ) ); + TS_ASSERT_SAME_DATA( heapData.data(), expectedData, sizeof( expectedData ) ); - TS_ASSERT_EQUALS( mock->lastMallocSize, sizeof(expectedData) ); + TS_ASSERT_EQUALS( mock->lastMallocSize, sizeof( expectedData ) ); HeapData *otherHeapData = NULL; { RealMalloc realMalloc; - otherHeapData = new HeapData( buffer2, sizeof(buffer2) ); + otherHeapData = new HeapData( buffer2, sizeof( buffer2 ) ); } TS_ASSERT_THROWS_NOTHING( heapData += *otherHeapData ); @@ -252,33 +252,33 @@ class HeapDataTestSuite : public CxxTest::TestSuite delete otherHeapData; } - memset( buffer2, 0, sizeof(buffer2) ); + memset( buffer2, 0, sizeof( buffer2 ) ); char expectedData2[] = { 1, 2, 3, 'a', 'b', 'c', 'a', 'b', 'c' }; - TS_ASSERT_EQUALS( heapData.size(), sizeof(expectedData2) ); - TS_ASSERT_SAME_DATA( heapData.data(), expectedData2, sizeof(expectedData2) ); + TS_ASSERT_EQUALS( heapData.size(), sizeof( expectedData2 ) ); + TS_ASSERT_SAME_DATA( heapData.data(), expectedData2, sizeof( expectedData2 ) ); - TS_ASSERT_EQUALS( mock->lastMallocSize, sizeof(expectedData2) ); - } + TS_ASSERT_EQUALS( mock->lastMallocSize, sizeof( expectedData2 ) ); + } void test_constructor_from_const_simple_data() { char data[] = { 0x01, 0x02, 0x03 }; - ConstSimpleData constData( data, sizeof(data) ); + ConstSimpleData constData( data, sizeof( data ) ); HeapData *heapData = NULL; TS_ASSERT( heapData = new HeapData( constData ) ); - TS_ASSERT_EQUALS( heapData->size(), sizeof(data) ); - TS_ASSERT_SAME_DATA( heapData->data(), data, sizeof(data) ); + TS_ASSERT_EQUALS( heapData->size(), sizeof( data ) ); + TS_ASSERT_SAME_DATA( heapData->data(), data, sizeof( data ) ); - char copyOfData[sizeof(data)]; - memcpy( copyOfData, data, sizeof(data) ); + char copyOfData[sizeof( data )]; + memcpy( copyOfData, data, sizeof( data ) ); data[0]++; - TS_ASSERT_SAME_DATA( heapData->data(), copyOfData, sizeof(copyOfData) ); + TS_ASSERT_SAME_DATA( heapData->data(), copyOfData, sizeof( copyOfData ) ); TS_ASSERT_THROWS_NOTHING( delete heapData ); } @@ -290,7 +290,7 @@ class HeapDataTestSuite : public CxxTest::TestSuite { RealMalloc realMalloc; - other = new HeapData( data, sizeof(data) ); + other = new HeapData( data, sizeof( data ) ); } HeapData *heapData = NULL; @@ -302,31 +302,31 @@ class HeapDataTestSuite : public CxxTest::TestSuite delete other; } - TS_ASSERT_EQUALS( heapData->size(), sizeof(data) ); - TS_ASSERT_SAME_DATA( heapData->data(), data, sizeof(data) ); + TS_ASSERT_EQUALS( heapData->size(), sizeof( data ) ); + TS_ASSERT_SAME_DATA( heapData->data(), data, sizeof( data ) ); - char copyOfData[sizeof(data)]; - memcpy( copyOfData, data, sizeof(data) ); + char copyOfData[sizeof( data )]; + memcpy( copyOfData, data, sizeof( data ) ); data[0]++; - TS_ASSERT_SAME_DATA( heapData->data(), copyOfData, sizeof(copyOfData) ); + TS_ASSERT_SAME_DATA( heapData->data(), copyOfData, sizeof( copyOfData ) ); TS_ASSERT_THROWS_NOTHING( delete heapData ); } void test_clear() - { - char buffer[] = { 1, 2, 3, 4, 5 }; - char copyOfBuffer[sizeof(buffer)]; - memcpy( copyOfBuffer, buffer, sizeof(buffer) ); + { + char buffer[] = { 1, 2, 3, 4, 5 }; + char copyOfBuffer[sizeof( buffer )]; + memcpy( copyOfBuffer, buffer, sizeof( buffer ) ); - HeapData *data = NULL; + HeapData *data = NULL; - TS_ASSERT( data = new HeapData( buffer, sizeof(buffer) ) ); + TS_ASSERT( data = new HeapData( buffer, sizeof( buffer ) ) ); - TS_ASSERT_EQUALS( data->size(), sizeof(buffer) ); - TS_ASSERT_DIFFERS( data->data(), buffer ); - TS_ASSERT_SAME_DATA( data->data(), buffer, sizeof(buffer) ); + TS_ASSERT_EQUALS( data->size(), sizeof( buffer ) ); + TS_ASSERT_DIFFERS( data->data(), buffer ); + TS_ASSERT_SAME_DATA( data->data(), buffer, sizeof( buffer ) ); data->clear(); @@ -335,13 +335,13 @@ class HeapDataTestSuite : public CxxTest::TestSuite buffer[1]++; - *data = ConstSimpleData( copyOfBuffer, sizeof(copyOfBuffer) ); + *data = ConstSimpleData( copyOfBuffer, sizeof( copyOfBuffer ) ); - TS_ASSERT_EQUALS( data->size(), sizeof(copyOfBuffer) ); - TS_ASSERT_SAME_DATA( data->data(), copyOfBuffer, sizeof(copyOfBuffer) ); + TS_ASSERT_EQUALS( data->size(), sizeof( copyOfBuffer ) ); + TS_ASSERT_SAME_DATA( data->data(), copyOfBuffer, sizeof( copyOfBuffer ) ); - TS_ASSERT_THROWS_NOTHING( delete data ); - } + TS_ASSERT_THROWS_NOTHING( delete data ); + } void test_equality() { @@ -353,10 +353,10 @@ class HeapDataTestSuite : public CxxTest::TestSuite { RealMalloc realMalloc; - HeapData heap1( data1, sizeof(data1) ); - HeapData heap2( data2, sizeof(data2) ); - HeapData heap3( data3, sizeof(data3) ); - HeapData heap4( data4, sizeof(data4) ); + HeapData heap1( data1, sizeof( data1 ) ); + HeapData heap2( data2, sizeof( data2 ) ); + HeapData heap3( data3, sizeof( data3 ) ); + HeapData heap4( data4, sizeof( data4 ) ); TS_ASSERT( heap1 == heap1 ); TS_ASSERT( heap1 == heap2 ); diff --git a/src/common/tests/Test_LinearExpression.h b/src/common/tests/Test_LinearExpression.h index fa7edaed1a..5d513441b5 100644 --- a/src/common/tests/Test_LinearExpression.h +++ b/src/common/tests/Test_LinearExpression.h @@ -14,14 +14,13 @@ ** [[ Add lengthier description here ]] **/ -#include - #include "LinearExpression.h" +#include + class LinearExpressionTestSuite : public CxxTest::TestSuite { public: - void setUp() { } @@ -44,6 +43,6 @@ class LinearExpressionTestSuite : public CxxTest::TestSuite assignment[1] = 3; assignment[2] = -2; - TS_ASSERT_EQUALS( expr.evaluate( assignment ), -9.5); + TS_ASSERT_EQUALS( expr.evaluate( assignment ), -9.5 ); } }; diff --git a/src/common/tests/Test_List.h b/src/common/tests/Test_List.h index ac35e9c282..a71bf2dc61 100644 --- a/src/common/tests/Test_List.h +++ b/src/common/tests/Test_List.h @@ -14,12 +14,12 @@ ** [[ Add lengthier description here ]] **/ -#include - #include "List.h" #include "MString.h" #include "MockErrno.h" +#include + class ListTestSuite : public CxxTest::TestSuite { public: @@ -198,7 +198,7 @@ class ListTestSuite : public CxxTest::TestSuite void test_initializer_list() { - List a { 1, 2, 3 }; + List a{ 1, 2, 3 }; TS_ASSERT_EQUALS( a.size(), 3U ); @@ -230,7 +230,7 @@ class ListTestSuite : public CxxTest::TestSuite TS_ASSERT_EQUALS( a.size(), 6U ); - TS_ASSERT_EQUALS( a, List ( { 1, 2, 3, 4, 5, 6 } ) ); + TS_ASSERT_EQUALS( a, List( { 1, 2, 3, 4, 5, 6 } ) ); } void test_reverse_iterator() @@ -284,10 +284,8 @@ class ListTestSuite : public CxxTest::TestSuite a.popBack(); TS_ASSERT( a.empty() ); - TS_ASSERT_THROWS_EQUALS( a.popBack(), - const CommonError &e, - e.getCode(), - CommonError::LIST_IS_EMPTY ); + TS_ASSERT_THROWS_EQUALS( + a.popBack(), const CommonError &e, e.getCode(), CommonError::LIST_IS_EMPTY ); } void test_remove_if() @@ -299,7 +297,7 @@ class ListTestSuite : public CxxTest::TestSuite a.append( 1 ); a.append( -2 ); - a.removeIf( [] ( int number ) { return number < 0; } ); + a.removeIf( []( int number ) { return number < 0; } ); auto it = a.begin(); TS_ASSERT_EQUALS( *it, 0 ); diff --git a/src/common/tests/Test_MString.h b/src/common/tests/Test_MString.h index 907cc6ff96..2cceaa2569 100644 --- a/src/common/tests/Test_MString.h +++ b/src/common/tests/Test_MString.h @@ -14,65 +14,65 @@ ** [[ Add lengthier description here ]] **/ -#include - #include "MString.h" -//template class List; +#include + +// template class List; class StringTestSuite : public CxxTest::TestSuite { public: - void test_ascii() - { - char data[] = { "hello world" }; + void test_ascii() + { + char data[] = { "hello world" }; - String string( data ); + String string( data ); - TS_ASSERT_EQUALS( strlen( data ), strlen( string.ascii() ) ); - TS_ASSERT_SAME_DATA( data, string.ascii(), strlen( data ) ); - } + TS_ASSERT_EQUALS( strlen( data ), strlen( string.ascii() ) ); + TS_ASSERT_SAME_DATA( data, string.ascii(), strlen( data ) ); + } - void test_bracket_operator() - { - String myString( "red apple" ); + void test_bracket_operator() + { + String myString( "red apple" ); - TS_ASSERT_EQUALS( myString[0], 'r' ); - TS_ASSERT_EQUALS( myString[3], ' ' ); - TS_ASSERT_EQUALS( myString[8], 'e' ); - } + TS_ASSERT_EQUALS( myString[0], 'r' ); + TS_ASSERT_EQUALS( myString[3], ' ' ); + TS_ASSERT_EQUALS( myString[8], 'e' ); + } - void test_empty_constructor() - { - String string; + void test_empty_constructor() + { + String string; - TS_ASSERT_EQUALS( string.length(), 0U ); - } + TS_ASSERT_EQUALS( string.length(), 0U ); + } - void test_assignemnt_from_c_str() - { - String myString; + void test_assignemnt_from_c_str() + { + String myString; - TS_ASSERT_EQUALS( myString.length(), 0U ); + TS_ASSERT_EQUALS( myString.length(), 0U ); - myString = "apple"; + myString = "apple"; - TS_ASSERT_EQUALS( myString.length(), strlen( "apple" ) ); - TS_ASSERT_SAME_DATA( myString.ascii(), "apple", myString.length() ); - } + TS_ASSERT_EQUALS( myString.length(), strlen( "apple" ) ); + TS_ASSERT_SAME_DATA( myString.ascii(), "apple", myString.length() ); + } - void test_equality_operator() - { - String string( "apple" ); - String otherString( "apple" ); - String different( "banana" ); + void test_equality_operator() + { + String string( "apple" ); + String otherString( "apple" ); + String different( "banana" ); - TS_ASSERT( string == otherString ); - TS_ASSERT( !( string == different ) ); - TS_ASSERT( string != different ); + TS_ASSERT( string == otherString ); + TS_ASSERT( !( string == different ) ); + TS_ASSERT( string != different ); - TS_ASSERT_EQUALS( string, "apple" ); - TS_ASSERT_DIFFERS( string, "banana" ); + TS_ASSERT_EQUALS( string, "apple" ); + TS_ASSERT_DIFFERS( string, "banana" ); String otherApple( "apple" ); @@ -247,16 +247,16 @@ class StringTestSuite : public CxxTest::TestSuite void test_trim() { - TS_ASSERT_EQUALS( String( " hello world \n" ).trim() , "hello world" ); - TS_ASSERT_EQUALS( String( " \n" ).trim() , "" ); - TS_ASSERT_EQUALS( String( " a" ).trim() , "a" ); - TS_ASSERT_EQUALS( String( " ab\n" ).trim() , "ab" ); - TS_ASSERT_EQUALS( String( "ab\n \n" ).trim() , "ab" ); - TS_ASSERT_EQUALS( String( "hey there \n" ).trim() , "hey there" ); - TS_ASSERT_EQUALS( String( "ab \r" ).trim() , "ab" ); - TS_ASSERT_EQUALS( String( " ab\r \r" ).trim() , "ab" ); - TS_ASSERT_EQUALS( String( "ab \r\n" ).trim() , "ab" ); - TS_ASSERT_EQUALS( String( " ab \r \r\n" ).trim() , "ab" ); + TS_ASSERT_EQUALS( String( " hello world \n" ).trim(), "hello world" ); + TS_ASSERT_EQUALS( String( " \n" ).trim(), "" ); + TS_ASSERT_EQUALS( String( " a" ).trim(), "a" ); + TS_ASSERT_EQUALS( String( " ab\n" ).trim(), "ab" ); + TS_ASSERT_EQUALS( String( "ab\n \n" ).trim(), "ab" ); + TS_ASSERT_EQUALS( String( "hey there \n" ).trim(), "hey there" ); + TS_ASSERT_EQUALS( String( "ab \r" ).trim(), "ab" ); + TS_ASSERT_EQUALS( String( " ab\r \r" ).trim(), "ab" ); + TS_ASSERT_EQUALS( String( "ab \r\n" ).trim(), "ab" ); + TS_ASSERT_EQUALS( String( " ab \r \r\n" ).trim(), "ab" ); } }; diff --git a/src/common/tests/Test_MStringf.h b/src/common/tests/Test_MStringf.h index 23abf0564a..616425865e 100644 --- a/src/common/tests/Test_MStringf.h +++ b/src/common/tests/Test_MStringf.h @@ -14,15 +14,15 @@ ** [[ Add lengthier description here ]] **/ -#include - #include "MStringf.h" +#include + class StringfTestSuite : public CxxTest::TestSuite { public: - void test_constructor() - { + void test_constructor() + { Stringf stringf( "Hello %s %u world", "bla", 5 ); String expected( "Hello bla 5 world" ); diff --git a/src/common/tests/Test_Map.h b/src/common/tests/Test_Map.h index 2ae75d3a4d..9784c38a56 100644 --- a/src/common/tests/Test_Map.h +++ b/src/common/tests/Test_Map.h @@ -14,12 +14,12 @@ ** [[ Add lengthier description here ]] **/ -#include - #include "MString.h" #include "Map.h" #include "MockErrno.h" +#include + class MapTestSuite : public CxxTest::TestSuite { public: @@ -198,10 +198,8 @@ class MapTestSuite : public CxxTest::TestSuite TS_ASSERT_EQUALS( map.get( 2 ), "Red" ); TS_ASSERT_EQUALS( map.get( 3 ), "Tasty" ); - TS_ASSERT_THROWS_EQUALS( map.at( 4 ), - const CommonError &e, - e.getCode(), - CommonError::KEY_DOESNT_EXIST_IN_MAP ); + TS_ASSERT_THROWS_EQUALS( + map.at( 4 ), const CommonError &e, e.getCode(), CommonError::KEY_DOESNT_EXIST_IN_MAP ); } void test_equality() @@ -275,10 +273,8 @@ class MapTestSuite : public CxxTest::TestSuite TS_ASSERT_EQUALS( map.at( 3 ), "fox" ); - TS_ASSERT_THROWS_EQUALS( map.at( 4 ), - const CommonError &e, - e.getCode(), - CommonError::KEY_DOESNT_EXIST_IN_MAP ); + TS_ASSERT_THROWS_EQUALS( + map.at( 4 ), const CommonError &e, e.getCode(), CommonError::KEY_DOESNT_EXIST_IN_MAP ); } void test_rbegin_and_rend() @@ -320,13 +316,13 @@ class MapTestSuite : public CxxTest::TestSuite TS_ASSERT_EQUALS( flipped.size(), 3U ); TS_ASSERT_EQUALS( flipped["cat"].size(), 1U ); - TS_ASSERT_EQUALS( *(flipped["cat"].begin()), 1 ); + TS_ASSERT_EQUALS( *( flipped["cat"].begin() ), 1 ); TS_ASSERT_EQUALS( flipped["dog"].size(), 1U ); - TS_ASSERT_EQUALS( *(flipped["dog"].begin()), 2 ); + TS_ASSERT_EQUALS( *( flipped["dog"].begin() ), 2 ); TS_ASSERT_EQUALS( flipped["bear"].size(), 1U ); - TS_ASSERT_EQUALS( *(flipped["bear"].begin()), 3 ); + TS_ASSERT_EQUALS( *( flipped["bear"].begin() ), 3 ); map[4] = "dog"; @@ -335,14 +331,14 @@ class MapTestSuite : public CxxTest::TestSuite TS_ASSERT_EQUALS( flipped.size(), 3U ); TS_ASSERT_EQUALS( flipped["cat"].size(), 1U ); - TS_ASSERT_EQUALS( *(flipped["cat"].begin()), 1 ); + TS_ASSERT_EQUALS( *( flipped["cat"].begin() ), 1 ); TS_ASSERT_EQUALS( flipped["dog"].size(), 2U ); - TS_ASSERT_EQUALS( *(flipped["dog"].begin()), 2 ); + TS_ASSERT_EQUALS( *( flipped["dog"].begin() ), 2 ); TS_ASSERT_EQUALS( flipped["dog"].back(), 4 ); TS_ASSERT_EQUALS( flipped["bear"].size(), 1U ); - TS_ASSERT_EQUALS( *(flipped["bear"].begin()), 3 ); + TS_ASSERT_EQUALS( *( flipped["bear"].begin() ), 3 ); } void test_key_with_largest_value() diff --git a/src/common/tests/Test_MatrixMultiplication.h b/src/common/tests/Test_MatrixMultiplication.h index d36419d2ca..6eda0af712 100644 --- a/src/common/tests/Test_MatrixMultiplication.h +++ b/src/common/tests/Test_MatrixMultiplication.h @@ -14,46 +14,45 @@ ** [[ Add lengthier description here ]] **/ -#include - #include "MatrixMultiplication.h" +#include + class MatrixMultiplicationTestSuite : public CxxTest::TestSuite { public: - void test_vector_matrix() { - double matA[] = {1,2}; - double matB[] = {1,2,3,1}; - double matC[2] = {0}; + double matA[] = { 1, 2 }; + double matB[] = { 1, 2, 3, 1 }; + double matC[2] = { 0 }; unsigned rowsA = 1; unsigned columnsA = 2; unsigned columnsB = 2; - matrixMultiplication(matA, matB, matC, rowsA, columnsA, columnsB); + matrixMultiplication( matA, matB, matC, rowsA, columnsA, columnsB ); // matC[0] = 1*1+2*3 = 7 // matC[1] = 1*2+2*1 = 4 - TS_ASSERT(matC[0] == 7); - TS_ASSERT(matC[1] == 4); + TS_ASSERT( matC[0] == 7 ); + TS_ASSERT( matC[1] == 4 ); } void test_matrix_matrix() { - double matA[] = {1,2,3,4,5,6}; // [1,2], [3,4], [5,6] - double matB[] = {1,2,3,4}; // [1,2], [3,4] - double matC[6] = {0}; + double matA[] = { 1, 2, 3, 4, 5, 6 }; // [1,2], [3,4], [5,6] + double matB[] = { 1, 2, 3, 4 }; // [1,2], [3,4] + double matC[6] = { 0 }; unsigned rowsA = 3; unsigned columnsA = 2; unsigned columnsB = 2; - matrixMultiplication(matA, matB, matC, rowsA, columnsA, columnsB); + matrixMultiplication( matA, matB, matC, rowsA, columnsA, columnsB ); - TS_ASSERT(matC[0] == 7); - TS_ASSERT(matC[1] == 10); - TS_ASSERT(matC[2] == 15); - TS_ASSERT(matC[3] == 22); - TS_ASSERT(matC[4] == 23); - TS_ASSERT(matC[5] == 34); + TS_ASSERT( matC[0] == 7 ); + TS_ASSERT( matC[1] == 10 ); + TS_ASSERT( matC[2] == 15 ); + TS_ASSERT( matC[3] == 22 ); + TS_ASSERT( matC[4] == 23 ); + TS_ASSERT( matC[5] == 34 ); } }; diff --git a/src/common/tests/Test_Pair.h b/src/common/tests/Test_Pair.h index 0f09022b72..69555007fa 100644 --- a/src/common/tests/Test_Pair.h +++ b/src/common/tests/Test_Pair.h @@ -14,15 +14,14 @@ ** [[ Add lengthier description here ]] **/ -#include - #include "MString.h" #include "Pair.h" +#include + class PairTestSuite : public CxxTest::TestSuite { public: - void test_pair() { Pair p1; diff --git a/src/common/tests/Test_Queue.h b/src/common/tests/Test_Queue.h index a229a83b17..b83a9aa26e 100644 --- a/src/common/tests/Test_Queue.h +++ b/src/common/tests/Test_Queue.h @@ -14,12 +14,12 @@ ** [[ Add lengthier description here ]] **/ -#include - #include "MString.h" #include "MockErrno.h" #include "Queue.h" +#include + class QueueTestSuite : public CxxTest::TestSuite { public: @@ -74,15 +74,11 @@ class QueueTestSuite : public CxxTest::TestSuite TS_ASSERT( q.empty() ); - TS_ASSERT_THROWS_EQUALS( q.peak(), - const CommonError &e, - e.getCode(), - CommonError::QUEUE_IS_EMPTY ); + TS_ASSERT_THROWS_EQUALS( + q.peak(), const CommonError &e, e.getCode(), CommonError::QUEUE_IS_EMPTY ); - TS_ASSERT_THROWS_EQUALS( q.pop(), - const CommonError &e, - e.getCode(), - CommonError::QUEUE_IS_EMPTY ); + TS_ASSERT_THROWS_EQUALS( + q.pop(), const CommonError &e, e.getCode(), CommonError::QUEUE_IS_EMPTY ); } }; diff --git a/src/common/tests/Test_Set.h b/src/common/tests/Test_Set.h index 5e56a50d0a..9e5220b0dc 100644 --- a/src/common/tests/Test_Set.h +++ b/src/common/tests/Test_Set.h @@ -14,14 +14,14 @@ ** [[ Add lengthier description here ]] **/ -#include - #include "MockErrno.h" #include "Set.h" -class MockForSet : - public MockErrno, - public T::Base_rand +#include + +class MockForSet + : public MockErrno + , public T::Base_rand { public: MockForSet() @@ -56,7 +56,7 @@ class SetTestSuite : public CxxTest::TestSuite void test_initializer_list() { - Set set { 1, 2, 3 }; + Set set{ 1, 2, 3 }; TS_ASSERT_EQUALS( set.size(), 3U ); @@ -292,7 +292,7 @@ class SetTestSuite : public CxxTest::TestSuite TS_ASSERT( !Set::containedIn( a, b ) ); - b.insert( 1 ) ; + b.insert( 1 ); TS_ASSERT( Set::containedIn( a, b ) ); diff --git a/src/common/tests/Test_Stack.h b/src/common/tests/Test_Stack.h index 44ed0b2cc4..267f5b2e50 100644 --- a/src/common/tests/Test_Stack.h +++ b/src/common/tests/Test_Stack.h @@ -14,12 +14,12 @@ ** [[ Add lengthier description here ]] **/ -#include - #include "CommonError.h" #include "MockErrno.h" #include "Stack.h" +#include + class StackTestSuite : public CxxTest::TestSuite { public: @@ -74,15 +74,11 @@ class StackTestSuite : public CxxTest::TestSuite TS_ASSERT( q.empty() ); - TS_ASSERT_THROWS_EQUALS( q.top(), - const CommonError &e, - e.getCode(), - CommonError::STACK_IS_EMPTY ); + TS_ASSERT_THROWS_EQUALS( + q.top(), const CommonError &e, e.getCode(), CommonError::STACK_IS_EMPTY ); - TS_ASSERT_THROWS_EQUALS( q.pop(), - const CommonError &e, - e.getCode(), - CommonError::STACK_IS_EMPTY ); + TS_ASSERT_THROWS_EQUALS( + q.pop(), const CommonError &e, e.getCode(), CommonError::STACK_IS_EMPTY ); } }; diff --git a/src/common/tests/Test_Vector.h b/src/common/tests/Test_Vector.h index d1118106b6..8b28145edb 100644 --- a/src/common/tests/Test_Vector.h +++ b/src/common/tests/Test_Vector.h @@ -14,12 +14,12 @@ ** [[ Add lengthier description here ]] **/ -#include - #include "MString.h" #include "MockErrno.h" #include "Vector.h" +#include + class VectorTestSuite : public CxxTest::TestSuite { public: @@ -297,10 +297,8 @@ class VectorTestSuite : public CxxTest::TestSuite { Vector vector; - TS_ASSERT_THROWS_EQUALS( vector.first(), - const CommonError &e, - e.getCode(), - CommonError::VECTOR_OUT_OF_BOUNDS ); + TS_ASSERT_THROWS_EQUALS( + vector.first(), const CommonError &e, e.getCode(), CommonError::VECTOR_OUT_OF_BOUNDS ); vector.append( 1 ); TS_ASSERT_EQUALS( vector.first(), 1 ); @@ -319,10 +317,8 @@ class VectorTestSuite : public CxxTest::TestSuite { Vector vector; - TS_ASSERT_THROWS_EQUALS( vector.last(), - const CommonError &e, - e.getCode(), - CommonError::VECTOR_OUT_OF_BOUNDS ); + TS_ASSERT_THROWS_EQUALS( + vector.last(), const CommonError &e, e.getCode(), CommonError::VECTOR_OUT_OF_BOUNDS ); vector.append( 1 ); TS_ASSERT_EQUALS( vector.last(), 1 ); @@ -466,7 +462,7 @@ class VectorTestSuite : public CxxTest::TestSuite void test_assignemnt() { - Vector a,b; + Vector a, b; a.append( 1 ); a.append( 2 ); diff --git a/src/configuration/ConfigurationError.h b/src/configuration/ConfigurationError.h index ea4486f3d4..6cc7f0e055 100644 --- a/src/configuration/ConfigurationError.h +++ b/src/configuration/ConfigurationError.h @@ -21,16 +21,18 @@ class ConfigurationError : public Error { public: - enum Code { + enum Code { OPTION_KEY_DOESNT_EXIST = 0, INCOMPTATIBLE_OPTIONS = 1, }; - ConfigurationError( ConfigurationError::Code code ) : Error( "ConfigurationError", (int)code ) - { - } + ConfigurationError( ConfigurationError::Code code ) + : Error( "ConfigurationError", (int)code ) + { + } - ConfigurationError( ConfigurationError::Code code, const char *userMessage ) : Error( "ConfigurationError", (int)code, userMessage ) + ConfigurationError( ConfigurationError::Code code, const char *userMessage ) + : Error( "ConfigurationError", (int)code, userMessage ) { } }; diff --git a/src/configuration/GlobalConfiguration.cpp b/src/configuration/GlobalConfiguration.cpp index 706502f5a7..0fda5a937a 100644 --- a/src/configuration/GlobalConfiguration.cpp +++ b/src/configuration/GlobalConfiguration.cpp @@ -13,9 +13,11 @@ **/ -#include "DivideStrategy.h" #include "GlobalConfiguration.h" + +#include "DivideStrategy.h" #include "MString.h" + #include @@ -24,7 +26,7 @@ const double GlobalConfiguration::EXPONENTIAL_MOVING_AVERAGE_ALPHA = 0.5; // Whether to use SoI instead of Reluplex for local search for satisfying assignments -//to non-linear constraint. +// to non-linear constraint. bool GlobalConfiguration::USE_DEEPSOI_LOCAL_SEARCH = true; const double GlobalConfiguration::SCORE_BUMP_FOR_PL_CONSTRAINTS_NOT_IN_SOI = 5; @@ -43,9 +45,11 @@ const double GlobalConfiguration::PIVOT_CHANGE_COLUMN_TOLERANCE = 0.000000001; const double GlobalConfiguration::PIVOT_ROW_AND_COLUMN_TOLERANCE = 0.01; const double GlobalConfiguration::ENTRY_ELIGIBILITY_TOLERANCE = 0.00000001; const double GlobalConfiguration::RATIO_CONSTRAINT_ADDITIVE_TOLERANCE = 0.0000001 * 0.3; -const double GlobalConfiguration::RATIO_CONSTRAINT_MULTIPLICATIVE_TOLERANCE = 0.001 * 0.0000001 * 0.3; +const double GlobalConfiguration::RATIO_CONSTRAINT_MULTIPLICATIVE_TOLERANCE = + 0.001 * 0.0000001 * 0.3; const double GlobalConfiguration::HARRIS_RATIO_CONSTRAINT_ADDITIVE_TOLERANCE = 0.0000001 * 0.5; -const double GlobalConfiguration::HARRIS_RATIO_CONSTRAINT_MULTIPLICATIVE_TOLERANCE = 0.001 * 0.0000001 * 0.5; +const double GlobalConfiguration::HARRIS_RATIO_CONSTRAINT_MULTIPLICATIVE_TOLERANCE = + 0.001 * 0.0000001 * 0.5; const double GlobalConfiguration::BASIC_COSTS_ADDITIVE_TOLERANCE = 0.0000001; const double GlobalConfiguration::BASIC_COSTS_MULTIPLICATIVE_TOLERANCE = 0.001 * 0.0000001; const double GlobalConfiguration::SPARSE_FORREST_TOMLIN_DIAGONAL_ELEMENT_TOLERANCE = 0.00001; @@ -93,8 +97,9 @@ const double GlobalConfiguration::SOFTMAX_LSE2_THRESHOLD = 0.6; const bool GlobalConfiguration::ONLY_AUX_INITIAL_BASIS = false; -const GlobalConfiguration::ExplicitBasisBoundTighteningType GlobalConfiguration::EXPLICIT_BASIS_BOUND_TIGHTENING_TYPE = - GlobalConfiguration::COMPUTE_INVERTED_BASIS_MATRIX; +const GlobalConfiguration::ExplicitBasisBoundTighteningType + GlobalConfiguration::EXPLICIT_BASIS_BOUND_TIGHTENING_TYPE = + GlobalConfiguration::COMPUTE_INVERTED_BASIS_MATRIX; const bool GlobalConfiguration::EXPLICIT_BOUND_TIGHTENING_UNTIL_SATURATION = false; const double GlobalConfiguration::EXPLICIT_BASIS_BOUND_TIGHTENING_ROUNDING_CONSTANT = 1e-6; @@ -129,8 +134,8 @@ const bool GlobalConfiguration::GAUSSIAN_ELIMINATION_LOGGING = false; const bool GlobalConfiguration::QUERY_LOADER_LOGGING = false; const bool GlobalConfiguration::SYMBOLIC_BOUND_TIGHTENER_LOGGING = false; const bool GlobalConfiguration::NETWORK_LEVEL_REASONER_LOGGING = false; -const bool GlobalConfiguration::MPS_PARSER_LOGGING= false; -const bool GlobalConfiguration::ONNX_PARSER_LOGGING= false; +const bool GlobalConfiguration::MPS_PARSER_LOGGING = false; +const bool GlobalConfiguration::ONNX_PARSER_LOGGING = false; const bool GlobalConfiguration::SOI_LOGGING = false; const bool GlobalConfiguration::SCORE_TRACKER_LOGGING = false; @@ -145,18 +150,24 @@ void GlobalConfiguration::print() printf( " DEFAULT_EPSILON_FOR_COMPARISONS: %.15lf\n", DEFAULT_EPSILON_FOR_COMPARISONS ); printf( " DEFAULT_DOUBLE_TO_STRING_PRECISION: %u\n", DEFAULT_DOUBLE_TO_STRING_PRECISION ); printf( " STATISTICS_PRINTING_FREQUENCY: %u\n", STATISTICS_PRINTING_FREQUENCY ); - printf( " BOUND_COMPARISON_ADDITIVE_TOLERANCE: %.15lf\n", BOUND_COMPARISON_ADDITIVE_TOLERANCE ); - printf( " BOUND_COMPARISON_MULTIPLICATIVE_TOLERANCE: %.15lf\n", BOUND_COMPARISON_MULTIPLICATIVE_TOLERANCE ); + printf( " BOUND_COMPARISON_ADDITIVE_TOLERANCE: %.15lf\n", + BOUND_COMPARISON_ADDITIVE_TOLERANCE ); + printf( " BOUND_COMPARISON_MULTIPLICATIVE_TOLERANCE: %.15lf\n", + BOUND_COMPARISON_MULTIPLICATIVE_TOLERANCE ); printf( " PIVOT_CHANGE_COLUMN_TOLERANCE: %.15lf\n", PIVOT_CHANGE_COLUMN_TOLERANCE ); - printf( " RATIO_CONSTRAINT_ADDITIVE_TOLERANCE: %.15lf\n", RATIO_CONSTRAINT_ADDITIVE_TOLERANCE ); - printf( " RATIO_CONSTRAINT_MULTIPLICATIVE_TOLERANCE: %.15lf\n", RATIO_CONSTRAINT_MULTIPLICATIVE_TOLERANCE ); + printf( " RATIO_CONSTRAINT_ADDITIVE_TOLERANCE: %.15lf\n", + RATIO_CONSTRAINT_ADDITIVE_TOLERANCE ); + printf( " RATIO_CONSTRAINT_MULTIPLICATIVE_TOLERANCE: %.15lf\n", + RATIO_CONSTRAINT_MULTIPLICATIVE_TOLERANCE ); printf( " BASIC_COSTS_ADDITIVE_TOLERANCE: %.15lf\n", BASIC_COSTS_ADDITIVE_TOLERANCE ); - printf( " BASIC_COSTS_MULTIPLICATIVE_TOLERANCE: %.15lf\n", BASIC_COSTS_MULTIPLICATIVE_TOLERANCE ); + printf( " BASIC_COSTS_MULTIPLICATIVE_TOLERANCE: %.15lf\n", + BASIC_COSTS_MULTIPLICATIVE_TOLERANCE ); printf( " DEGRADATION_CHECKING_FREQUENCY: %u\n", DEGRADATION_CHECKING_FREQUENCY ); printf( " DEGRADATION_THRESHOLD: %.15lf\n", DEGRADATION_THRESHOLD ); printf( " ACCEPTABLE_SIMPLEX_PIVOT_THRESHOLD: %.15lf\n", ACCEPTABLE_SIMPLEX_PIVOT_THRESHOLD ); printf( " USE_COLUMN_MERGING_EQUATIONS: %s\n", USE_COLUMN_MERGING_EQUATIONS ? "Yes" : "No" ); - printf( " GAUSSIAN_ELIMINATION_PIVOT_SCALE_THRESHOLD: %.15lf\n", GAUSSIAN_ELIMINATION_PIVOT_SCALE_THRESHOLD ); + printf( " GAUSSIAN_ELIMINATION_PIVOT_SCALE_THRESHOLD: %.15lf\n", + GAUSSIAN_ELIMINATION_PIVOT_SCALE_THRESHOLD ); printf( " MAX_SIMPLEX_PIVOT_SEARCH_ITERATIONS: %u\n", MAX_SIMPLEX_PIVOT_SEARCH_ITERATIONS ); printf( " BOUND_TIGHTING_ON_CONSTRAINT_MATRIX_FREQUENCY: %u\n", BOUND_TIGHTING_ON_CONSTRAINT_MATRIX_FREQUENCY ); @@ -164,7 +175,8 @@ void GlobalConfiguration::print() printf( " USE_HARRIS_RATIO_TEST: %s\n", USE_HARRIS_RATIO_TEST ? "Yes" : "No" ); printf( " PREPROCESS_INPUT_QUERY: %s\n", PREPROCESS_INPUT_QUERY ? "Yes" : "No" ); - printf( " PREPROCESSOR_ELIMINATE_VARIABLES: %s\n", PREPROCESSOR_ELIMINATE_VARIABLES ? "Yes" : "No" ); + printf( " PREPROCESSOR_ELIMINATE_VARIABLES: %s\n", + PREPROCESSOR_ELIMINATE_VARIABLES ? "Yes" : "No" ); printf( " PSE_ITERATIONS_BEFORE_RESET: %u\n", PSE_ITERATIONS_BEFORE_RESET ); printf( " PSE_GAMMA_ERROR_THRESHOLD: %.15lf\n", PSE_GAMMA_ERROR_THRESHOLD ); printf( " CONSTRAINT_COMPARISON_TOLERANCE: %.15lf\n", CONSTRAINT_COMPARISON_TOLERANCE ); @@ -185,7 +197,8 @@ void GlobalConfiguration::print() break; } - printf( " EXPLICIT_BASIS_BOUND_TIGHTENING_INVERT_BASIS: %s\n", basisBoundTighteningType.ascii() ); + printf( " EXPLICIT_BASIS_BOUND_TIGHTENING_INVERT_BASIS: %s\n", + basisBoundTighteningType.ascii() ); printf( " EXPLICIT_BOUND_TIGHTENING_UNTIL_SATURATION: %s\n", EXPLICIT_BOUND_TIGHTENING_UNTIL_SATURATION ? "Yes" : "No" ); printf( " REFACTORIZATION_THRESHOLD: %u\n", REFACTORIZATION_THRESHOLD ); diff --git a/src/configuration/GlobalConfiguration.h b/src/configuration/GlobalConfiguration.h index 042061a5ff..fc96762ec7 100644 --- a/src/configuration/GlobalConfiguration.h +++ b/src/configuration/GlobalConfiguration.h @@ -28,7 +28,7 @@ class GlobalConfiguration static const double EXPONENTIAL_MOVING_AVERAGE_ALPHA; // Whether to use SoI instead of Reluplex for local search for satisfying assignments - //to non-linear constraint. + // to non-linear constraint. static bool USE_DEEPSOI_LOCAL_SEARCH; // The quantity by which the score is bumped up for PLContraints not @@ -119,12 +119,12 @@ class GlobalConfiguration // The threshold of degradation above which restoration is required static const double DEGRADATION_THRESHOLD; - // If a pivot element in a simplex iteration is smaller than this threshold, the engine will attempt - // to pick another element. + // If a pivot element in a simplex iteration is smaller than this threshold, the engine will + // attempt to pick another element. static const double ACCEPTABLE_SIMPLEX_PIVOT_THRESHOLD; - // If true, column-merging equations are given special treatment and cause columns in the tableau - // to be merged (instead of a new row added). + // If true, column-merging equations are given special treatment and cause columns in the + // tableau to be merged (instead of a new row added). static const bool USE_COLUMN_MERGING_EQUATIONS; // If a pivot element in a Gaussian elimination iteration is smaller than this threshold times @@ -159,7 +159,8 @@ class GlobalConfiguration // How often should projected steepest edge reset the reference space? static const unsigned PSE_ITERATIONS_BEFORE_RESET; - // An error threshold which, when crossed, causes projected steepest edge to reset the reference space + // An error threshold which, when crossed, causes projected steepest edge to reset the reference + // space static const double PSE_GAMMA_ERROR_THRESHOLD; // PSE's Gamma function's update tolerance @@ -187,7 +188,8 @@ class GlobalConfiguration DISABLE_EXPLICIT_BASIS_TIGHTENING = 2, }; - // When doing bound tightening using the explicit basis matrix, should the basis matrix be inverted? + // When doing bound tightening using the explicit basis matrix, should the basis matrix be + // inverted? static const ExplicitBasisBoundTighteningType EXPLICIT_BASIS_BOUND_TIGHTENING_TYPE; static const double EXPLICIT_BASIS_BOUND_TIGHTENING_ROUNDING_CONSTANT; @@ -211,8 +213,8 @@ class GlobalConfiguration // for any relevant linear connections between the variables? static const bool USE_SMART_FIX; - // A heuristic for selecting which of the broken PL constraints will be repaired next. In this case, - // the one that has been repaired the least number of times so far. + // A heuristic for selecting which of the broken PL constraints will be repaired next. In this + // case, the one that has been repaired the least number of times so far. static const bool USE_LEAST_FIX; /* @@ -237,19 +239,19 @@ class GlobalConfiguration static const unsigned POLARITY_CANDIDATES_THRESHOLD; /* The max number of DnC splits - */ + */ static const unsigned DNC_DEPTH_THRESHOLD; /* Minimal coefficient of a variable in a Tableau row, that is used for bound tightening - */ + */ static const double MINIMAL_COEFFICIENT_FOR_TIGHTENING; /* The tolerance of errors when checking lemmas in the proof-checking process - */ + */ static const double LEMMA_CERTIFICATION_TOLERANCE; /* Denote whether proofs should be written as a JSON file - */ + */ static const bool WRITE_JSON_PROOF; #ifdef ENABLE_GUROBI diff --git a/src/configuration/OptionParser.cpp b/src/configuration/OptionParser.cpp index 817ae90b51..1e0916b173 100644 --- a/src/configuration/OptionParser.cpp +++ b/src/configuration/OptionParser.cpp @@ -13,8 +13,9 @@ **/ -#include "Debug.h" #include "OptionParser.h" + +#include "Debug.h" #include "Options.h" OptionParser::OptionParser() @@ -40,151 +41,215 @@ OptionParser::OptionParser( Map *boolOptions, void OptionParser::initialize() { - _positional.add_options() - ( "input", - boost::program_options::value( &(*_stringOptions)[Options::INPUT_FILE_PATH] )->default_value( (*_stringOptions)[Options::INPUT_FILE_PATH] ), - "Neural network file." ) - ( "property", - boost::program_options::value( &(*_stringOptions)[Options::PROPERTY_FILE_PATH] )->default_value( (*_stringOptions)[Options::PROPERTY_FILE_PATH] ), - "Property file." ) - ; + _positional.add_options()( + "input", + boost::program_options::value( &( *_stringOptions )[Options::INPUT_FILE_PATH] ) + ->default_value( ( *_stringOptions )[Options::INPUT_FILE_PATH] ), + "Neural network file." )( + "property", + boost::program_options::value( + &( *_stringOptions )[Options::PROPERTY_FILE_PATH] ) + ->default_value( ( *_stringOptions )[Options::PROPERTY_FILE_PATH] ), + "Property file." ); // Most common options - _common.add_options() - ( "help", - boost::program_options::bool_switch( &(*_boolOptions)[Options::HELP] )->default_value( (*_boolOptions)[Options::HELP] ), - "Prints the help message.") - ( "version", - boost::program_options::bool_switch( &(*_boolOptions)[Options::VERSION] )->default_value( (*_boolOptions)[Options::VERSION] ), - "Prints the version number.") - ( "input-query", - boost::program_options::value( &((*_stringOptions)[Options::INPUT_QUERY_FILE_PATH]) )->default_value( (*_stringOptions)[Options::INPUT_QUERY_FILE_PATH] ), - "Input Query file. When specified, Marabou will solve this instead of the network and property pair." ) - ( "num-workers", - boost::program_options::value( &(*_intOptions)[Options::NUM_WORKERS] )->default_value( (*_intOptions)[Options::NUM_WORKERS] ), - "Number of threads to use." ) - ( "timeout", - boost::program_options::value( &(*_intOptions)[Options::TIMEOUT] )->default_value( (*_intOptions)[Options::TIMEOUT] ), - "Global timeout in seconds. 0 means no timeout." ) + _common.add_options()( "help", + boost::program_options::bool_switch( &( *_boolOptions )[Options::HELP] ) + ->default_value( ( *_boolOptions )[Options::HELP] ), + "Prints the help message." )( + "version", + boost::program_options::bool_switch( &( *_boolOptions )[Options::VERSION] ) + ->default_value( ( *_boolOptions )[Options::VERSION] ), + "Prints the version number." )( + "input-query", + boost::program_options::value( + &( ( *_stringOptions )[Options::INPUT_QUERY_FILE_PATH] ) ) + ->default_value( ( *_stringOptions )[Options::INPUT_QUERY_FILE_PATH] ), + "Input Query file. When specified, Marabou will solve this instead of the network and " + "property pair." )( + "num-workers", + boost::program_options::value( &( *_intOptions )[Options::NUM_WORKERS] ) + ->default_value( ( *_intOptions )[Options::NUM_WORKERS] ), + "Number of threads to use." )( + "timeout", + boost::program_options::value( &( *_intOptions )[Options::TIMEOUT] ) + ->default_value( ( *_intOptions )[Options::TIMEOUT] ), + "Global timeout in seconds. 0 means no timeout." ) #ifdef ENABLE_GUROBI ( "milp", - boost::program_options::bool_switch( &(*_boolOptions)[Options::SOLVE_WITH_MILP] )->default_value( (*_boolOptions)[Options::SOLVE_WITH_MILP] ), + boost::program_options::bool_switch( &( *_boolOptions )[Options::SOLVE_WITH_MILP] ) + ->default_value( ( *_boolOptions )[Options::SOLVE_WITH_MILP] ), "Solve the input query with a MILP encoding in Gruobi." ) #endif ; // Less common options - _other.add_options() - ( "verbosity", - boost::program_options::value( &((*_intOptions)[Options::VERBOSITY]) )->default_value( (*_intOptions)[Options::VERBOSITY] ), - "Verbosity of engine::solve(). 0: does not print anything, 1: print" - "out statistics in the beginning and end, 2: print out statistics during solving." ) - ( "snc", - boost::program_options::bool_switch( &((*_boolOptions)[Options::DNC_MODE]) )->default_value( (*_boolOptions)[Options::DNC_MODE] ), - "Use the split-and-conquer solving mode." ) - ( "seed", - boost::program_options::value( &((*_intOptions)[Options::SEED]) )->default_value( (*_intOptions)[Options::SEED] ), - "The random seed." ) - ( "dump-bounds", - boost::program_options::bool_switch( &((*_boolOptions)[Options::DUMP_BOUNDS]) )->default_value( (*_boolOptions)[Options::DUMP_BOUNDS] ), - "Dump the bounds after preprocessing." ) - ( "dump-topology", - boost::program_options::bool_switch( &((*_boolOptions)[Options::DUMP_TOPOLOGY]) )->default_value( (*_boolOptions)[Options::DUMP_TOPOLOGY] ), - "Dump the topology after the network level reasoning is initialized." ) - ( "query-dump-file", - boost::program_options::value( &(*_stringOptions)[Options::QUERY_DUMP_FILE] )->default_value( (*_stringOptions)[Options::QUERY_DUMP_FILE] ), - "Dump the verification query in Marabou's input query format." ) - ( "summary-file", - boost::program_options::value( &((*_stringOptions)[Options::SUMMARY_FILE]) )->default_value( (*_stringOptions)[Options::SUMMARY_FILE] ), - "Produce a summary file of the run." ) - ( "export-assignment", - boost::program_options::bool_switch( &((*_boolOptions)[Options::EXPORT_ASSIGNMENT]) )->default_value( (*_boolOptions)[Options::EXPORT_ASSIGNMENT] ), - "Export a satisfying assignment if found." ) - ( "export-assignment-file", - boost::program_options::value( &(*_stringOptions)[Options::EXPORT_ASSIGNMENT_FILE_PATH] )->default_value( (*_stringOptions)[Options::EXPORT_ASSIGNMENT_FILE_PATH] ), - "Specifies a file to export the assignment." ) - ( "debug-assignment", - boost::program_options::bool_switch( &((*_boolOptions)[Options::DEBUG_ASSIGNMENT]) )->default_value( (*_boolOptions)[Options::DEBUG_ASSIGNMENT] ), - "Import an assignment for debugging." ) - ( "debug-assignment-file", - boost::program_options::value( &(*_stringOptions)[Options::EXPORT_ASSIGNMENT_FILE_PATH] )->default_value( (*_stringOptions)[Options::EXPORT_ASSIGNMENT_FILE_PATH] ), - "Specifies a file to import the assignment for debugging." ) - ( "prove-unsat", - boost::program_options::bool_switch( &((*_boolOptions)[Options::PRODUCE_PROOFS]) )->default_value( (*_boolOptions)[Options::PRODUCE_PROOFS] ), + _other.add_options()( + "verbosity", + boost::program_options::value( &( ( *_intOptions )[Options::VERBOSITY] ) ) + ->default_value( ( *_intOptions )[Options::VERBOSITY] ), + "Verbosity of engine::solve(). 0: does not print anything, 1: print" + "out statistics in the beginning and end, 2: print out statistics during solving." )( + "snc", + boost::program_options::bool_switch( &( ( *_boolOptions )[Options::DNC_MODE] ) ) + ->default_value( ( *_boolOptions )[Options::DNC_MODE] ), + "Use the split-and-conquer solving mode." )( + "seed", + boost::program_options::value( &( ( *_intOptions )[Options::SEED] ) ) + ->default_value( ( *_intOptions )[Options::SEED] ), + "The random seed." )( + "dump-bounds", + boost::program_options::bool_switch( &( ( *_boolOptions )[Options::DUMP_BOUNDS] ) ) + ->default_value( ( *_boolOptions )[Options::DUMP_BOUNDS] ), + "Dump the bounds after preprocessing." )( + "dump-topology", + boost::program_options::bool_switch( &( ( *_boolOptions )[Options::DUMP_TOPOLOGY] ) ) + ->default_value( ( *_boolOptions )[Options::DUMP_TOPOLOGY] ), + "Dump the topology after the network level reasoning is initialized." )( + "query-dump-file", + boost::program_options::value( &( *_stringOptions )[Options::QUERY_DUMP_FILE] ) + ->default_value( ( *_stringOptions )[Options::QUERY_DUMP_FILE] ), + "Dump the verification query in Marabou's input query format." )( + "summary-file", + boost::program_options::value( + &( ( *_stringOptions )[Options::SUMMARY_FILE] ) ) + ->default_value( ( *_stringOptions )[Options::SUMMARY_FILE] ), + "Produce a summary file of the run." )( + "export-assignment", + boost::program_options::bool_switch( &( ( *_boolOptions )[Options::EXPORT_ASSIGNMENT] ) ) + ->default_value( ( *_boolOptions )[Options::EXPORT_ASSIGNMENT] ), + "Export a satisfying assignment if found." )( + "export-assignment-file", + boost::program_options::value( + &( *_stringOptions )[Options::EXPORT_ASSIGNMENT_FILE_PATH] ) + ->default_value( ( *_stringOptions )[Options::EXPORT_ASSIGNMENT_FILE_PATH] ), + "Specifies a file to export the assignment." )( + "debug-assignment", + boost::program_options::bool_switch( &( ( *_boolOptions )[Options::DEBUG_ASSIGNMENT] ) ) + ->default_value( ( *_boolOptions )[Options::DEBUG_ASSIGNMENT] ), + "Import an assignment for debugging." )( + "debug-assignment-file", + boost::program_options::value( + &( *_stringOptions )[Options::EXPORT_ASSIGNMENT_FILE_PATH] ) + ->default_value( ( *_stringOptions )[Options::EXPORT_ASSIGNMENT_FILE_PATH] ), + "Specifies a file to import the assignment for debugging." )( + "prove-unsat", + boost::program_options::bool_switch( &( ( *_boolOptions )[Options::PRODUCE_PROOFS] ) ) + ->default_value( ( *_boolOptions )[Options::PRODUCE_PROOFS] ), "Produce proofs of UNSAT and check them" ) #ifdef ENABLE_GUROBI #endif // ENABLE_GUROBI ; - _expert.add_options() - ( "tightening-strategy", - boost::program_options::value( &((*_stringOptions)[Options::SYMBOLIC_BOUND_TIGHTENING_TYPE]) )->default_value( (*_stringOptions)[Options::SYMBOLIC_BOUND_TIGHTENING_TYPE] ), - "type of bound tightening technique to use: sbt/deeppoly/none." ) - ( "branch", - boost::program_options::value( &((*_stringOptions)[Options::SPLITTING_STRATEGY]) )->default_value( (*_stringOptions)[Options::SPLITTING_STRATEGY] ), - "The branching strategy (earliest-relu/pseudo-impact/largest-interval/relu-violation/polarity)." - " pseudo-impact is specific to the DeepSoI (default) procedure and relu-violation is specific to the Reluplex procedure.\n" ) - ( "soi-split-threshold", - boost::program_options::value( &((*_intOptions)[Options::DEEP_SOI_REJECTION_THRESHOLD]) )->default_value( (*_intOptions)[Options::DEEP_SOI_REJECTION_THRESHOLD] ), - "(DeepSoI) Max number of rejected phase pattern proposal before splitting." ) - ( "soi-search-strategy", - boost::program_options::value( &((*_stringOptions)[Options::SOI_SEARCH_STRATEGY]) )->default_value( (*_stringOptions)[Options::SOI_SEARCH_STRATEGY] ), - "(DeepSoI) Strategy for stochastically minimizing the soi: mcmc/walksat." ) - ( "soi-init-strategy", - boost::program_options::value( &((*_stringOptions)[Options::SOI_INITIALIZATION_STRATEGY]) )->default_value( (*_stringOptions)[Options::SOI_INITIALIZATION_STRATEGY] ), - "(DeepSoI) Strategy for initialize the soi function: input-assignment/current-assignment. default: input-assignment." ) - ( "mcmc-beta", - boost::program_options::value( &((*_floatOptions)[Options::PROBABILITY_DENSITY_PARAMETER]) )->default_value( (*_floatOptions)[Options::PROBABILITY_DENSITY_PARAMETER] ), - "(DeepSoI) The beta parameter in MCMC search.\n" ) - ( "split-strategy", - boost::program_options::value( &((*_stringOptions)[Options::SNC_SPLITTING_STRATEGY]) )->default_value( (*_stringOptions)[Options::SNC_SPLITTING_STRATEGY] ), - "(SnC) The splitting strategy." ) - ( "initial-divides", - boost::program_options::value( &((*_intOptions)[Options::NUM_INITIAL_DIVIDES]) )->default_value( (*_intOptions)[Options::NUM_INITIAL_DIVIDES] ), - "(SnC) Number of times to initially bisect the input region." ) - ( "initial-timeout", - boost::program_options::value( &((*_intOptions)[Options::INITIAL_TIMEOUT]) )->default_value( (*_intOptions)[Options::INITIAL_TIMEOUT] ), - "(SnC) The initial timeout." ) - ( "num-online-divides", - boost::program_options::value( &((*_intOptions)[Options::NUM_ONLINE_DIVIDES]) )->default_value( (*_intOptions)[Options::NUM_ONLINE_DIVIDES] ), - "(SnC) Number of times to further bisect a sub-region when a timeout occurs." ) - ( "timeout-factor", - boost::program_options::value( &((*_floatOptions)[Options::TIMEOUT_FACTOR]) )->default_value( (*_floatOptions)[Options::TIMEOUT_FACTOR] ), - "(SnC) The timeout factor." ) - ( "restore-tree-states", - boost::program_options::bool_switch( &((*_boolOptions)[Options::RESTORE_TREE_STATES]) )->default_value( (*_boolOptions)[Options::RESTORE_TREE_STATES] ), - "(SnC) Restore tree states in SnC mode.\n" ) - ( "blas-threads", - boost::program_options::value( &((*_intOptions)[Options::NUM_BLAS_THREADS]) )->default_value( (*_intOptions)[Options::NUM_BLAS_THREADS] ), - "Number of threads to use for matrix multiplication with OpenBLAS." ) - ( "reluplex-split-threshold", - boost::program_options::value( &((*_intOptions)[Options::CONSTRAINT_VIOLATION_THRESHOLD]) )->default_value( (*_intOptions)[Options::CONSTRAINT_VIOLATION_THRESHOLD] ), - "Max number of tries to repair a relu before splitting when the Reluplex procedure is used." ) - ( "preprocessor-bound-tolerance", - boost::program_options::value( &((*_floatOptions)[Options::PREPROCESSOR_BOUND_TOLERANCE]) )->default_value( (*_floatOptions)[Options::PREPROCESSOR_BOUND_TOLERANCE] ), - "epsilon for preprocessor bound tightening comparisons." ) - ( "softmax-bound-type", - boost::program_options::value( &(*_stringOptions)[Options::SOFTMAX_BOUND_TYPE] )->default_value( (*_stringOptions)[Options::SOFTMAX_BOUND_TYPE] ), - "Type of softmax symbolic bound to use: er/lse, detailed in paper 'Convex Bounds on the Softmax Function with Applications to Robustness Verification'" ) - ( "poi", - boost::program_options::bool_switch( &(*_boolOptions)[Options::PARALLEL_DEEPSOI] )->default_value( (*_boolOptions)[Options::PARALLEL_DEEPSOI] ), - "Use the parallel deep-soi solving mode." ) + _expert.add_options()( + "tightening-strategy", + boost::program_options::value( + &( ( *_stringOptions )[Options::SYMBOLIC_BOUND_TIGHTENING_TYPE] ) ) + ->default_value( ( *_stringOptions )[Options::SYMBOLIC_BOUND_TIGHTENING_TYPE] ), + "type of bound tightening technique to use: sbt/deeppoly/none." )( + "branch", + boost::program_options::value( + &( ( *_stringOptions )[Options::SPLITTING_STRATEGY] ) ) + ->default_value( ( *_stringOptions )[Options::SPLITTING_STRATEGY] ), + "The branching strategy " + "(earliest-relu/pseudo-impact/largest-interval/relu-violation/polarity)." + " pseudo-impact is specific to the DeepSoI (default) procedure and relu-violation is " + "specific to the Reluplex procedure.\n" )( + "soi-split-threshold", + boost::program_options::value( + &( ( *_intOptions )[Options::DEEP_SOI_REJECTION_THRESHOLD] ) ) + ->default_value( ( *_intOptions )[Options::DEEP_SOI_REJECTION_THRESHOLD] ), + "(DeepSoI) Max number of rejected phase pattern proposal before splitting." )( + "soi-search-strategy", + boost::program_options::value( + &( ( *_stringOptions )[Options::SOI_SEARCH_STRATEGY] ) ) + ->default_value( ( *_stringOptions )[Options::SOI_SEARCH_STRATEGY] ), + "(DeepSoI) Strategy for stochastically minimizing the soi: mcmc/walksat." )( + "soi-init-strategy", + boost::program_options::value( + &( ( *_stringOptions )[Options::SOI_INITIALIZATION_STRATEGY] ) ) + ->default_value( ( *_stringOptions )[Options::SOI_INITIALIZATION_STRATEGY] ), + "(DeepSoI) Strategy for initialize the soi function: input-assignment/current-assignment. " + "default: input-assignment." )( + "mcmc-beta", + boost::program_options::value( + &( ( *_floatOptions )[Options::PROBABILITY_DENSITY_PARAMETER] ) ) + ->default_value( ( *_floatOptions )[Options::PROBABILITY_DENSITY_PARAMETER] ), + "(DeepSoI) The beta parameter in MCMC search.\n" )( + "split-strategy", + boost::program_options::value( + &( ( *_stringOptions )[Options::SNC_SPLITTING_STRATEGY] ) ) + ->default_value( ( *_stringOptions )[Options::SNC_SPLITTING_STRATEGY] ), + "(SnC) The splitting strategy." )( + "initial-divides", + boost::program_options::value( &( ( *_intOptions )[Options::NUM_INITIAL_DIVIDES] ) ) + ->default_value( ( *_intOptions )[Options::NUM_INITIAL_DIVIDES] ), + "(SnC) Number of times to initially bisect the input region." )( + "initial-timeout", + boost::program_options::value( &( ( *_intOptions )[Options::INITIAL_TIMEOUT] ) ) + ->default_value( ( *_intOptions )[Options::INITIAL_TIMEOUT] ), + "(SnC) The initial timeout." )( + "num-online-divides", + boost::program_options::value( &( ( *_intOptions )[Options::NUM_ONLINE_DIVIDES] ) ) + ->default_value( ( *_intOptions )[Options::NUM_ONLINE_DIVIDES] ), + "(SnC) Number of times to further bisect a sub-region when a timeout occurs." )( + "timeout-factor", + boost::program_options::value( &( ( *_floatOptions )[Options::TIMEOUT_FACTOR] ) ) + ->default_value( ( *_floatOptions )[Options::TIMEOUT_FACTOR] ), + "(SnC) The timeout factor." )( + "restore-tree-states", + boost::program_options::bool_switch( &( ( *_boolOptions )[Options::RESTORE_TREE_STATES] ) ) + ->default_value( ( *_boolOptions )[Options::RESTORE_TREE_STATES] ), + "(SnC) Restore tree states in SnC mode.\n" )( + "blas-threads", + boost::program_options::value( &( ( *_intOptions )[Options::NUM_BLAS_THREADS] ) ) + ->default_value( ( *_intOptions )[Options::NUM_BLAS_THREADS] ), + "Number of threads to use for matrix multiplication with OpenBLAS." )( + "reluplex-split-threshold", + boost::program_options::value( + &( ( *_intOptions )[Options::CONSTRAINT_VIOLATION_THRESHOLD] ) ) + ->default_value( ( *_intOptions )[Options::CONSTRAINT_VIOLATION_THRESHOLD] ), + "Max number of tries to repair a relu before splitting when the Reluplex procedure is " + "used." )( "preprocessor-bound-tolerance", + boost::program_options::value( + &( ( *_floatOptions )[Options::PREPROCESSOR_BOUND_TOLERANCE] ) ) + ->default_value( ( *_floatOptions )[Options::PREPROCESSOR_BOUND_TOLERANCE] ), + "epsilon for preprocessor bound tightening comparisons." )( + "softmax-bound-type", + boost::program_options::value( + &( *_stringOptions )[Options::SOFTMAX_BOUND_TYPE] ) + ->default_value( ( *_stringOptions )[Options::SOFTMAX_BOUND_TYPE] ), + "Type of softmax symbolic bound to use: er/lse, detailed in paper 'Convex Bounds on the " + "Softmax Function with Applications to Robustness Verification'" )( + "poi", + boost::program_options::bool_switch( &( *_boolOptions )[Options::PARALLEL_DEEPSOI] ) + ->default_value( ( *_boolOptions )[Options::PARALLEL_DEEPSOI] ), + "Use the parallel deep-soi solving mode." ) #ifdef ENABLE_GUROBI ( "lp-solver", - boost::program_options::value( &((*_stringOptions)[Options::LP_SOLVER]) )->default_value( (*_stringOptions)[Options::LP_SOLVER] ), - "Solver for the LPs during the complete analysis: native/gurobi." ) - ( "num-simulations", - boost::program_options::value( &((*_intOptions)[Options::NUMBER_OF_SIMULATIONS]) )->default_value( (*_intOptions)[Options::NUMBER_OF_SIMULATIONS] ), - "Number of simulations generated per neuron." ) - ( "lp-tightening-after-split", - boost::program_options::bool_switch( &((*_boolOptions)[Options::PERFORM_LP_TIGHTENING_AFTER_SPLIT]) )->default_value( (*_boolOptions)[Options::PERFORM_LP_TIGHTENING_AFTER_SPLIT] ), - "Whether to skip a LP tightening after a case split." ) - ( "milp-timeout", - boost::program_options::value( &((*_floatOptions)[Options::MILP_SOLVER_TIMEOUT]) )->default_value( (*_floatOptions)[Options::MILP_SOLVER_TIMEOUT] ), - "Per-ReLU timeout for iterative propagation." ) - ( "milp-tightening", - boost::program_options::value( &((*_stringOptions)[Options::MILP_SOLVER_BOUND_TIGHTENING_TYPE ]) )->default_value((*_stringOptions)[Options::MILP_SOLVER_BOUND_TIGHTENING_TYPE ]) , - "The MILP solver bound tightening type: lp/lp-inc/milp/milp-inc/iter-prop/none." ) + boost::program_options::value( &( ( *_stringOptions )[Options::LP_SOLVER] ) ) + ->default_value( ( *_stringOptions )[Options::LP_SOLVER] ), + "Solver for the LPs during the complete analysis: native/gurobi." )( + "num-simulations", + boost::program_options::value( + &( ( *_intOptions )[Options::NUMBER_OF_SIMULATIONS] ) ) + ->default_value( ( *_intOptions )[Options::NUMBER_OF_SIMULATIONS] ), + "Number of simulations generated per neuron." )( + "lp-tightening-after-split", + boost::program_options::bool_switch( + &( ( *_boolOptions )[Options::PERFORM_LP_TIGHTENING_AFTER_SPLIT] ) ) + ->default_value( ( *_boolOptions )[Options::PERFORM_LP_TIGHTENING_AFTER_SPLIT] ), + "Whether to skip a LP tightening after a case split." )( + "milp-timeout", + boost::program_options::value( + &( ( *_floatOptions )[Options::MILP_SOLVER_TIMEOUT] ) ) + ->default_value( ( *_floatOptions )[Options::MILP_SOLVER_TIMEOUT] ), + "Per-ReLU timeout for iterative propagation." )( + "milp-tightening", + boost::program_options::value( + &( ( *_stringOptions )[Options::MILP_SOLVER_BOUND_TIGHTENING_TYPE] ) ) + ->default_value( ( *_stringOptions )[Options::MILP_SOLVER_BOUND_TIGHTENING_TYPE] ), + "The MILP solver bound tightening type: lp/lp-inc/milp/milp-inc/iter-prop/none." ) #endif ; @@ -197,10 +262,11 @@ void OptionParser::initialize() void OptionParser::parse( int argc, char **argv ) { - boost::program_options::store - ( boost::program_options::command_line_parser( argc, argv ) - .options( _optionDescription ).positional( _positionalOptions ).run(), - _variableMap ); + boost::program_options::store( boost::program_options::command_line_parser( argc, argv ) + .options( _optionDescription ) + .positional( _positionalOptions ) + .run(), + _variableMap ); boost::program_options::notify( _variableMap ); } @@ -218,7 +284,7 @@ int OptionParser::extractIntValue( const String &option ) void OptionParser::printHelpMessage() const { std::cerr << "\nusage: ./Marabou []\n" << std::endl; - std::cerr << "OR ./Marabou --input-query []\n" << std::endl; + std::cerr << "OR ./Marabou --input-query []\n" << std::endl; std::cerr << "You might also consider using the ./resources/runMarabou.py " << "script, see README.md for more information." << std::endl; diff --git a/src/configuration/Options.cpp b/src/configuration/Options.cpp index bde7fe4118..2ac88c5acd 100644 --- a/src/configuration/Options.cpp +++ b/src/configuration/Options.cpp @@ -13,10 +13,11 @@ **/ +#include "Options.h" + #include "ConfigurationError.h" #include "Debug.h" #include "GlobalConfiguration.h" -#include "Options.h" Options *Options::get() { @@ -74,7 +75,7 @@ void Options::initializeDefaultValues() */ _floatOptions[TIMEOUT_FACTOR] = 1.5; _floatOptions[MILP_SOLVER_TIMEOUT] = 1.0; - _floatOptions[PREPROCESSOR_BOUND_TOLERANCE] = \ + _floatOptions[PREPROCESSOR_BOUND_TOLERANCE] = GlobalConfiguration::DEFAULT_EPSILON_FOR_COMPARISONS; _floatOptions[PROBABILITY_DENSITY_PARAMETER] = 10; @@ -150,8 +151,7 @@ void Options::setString( unsigned option, std::string value ) DivideStrategy Options::getDivideStrategy() const { - String strategyString = String( _stringOptions.get - ( Options::SPLITTING_STRATEGY ) ); + String strategyString = String( _stringOptions.get( Options::SPLITTING_STRATEGY ) ); if ( strategyString == "polarity" ) return DivideStrategy::Polarity; else if ( strategyString == "earliest-relu" ) @@ -179,8 +179,7 @@ SnCDivideStrategy Options::getSnCDivideStrategy() const SymbolicBoundTighteningType Options::getSymbolicBoundTighteningType() const { - String strategyString = - String( _stringOptions.get( Options::SYMBOLIC_BOUND_TIGHTENING_TYPE ) ); + String strategyString = String( _stringOptions.get( Options::SYMBOLIC_BOUND_TIGHTENING_TYPE ) ); if ( strategyString == "sbt" ) return SymbolicBoundTighteningType::SYMBOLIC_BOUND_TIGHTENING; else if ( strategyString == "deeppoly" ) @@ -195,7 +194,8 @@ MILPSolverBoundTighteningType Options::getMILPSolverBoundTighteningType() const { if ( gurobiEnabled() ) { - String strategyString = String( _stringOptions.get( Options::MILP_SOLVER_BOUND_TIGHTENING_TYPE ) ); + String strategyString = + String( _stringOptions.get( Options::MILP_SOLVER_BOUND_TIGHTENING_TYPE ) ); if ( strategyString == "lp" ) return MILPSolverBoundTighteningType::LP_RELAXATION; else if ( strategyString == "lp-inc" ) @@ -219,8 +219,7 @@ MILPSolverBoundTighteningType Options::getMILPSolverBoundTighteningType() const SoISearchStrategy Options::getSoISearchStrategy() const { - String strategyString = String( _stringOptions.get - ( Options::SOI_SEARCH_STRATEGY ) ); + String strategyString = String( _stringOptions.get( Options::SOI_SEARCH_STRATEGY ) ); if ( strategyString == "mcmc" ) return SoISearchStrategy::MCMC; else if ( strategyString == "walksat" ) @@ -231,8 +230,7 @@ SoISearchStrategy Options::getSoISearchStrategy() const SoIInitializationStrategy Options::getSoIInitializationStrategy() const { - String strategyString = String( _stringOptions.get - ( Options::SOI_INITIALIZATION_STRATEGY ) ); + String strategyString = String( _stringOptions.get( Options::SOI_INITIALIZATION_STRATEGY ) ); if ( strategyString == "input-assignment" ) return SoIInitializationStrategy::INPUT_ASSIGNMENT; if ( strategyString == "current-assignment" ) @@ -243,8 +241,7 @@ SoIInitializationStrategy Options::getSoIInitializationStrategy() const LPSolverType Options::getLPSolverType() const { - String solverString = String( _stringOptions.get - ( Options::LP_SOLVER ) ); + String solverString = String( _stringOptions.get( Options::LP_SOLVER ) ); if ( solverString == "native" ) return LPSolverType::NATIVE; else if ( _boolOptions.get( Options::PRODUCE_PROOFS ) ) @@ -269,5 +266,4 @@ SoftmaxBoundType Options::getSoftmaxBoundType() const { return SoftmaxBoundType::LOG_SUM_EXP_DECOMPOSITION; } - } diff --git a/src/configuration/Options.h b/src/configuration/Options.h index 212c9f0ba0..ddc77007ce 100644 --- a/src/configuration/Options.h +++ b/src/configuration/Options.h @@ -18,16 +18,15 @@ #include "DivideStrategy.h" #include "LPSolverType.h" +#include "MILPSolverBoundTighteningType.h" #include "MString.h" #include "Map.h" -#include "MILPSolverBoundTighteningType.h" #include "OptionParser.h" #include "SnCDivideStrategy.h" #include "SoIInitializationStrategy.h" #include "SoISearchStrategy.h" #include "SoftmaxBoundType.h" #include "SymbolicBoundTighteningType.h" - #include "boost/program_options.hpp" /* @@ -69,10 +68,12 @@ class Options // any of the thread finishes. PARALLEL_DEEPSOI, - // Export SAT assignment into a file, use EXPORT_ASSIGNMENT_FILE to specify the file (default: assignment.txt) + // Export SAT assignment into a file, use EXPORT_ASSIGNMENT_FILE to specify the file + // (default: assignment.txt) EXPORT_ASSIGNMENT, - // Import assignment for debugging purposes, use IMPORT_ASSIGNMENT_FILE to specify the file (default: assignment.txt) + // Import assignment for debugging purposes, use IMPORT_ASSIGNMENT_FILE to specify the file + // (default: assignment.txt) DEBUG_ASSIGNMENT, // Produce proofs of unsatisfiability and check them @@ -108,7 +109,7 @@ class Options NUM_BLAS_THREADS, }; - enum FloatOptions{ + enum FloatOptions { // DNC options TIMEOUT_FACTOR, diff --git a/src/engine/AbsoluteValueConstraint.cpp b/src/engine/AbsoluteValueConstraint.cpp index 63172d9f32..0d6055a392 100644 --- a/src/engine/AbsoluteValueConstraint.cpp +++ b/src/engine/AbsoluteValueConstraint.cpp @@ -120,12 +120,11 @@ void AbsoluteValueConstraint::unregisterAsWatcher( ITableau *tableau ) void AbsoluteValueConstraint::notifyLowerBound( unsigned variable, double bound ) { if ( _statistics ) - _statistics->incLongAttribute( - Statistics::NUM_BOUND_NOTIFICATIONS_TO_PL_CONSTRAINTS ); + _statistics->incLongAttribute( Statistics::NUM_BOUND_NOTIFICATIONS_TO_PL_CONSTRAINTS ); if ( _boundManager == nullptr && existsLowerBound( variable ) && !FloatUtils::gt( bound, getLowerBound( variable ) ) ) - return; + return; setLowerBound( variable, bound ); @@ -144,14 +143,20 @@ void AbsoluteValueConstraint::notifyLowerBound( unsigned variable, double bound { if ( bound < 0 ) { - double fUpperBound = FloatUtils::max( -bound, getUpperBound( _b ) ) ; - // If phase is not fixed, both bounds are stored and checker should check the max of the two + double fUpperBound = FloatUtils::max( -bound, getUpperBound( _b ) ); + // If phase is not fixed, both bounds are stored and checker should check the max of + // the two if ( proofs && !phaseFixed() ) - _boundManager->addLemmaExplanationAndTightenBound( _f, fUpperBound, BoundType::UPPER, - { variable, variable }, BoundType::UPPER, getType() ); + _boundManager->addLemmaExplanationAndTightenBound( _f, + fUpperBound, + BoundType::UPPER, + { variable, variable }, + BoundType::UPPER, + getType() ); else if ( proofs && phaseFixed() ) { - std::shared_ptr tighteningRow = fUpperBound == getUpperBound( _b ) ? _posTighteningRow : _negTighteningRow; + std::shared_ptr tighteningRow = + fUpperBound == getUpperBound( _b ) ? _posTighteningRow : _negTighteningRow; _boundManager->tightenUpperBound( _f, fUpperBound, *tighteningRow ); } else @@ -160,7 +165,8 @@ void AbsoluteValueConstraint::notifyLowerBound( unsigned variable, double bound if ( _auxVarsInUse ) { if ( proofs ) - _boundManager->tightenUpperBound( _posAux, fUpperBound - bound , *_posTighteningRow ); + _boundManager->tightenUpperBound( + _posAux, fUpperBound - bound, *_posTighteningRow ); else _boundManager->tightenUpperBound( _posAux, fUpperBound - bound ); } @@ -205,7 +211,6 @@ void AbsoluteValueConstraint::notifyUpperBound( unsigned variable, double bound // Update partner's bound if ( isActive() && _boundManager ) { - bool proofs = _boundManager->shouldProduceProofs(); if ( proofs ) @@ -216,16 +221,22 @@ void AbsoluteValueConstraint::notifyUpperBound( unsigned variable, double bound if ( variable == _b ) { - if ( bound > 0 ) + if ( bound > 0 ) { - double fUpperBound = FloatUtils::max( bound, -getLowerBound( _b ) ) ; - // If phase is not fixed, both bonds are stored and checker should check the max of the two + double fUpperBound = FloatUtils::max( bound, -getLowerBound( _b ) ); + // If phase is not fixed, both bonds are stored and checker should check the max of + // the two if ( proofs && !phaseFixed() ) - _boundManager->addLemmaExplanationAndTightenBound( _f, fUpperBound, BoundType::UPPER, - { variable, variable }, BoundType::UPPER, getType() ); + _boundManager->addLemmaExplanationAndTightenBound( _f, + fUpperBound, + BoundType::UPPER, + { variable, variable }, + BoundType::UPPER, + getType() ); else if ( proofs && phaseFixed() ) { - std::shared_ptr tighteningRow = fUpperBound == bound ? _posTighteningRow : _negTighteningRow; + std::shared_ptr tighteningRow = + fUpperBound == bound ? _posTighteningRow : _negTighteningRow; _boundManager->tightenUpperBound( _f, fUpperBound, *tighteningRow ); } else @@ -234,7 +245,8 @@ void AbsoluteValueConstraint::notifyUpperBound( unsigned variable, double bound if ( _auxVarsInUse ) { if ( proofs ) - _boundManager->tightenUpperBound( _negAux, fUpperBound + bound, *_negTighteningRow ); + _boundManager->tightenUpperBound( + _negAux, fUpperBound + bound, *_negTighteningRow ); else _boundManager->tightenUpperBound( _negAux, fUpperBound + bound ); } @@ -268,7 +280,8 @@ void AbsoluteValueConstraint::notifyUpperBound( unsigned variable, double bound if ( existsLowerBound( _b ) ) { if ( proofs ) - _boundManager->tightenUpperBound( _posAux, bound - getLowerBound( _b ), *_posTighteningRow ); + _boundManager->tightenUpperBound( + _posAux, bound - getLowerBound( _b ), *_posTighteningRow ); else _boundManager->tightenUpperBound( _posAux, bound - getLowerBound( _b ) ); } @@ -276,7 +289,8 @@ void AbsoluteValueConstraint::notifyUpperBound( unsigned variable, double bound if ( existsUpperBound( _b ) ) { if ( proofs ) - _boundManager->tightenUpperBound( _negAux, bound + getUpperBound( _b ), *_negTighteningRow ); + _boundManager->tightenUpperBound( + _negAux, bound + getUpperBound( _b ), *_negTighteningRow ); else _boundManager->tightenUpperBound( _negAux, bound + getUpperBound( _b ) ); } @@ -289,7 +303,8 @@ void AbsoluteValueConstraint::notifyUpperBound( unsigned variable, double bound if ( existsUpperBound( _b ) ) { if ( proofs ) - _boundManager->tightenUpperBound( _f, getUpperBound( _b ) + bound, *_posTighteningRow ); + _boundManager->tightenUpperBound( + _f, getUpperBound( _b ) + bound, *_posTighteningRow ); else _boundManager->tightenUpperBound( _f, getUpperBound( _b ) + bound ); } @@ -297,7 +312,8 @@ void AbsoluteValueConstraint::notifyUpperBound( unsigned variable, double bound if ( existsLowerBound( _f ) ) { if ( proofs ) - _boundManager->tightenLowerBound( _b, getLowerBound( _f ) - bound, *_posTighteningRow ); + _boundManager->tightenLowerBound( + _b, getLowerBound( _f ) - bound, *_posTighteningRow ); else _boundManager->tightenLowerBound( _b, getLowerBound( _f ) - bound ); } @@ -307,7 +323,8 @@ void AbsoluteValueConstraint::notifyUpperBound( unsigned variable, double bound if ( existsLowerBound( _b ) ) { if ( proofs ) - _boundManager->tightenUpperBound( _f, bound - getLowerBound( _b ), *_negTighteningRow ); + _boundManager->tightenUpperBound( + _f, bound - getLowerBound( _b ), *_negTighteningRow ); else _boundManager->tightenUpperBound( _f, bound - getLowerBound( _b ) ); } @@ -315,26 +332,26 @@ void AbsoluteValueConstraint::notifyUpperBound( unsigned variable, double bound if ( existsLowerBound( _f ) ) { if ( proofs ) - _boundManager->tightenUpperBound( _b, bound - getLowerBound( _f ), *_negTighteningRow ); + _boundManager->tightenUpperBound( + _b, bound - getLowerBound( _f ), *_negTighteningRow ); else _boundManager->tightenUpperBound( _b, bound - getLowerBound( _f ) ); } } - } + } } } bool AbsoluteValueConstraint::participatingVariable( unsigned variable ) const { - return ( variable == _b ) || ( variable == _f ) - || ( _auxVarsInUse && ( variable == _posAux || variable == _negAux ) ); + return ( variable == _b ) || ( variable == _f ) || + ( _auxVarsInUse && ( variable == _posAux || variable == _negAux ) ); } List AbsoluteValueConstraint::getParticipatingVariables() const { - return _auxVarsInUse ? - List( { _b, _f, _posAux, _negAux } ) : - List( { _b, _f } ); + return _auxVarsInUse ? List( { _b, _f, _posAux, _negAux } ) + : List( { _b, _f } ); } bool AbsoluteValueConstraint::satisfied() const @@ -352,9 +369,8 @@ bool AbsoluteValueConstraint::satisfied() const if ( fValue < 0 ) return false; - return FloatUtils::areEqual( FloatUtils::abs( bValue ), - fValue, - GlobalConfiguration::CONSTRAINT_COMPARISON_TOLERANCE ); + return FloatUtils::areEqual( + FloatUtils::abs( bValue ), fValue, GlobalConfiguration::CONSTRAINT_COMPARISON_TOLERANCE ); } List AbsoluteValueConstraint::getPossibleFixes() const @@ -382,7 +398,8 @@ List AbsoluteValueConstraint::getPossibleFixes() return fixes; } -List AbsoluteValueConstraint::getSmartFixes( ITableau */* tableau */ ) const +List +AbsoluteValueConstraint::getSmartFixes( ITableau * /* tableau */ ) const { return getPossibleFixes(); } @@ -490,31 +507,41 @@ void AbsoluteValueConstraint::eliminateVariable( unsigned variable, double /* fi void AbsoluteValueConstraint::dump( String &output ) const { - output = Stringf( "AbsoluteValueCosntraint: x%u = Abs( x%u ). Active? %s. PhaseStatus = %u (%s).\n", - _f, _b, - _constraintActive ? "Yes" : "No", - _phaseStatus, phaseToString( _phaseStatus ).ascii() - ); + output = + Stringf( "AbsoluteValueCosntraint: x%u = Abs( x%u ). Active? %s. PhaseStatus = %u (%s).\n", + _f, + _b, + _constraintActive ? "Yes" : "No", + _phaseStatus, + phaseToString( _phaseStatus ).ascii() ); - output += Stringf( "b in [%s, %s], ", - existsLowerBound( _b ) ? Stringf( "%lf", getLowerBound( _b ) ).ascii() : "-inf", - existsUpperBound( _b ) ? Stringf( "%lf", getUpperBound( _b ) ).ascii() : "inf" ); + output += + Stringf( "b in [%s, %s], ", + existsLowerBound( _b ) ? Stringf( "%lf", getLowerBound( _b ) ).ascii() : "-inf", + existsUpperBound( _b ) ? Stringf( "%lf", getUpperBound( _b ) ).ascii() : "inf" ); - output += Stringf( "f in [%s, %s]", - existsLowerBound( _f ) ? Stringf( "%lf", getLowerBound( _f ) ).ascii() : "-inf", - existsUpperBound( _f ) ? Stringf( "%lf", getUpperBound( _f ) ).ascii() : "inf" ); + output += + Stringf( "f in [%s, %s]", + existsLowerBound( _f ) ? Stringf( "%lf", getLowerBound( _f ) ).ascii() : "-inf", + existsUpperBound( _f ) ? Stringf( "%lf", getUpperBound( _f ) ).ascii() : "inf" ); if ( _auxVarsInUse ) { - output += Stringf( ". PosAux: %u. Range: [%s, %s]", - _posAux, - existsLowerBound( _posAux ) ? Stringf( "%lf", getLowerBound( _posAux ) ).ascii() : "-inf", - existsUpperBound( _posAux ) ? Stringf( "%lf", getUpperBound( _posAux ) ).ascii() : "inf" ); - - output += Stringf( ". NegAux: %u. Range: [%s, %s]", - _negAux, - existsLowerBound( _negAux ) ? Stringf( "%lf", getLowerBound( _negAux ) ).ascii() : "-inf", - existsUpperBound( _negAux ) ? Stringf( "%lf", getUpperBound( _negAux ) ).ascii() : "inf" ); + output += Stringf( + ". PosAux: %u. Range: [%s, %s]", + _posAux, + existsLowerBound( _posAux ) ? Stringf( "%lf", getLowerBound( _posAux ) ).ascii() + : "-inf", + existsUpperBound( _posAux ) ? Stringf( "%lf", getUpperBound( _posAux ) ).ascii() + : "inf" ); + + output += Stringf( + ". NegAux: %u. Range: [%s, %s]", + _negAux, + existsLowerBound( _negAux ) ? Stringf( "%lf", getLowerBound( _negAux ) ).ascii() + : "-inf", + existsUpperBound( _negAux ) ? Stringf( "%lf", getUpperBound( _negAux ) ).ascii() + : "inf" ); } } @@ -527,9 +554,9 @@ void AbsoluteValueConstraint::updateVariableIndex( unsigned oldIndex, unsigned n ASSERT( oldIndex == _b || oldIndex == _f || ( _auxVarsInUse && ( oldIndex == _posAux || oldIndex == _negAux ) ) ); - ASSERT( !existsLowerBound( newIndex ) && - !existsUpperBound( newIndex ) && - newIndex != _b && newIndex != _f && ( !_auxVarsInUse || ( newIndex != _posAux && newIndex != _negAux ) ) ); + ASSERT( !existsLowerBound( newIndex ) && !existsUpperBound( newIndex ) && newIndex != _b && + newIndex != _f && + ( !_auxVarsInUse || ( newIndex != _posAux && newIndex != _negAux ) ) ); if ( existsLowerBound( oldIndex ) ) { @@ -560,8 +587,8 @@ bool AbsoluteValueConstraint::constraintObsolete() const void AbsoluteValueConstraint::getEntailedTightenings( List &tightenings ) const { - ASSERT( existsLowerBound( _b ) && existsLowerBound( _f ) && - existsUpperBound( _b ) && existsUpperBound( _f ) ); + ASSERT( existsLowerBound( _b ) && existsLowerBound( _f ) && existsUpperBound( _b ) && + existsUpperBound( _f ) ); // Upper bounds double bUpperBound = getUpperBound( _b ); @@ -615,16 +642,13 @@ void AbsoluteValueConstraint::getEntailedTightenings( List &tighteni // Phase undetermined, b can be either positive or negative, f can be 0 tightenings.append( Tightening( _b, -fUpperBound, Tightening::LB ) ); tightenings.append( Tightening( _b, fUpperBound, Tightening::UB ) ); - tightenings.append( Tightening( _f, FloatUtils::max( -bLowerBound, bUpperBound ), Tightening::UB ) ); + tightenings.append( + Tightening( _f, FloatUtils::max( -bLowerBound, bUpperBound ), Tightening::UB ) ); if ( _auxVarsInUse ) { - tightenings.append( Tightening( _posAux, - fUpperBound - bLowerBound, - Tightening::UB ) ); - tightenings.append( Tightening( _negAux, - fUpperBound + bUpperBound, - Tightening::UB ) ); + tightenings.append( Tightening( _posAux, fUpperBound - bLowerBound, Tightening::UB ) ); + tightenings.append( Tightening( _negAux, fUpperBound + bUpperBound, Tightening::UB ) ); } } @@ -633,16 +657,13 @@ void AbsoluteValueConstraint::getEntailedTightenings( List &tighteni // Phase undetermined, b can be either positive or negative, f strictly positive tightenings.append( Tightening( _b, -fUpperBound, Tightening::LB ) ); tightenings.append( Tightening( _b, fUpperBound, Tightening::UB ) ); - tightenings.append( Tightening( _f, FloatUtils::max( -bLowerBound, bUpperBound ), Tightening::UB ) ); + tightenings.append( + Tightening( _f, FloatUtils::max( -bLowerBound, bUpperBound ), Tightening::UB ) ); if ( _auxVarsInUse ) { - tightenings.append( Tightening( _posAux, - fUpperBound - bLowerBound, - Tightening::UB ) ); - tightenings.append( Tightening( _negAux, - fUpperBound + bUpperBound, - Tightening::UB ) ); + tightenings.append( Tightening( _posAux, fUpperBound - bLowerBound, Tightening::UB ) ); + tightenings.append( Tightening( _negAux, fUpperBound + bUpperBound, Tightening::UB ) ); } // Below we test if the phase has actually become fixed @@ -664,8 +685,7 @@ void AbsoluteValueConstraint::getEntailedTightenings( List &tighteni } } -void AbsoluteValueConstraint::transformToUseAuxVariables( InputQuery - &inputQuery ) +void AbsoluteValueConstraint::transformToUseAuxVariables( InputQuery &inputQuery ) { /* We want to add the two equations @@ -724,7 +744,7 @@ void AbsoluteValueConstraint::getCostFunctionComponent( LinearExpression &cost, PhaseStatus phase ) const { // If the constraint is not active or is fixed, it contributes nothing - if( !isActive() || phaseFixed() ) + if ( !isActive() || phaseFixed() ) return; ASSERT( phase == ABS_PHASE_NEGATIVE || phase == ABS_PHASE_POSITIVE ); @@ -757,12 +777,11 @@ void AbsoluteValueConstraint::getCostFunctionComponent( LinearExpression &cost, } } -PhaseStatus AbsoluteValueConstraint::getPhaseStatusInAssignment -( const Map &assignment ) const +PhaseStatus +AbsoluteValueConstraint::getPhaseStatusInAssignment( const Map &assignment ) const { ASSERT( assignment.exists( _b ) ); - return FloatUtils::isNegative( assignment[_b] ) ? - ABS_PHASE_NEGATIVE : ABS_PHASE_POSITIVE; + return FloatUtils::isNegative( assignment[_b] ) ? ABS_PHASE_NEGATIVE : ABS_PHASE_POSITIVE; } bool AbsoluteValueConstraint::haveOutOfBoundVariables() const @@ -784,9 +803,8 @@ bool AbsoluteValueConstraint::haveOutOfBoundVariables() const String AbsoluteValueConstraint::serializeToString() const { // Output format is: Abs,f,b,posAux,NegAux - return _auxVarsInUse ? - Stringf( "absoluteValue,%u,%u,%u,%u", _f, _b, _posAux, _negAux ) : - Stringf( "absoluteValue,%u,%u", _f, _b ); + return _auxVarsInUse ? Stringf( "absoluteValue,%u,%u,%u,%u", _f, _b, _posAux, _negAux ) + : Stringf( "absoluteValue,%u,%u", _f, _b ); } void AbsoluteValueConstraint::fixPhaseIfNeeded() @@ -807,8 +825,8 @@ void AbsoluteValueConstraint::fixPhaseIfNeeded() { setPhaseStatus( ABS_PHASE_POSITIVE ); if ( proofs ) - _boundManager->addLemmaExplanationAndTightenBound( _posAux, 0, BoundType::UPPER, { _b }, - BoundType::LOWER, getType() ); + _boundManager->addLemmaExplanationAndTightenBound( + _posAux, 0, BoundType::UPPER, { _b }, BoundType::LOWER, getType() ); return; } @@ -817,8 +835,8 @@ void AbsoluteValueConstraint::fixPhaseIfNeeded() { setPhaseStatus( ABS_PHASE_NEGATIVE ); if ( proofs ) - _boundManager->addLemmaExplanationAndTightenBound( _negAux, 0, BoundType::UPPER, { _b }, - BoundType::UPPER, getType() ); + _boundManager->addLemmaExplanationAndTightenBound( + _negAux, 0, BoundType::UPPER, { _b }, BoundType::UPPER, getType() ); return; } @@ -831,8 +849,8 @@ void AbsoluteValueConstraint::fixPhaseIfNeeded() { setPhaseStatus( ABS_PHASE_NEGATIVE ); if ( proofs ) - _boundManager->addLemmaExplanationAndTightenBound( _negAux, 0, BoundType::UPPER, { _b, _f }, - BoundType::UPPER, getType() ); + _boundManager->addLemmaExplanationAndTightenBound( + _negAux, 0, BoundType::UPPER, { _b, _f }, BoundType::UPPER, getType() ); return; } @@ -842,8 +860,8 @@ void AbsoluteValueConstraint::fixPhaseIfNeeded() { setPhaseStatus( ABS_PHASE_POSITIVE ); if ( proofs ) - _boundManager->addLemmaExplanationAndTightenBound( _posAux, 0, BoundType::UPPER, { _b, _f }, - BoundType::LOWER, getType() ); + _boundManager->addLemmaExplanationAndTightenBound( + _posAux, 0, BoundType::UPPER, { _b, _f }, BoundType::LOWER, getType() ); return; } @@ -861,8 +879,8 @@ void AbsoluteValueConstraint::fixPhaseIfNeeded() { setPhaseStatus( ABS_PHASE_NEGATIVE ); if ( proofs ) - _boundManager->addLemmaExplanationAndTightenBound( _negAux, 0, BoundType::UPPER, { _posAux }, - BoundType::LOWER, getType() ); + _boundManager->addLemmaExplanationAndTightenBound( + _negAux, 0, BoundType::UPPER, { _posAux }, BoundType::LOWER, getType() ); return; } @@ -878,8 +896,8 @@ void AbsoluteValueConstraint::fixPhaseIfNeeded() { setPhaseStatus( ABS_PHASE_POSITIVE ); if ( proofs ) - _boundManager->addLemmaExplanationAndTightenBound( _posAux, 0, BoundType::UPPER, { _negAux }, - BoundType::LOWER, getType() ); + _boundManager->addLemmaExplanationAndTightenBound( + _posAux, 0, BoundType::UPPER, { _negAux }, BoundType::LOWER, getType() ); return; } } @@ -906,12 +924,13 @@ String AbsoluteValueConstraint::phaseToString( PhaseStatus phase ) void AbsoluteValueConstraint::createPosTighteningRow() { // Create the row only when needed and when not already created - if ( !_boundManager->getBoundExplainer() || _posTighteningRow || !_auxVarsInUse || _tableauAuxVars.empty() ) + if ( !_boundManager->getBoundExplainer() || _posTighteningRow || !_auxVarsInUse || + _tableauAuxVars.empty() ) return; - _posTighteningRow = std::unique_ptr( new TableauRow ( 3 ) ); + _posTighteningRow = std::unique_ptr( new TableauRow( 3 ) ); // f = b + aux + counterpart (an additional aux variable of tableau) - _posTighteningRow->_lhs = _f; + _posTighteningRow->_lhs = _f; _posTighteningRow->_row[0] = TableauRow::Entry( _b, 1 ); _posTighteningRow->_row[1] = TableauRow::Entry( _posAux, 1 ); _posTighteningRow->_row[2] = TableauRow::Entry( _tableauAuxVars.front(), 1 ); @@ -920,13 +939,14 @@ void AbsoluteValueConstraint::createPosTighteningRow() void AbsoluteValueConstraint::createNegTighteningRow() { // Create the row only when needed and when not already created - if ( !_boundManager->getBoundExplainer() || _negTighteningRow || !_auxVarsInUse || _tableauAuxVars.empty() ) + if ( !_boundManager->getBoundExplainer() || _negTighteningRow || !_auxVarsInUse || + _tableauAuxVars.empty() ) return; - _negTighteningRow = std::unique_ptr( new TableauRow ( 3 ) ); + _negTighteningRow = std::unique_ptr( new TableauRow( 3 ) ); // f = b + aux + counterpart (an additional aux variable of tableau) - _negTighteningRow->_lhs = _f; + _negTighteningRow->_lhs = _f; _negTighteningRow->_row[0] = TableauRow::Entry( _b, -1 ); _negTighteningRow->_row[1] = TableauRow::Entry( _negAux, 1 ); _negTighteningRow->_row[2] = TableauRow::Entry( _tableauAuxVars.back(), 1 ); diff --git a/src/engine/AbsoluteValueConstraint.h b/src/engine/AbsoluteValueConstraint.h index cf34ca02b1..95228f46b5 100644 --- a/src/engine/AbsoluteValueConstraint.h +++ b/src/engine/AbsoluteValueConstraint.h @@ -34,7 +34,6 @@ class AbsoluteValueConstraint : public PiecewiseLinearConstraint { - public: /* The f variable is the absolute value of the b variable: @@ -61,8 +60,8 @@ class AbsoluteValueConstraint : public PiecewiseLinearConstraint /* Register/unregister the constraint with a talbeau. */ - void registerAsWatcher( ITableau *tableau) override; - void unregisterAsWatcher( ITableau *tableau) override; + void registerAsWatcher( ITableau *tableau ) override; + void unregisterAsWatcher( ITableau *tableau ) override; /* These callbacks are invoked when a watched variable's value @@ -184,24 +183,40 @@ class AbsoluteValueConstraint : public PiecewiseLinearConstraint Return the phase status corresponding to the values of the *input* variables in the given assignment. */ - virtual PhaseStatus getPhaseStatusInAssignment( const Map - &assignment ) const override; + virtual PhaseStatus + getPhaseStatusInAssignment( const Map &assignment ) const override; /* Returns string with shape: absoluteValue,_f,_b */ String serializeToString() const override; - inline unsigned getB() const { return _b; }; + inline unsigned getB() const + { + return _b; + }; - inline unsigned getF() const { return _f; }; + inline unsigned getF() const + { + return _f; + }; - inline bool auxVariablesInUse() const { return _auxVarsInUse; }; + inline bool auxVariablesInUse() const + { + return _auxVarsInUse; + }; - inline unsigned getPosAux() const { return _posAux; }; - inline unsigned getNegAux() const { return _negAux; }; + inline unsigned getPosAux() const + { + return _posAux; + }; + inline unsigned getNegAux() const + { + return _negAux; + }; const List getNativeAuxVars() const override; + private: /* The variables that make up this constraint; _f = | _b |. @@ -254,4 +269,3 @@ class AbsoluteValueConstraint : public PiecewiseLinearConstraint }; #endif // __AbsoluteValueConstraint_h__ - diff --git a/src/engine/AutoConstraintMatrixAnalyzer.h b/src/engine/AutoConstraintMatrixAnalyzer.h index cab3e5a812..175abc6091 100644 --- a/src/engine/AutoConstraintMatrixAnalyzer.h +++ b/src/engine/AutoConstraintMatrixAnalyzer.h @@ -22,38 +22,38 @@ class AutoConstraintMatrixAnalyzer { public: - AutoConstraintMatrixAnalyzer() - { - _constraintMatrixAnalyzer = T::createConstraintMatrixAnalyzer(); - } + AutoConstraintMatrixAnalyzer() + { + _constraintMatrixAnalyzer = T::createConstraintMatrixAnalyzer(); + } - ~AutoConstraintMatrixAnalyzer() - { - T::discardConstraintMatrixAnalyzer( _constraintMatrixAnalyzer ); - } + ~AutoConstraintMatrixAnalyzer() + { + T::discardConstraintMatrixAnalyzer( _constraintMatrixAnalyzer ); + } - operator IConstraintMatrixAnalyzer &() - { - return *_constraintMatrixAnalyzer; - } + operator IConstraintMatrixAnalyzer &() + { + return *_constraintMatrixAnalyzer; + } - operator IConstraintMatrixAnalyzer *() - { - return _constraintMatrixAnalyzer; - } + operator IConstraintMatrixAnalyzer *() + { + return _constraintMatrixAnalyzer; + } - IConstraintMatrixAnalyzer *operator->() - { - return _constraintMatrixAnalyzer; - } + IConstraintMatrixAnalyzer *operator->() + { + return _constraintMatrixAnalyzer; + } - const IConstraintMatrixAnalyzer *operator->() const - { - return _constraintMatrixAnalyzer; - } + const IConstraintMatrixAnalyzer *operator->() const + { + return _constraintMatrixAnalyzer; + } private: - IConstraintMatrixAnalyzer *_constraintMatrixAnalyzer; + IConstraintMatrixAnalyzer *_constraintMatrixAnalyzer; }; #endif // __AutoConstraintMatrixAnalyzer_h__ diff --git a/src/engine/AutoCostFunctionManager.h b/src/engine/AutoCostFunctionManager.h index 3e41dc03ac..15e69402ca 100644 --- a/src/engine/AutoCostFunctionManager.h +++ b/src/engine/AutoCostFunctionManager.h @@ -22,39 +22,39 @@ class AutoCostFunctionManager { public: - AutoCostFunctionManager( ITableau *tableau ) - { - _costFunctionManager = T::createCostFunctionManager( tableau ); - } + AutoCostFunctionManager( ITableau *tableau ) + { + _costFunctionManager = T::createCostFunctionManager( tableau ); + } - ~AutoCostFunctionManager() - { - T::discardCostFunctionManager( _costFunctionManager ); - _costFunctionManager = 0; - } + ~AutoCostFunctionManager() + { + T::discardCostFunctionManager( _costFunctionManager ); + _costFunctionManager = 0; + } - operator ICostFunctionManager &() - { - return *_costFunctionManager; - } + operator ICostFunctionManager &() + { + return *_costFunctionManager; + } - operator ICostFunctionManager *() - { - return _costFunctionManager; - } + operator ICostFunctionManager *() + { + return _costFunctionManager; + } - ICostFunctionManager *operator->() - { - return _costFunctionManager; - } + ICostFunctionManager *operator->() + { + return _costFunctionManager; + } - const ICostFunctionManager *operator->() const - { - return _costFunctionManager; - } + const ICostFunctionManager *operator->() const + { + return _costFunctionManager; + } private: - ICostFunctionManager *_costFunctionManager; + ICostFunctionManager *_costFunctionManager; }; #endif // __AutoCostFunctionManager_h__ diff --git a/src/engine/AutoProjectedSteepestEdge.h b/src/engine/AutoProjectedSteepestEdge.h index 41fc6072c4..dbe6690bf2 100644 --- a/src/engine/AutoProjectedSteepestEdge.h +++ b/src/engine/AutoProjectedSteepestEdge.h @@ -22,39 +22,39 @@ class AutoProjectedSteepestEdgeRule { public: - AutoProjectedSteepestEdgeRule() - { - _projectedSteepestEdgeRule = T::createProjectedSteepestEdgeRule(); - } + AutoProjectedSteepestEdgeRule() + { + _projectedSteepestEdgeRule = T::createProjectedSteepestEdgeRule(); + } - ~AutoProjectedSteepestEdgeRule() - { - T::discardProjectedSteepestEdgeRule( _projectedSteepestEdgeRule ); - _projectedSteepestEdgeRule = 0; - } + ~AutoProjectedSteepestEdgeRule() + { + T::discardProjectedSteepestEdgeRule( _projectedSteepestEdgeRule ); + _projectedSteepestEdgeRule = 0; + } - operator IProjectedSteepestEdgeRule &() - { - return *_projectedSteepestEdgeRule; - } + operator IProjectedSteepestEdgeRule &() + { + return *_projectedSteepestEdgeRule; + } - operator IProjectedSteepestEdgeRule *() - { - return _projectedSteepestEdgeRule; - } + operator IProjectedSteepestEdgeRule *() + { + return _projectedSteepestEdgeRule; + } - IProjectedSteepestEdgeRule *operator->() - { - return _projectedSteepestEdgeRule; - } + IProjectedSteepestEdgeRule *operator->() + { + return _projectedSteepestEdgeRule; + } - const IProjectedSteepestEdgeRule *operator->() const - { - return _projectedSteepestEdgeRule; - } + const IProjectedSteepestEdgeRule *operator->() const + { + return _projectedSteepestEdgeRule; + } private: - IProjectedSteepestEdgeRule *_projectedSteepestEdgeRule; + IProjectedSteepestEdgeRule *_projectedSteepestEdgeRule; }; #endif // __AutoProjectedSteepestEdge_h__ diff --git a/src/engine/AutoRowBoundTightener.h b/src/engine/AutoRowBoundTightener.h index 6f4615dcff..deb3b87088 100644 --- a/src/engine/AutoRowBoundTightener.h +++ b/src/engine/AutoRowBoundTightener.h @@ -25,8 +25,7 @@ class AutoRowBoundTightener AutoRowBoundTightener( const ITableau &tableau ) { _rowBoundTightener = T::createRowBoundTightener( tableau ); - tableau.getBoundManager().registerRowBoundTightener( - _rowBoundTightener ); + tableau.getBoundManager().registerRowBoundTightener( _rowBoundTightener ); } ~AutoRowBoundTightener() diff --git a/src/engine/AutoTableau.h b/src/engine/AutoTableau.h index 15558963b5..7061f9f85e 100644 --- a/src/engine/AutoTableau.h +++ b/src/engine/AutoTableau.h @@ -17,7 +17,6 @@ #define __AutoTableau_h__ #include "BoundManager.h" - #include "ITableau.h" #include "T/TableauFactory.h" diff --git a/src/engine/BilinearConstraint.cpp b/src/engine/BilinearConstraint.cpp index 4ce44e10fe..584b1c0c66 100644 --- a/src/engine/BilinearConstraint.cpp +++ b/src/engine/BilinearConstraint.cpp @@ -198,8 +198,8 @@ bool BilinearConstraint::satisfied() const double b2Value = getAssignment( _b2 ); double fValue = getAssignment( _f ); - return FloatUtils::areEqual( b1Value * b2Value, fValue, - GlobalConfiguration::CONSTRAINT_COMPARISON_TOLERANCE ); + return FloatUtils::areEqual( + b1Value * b2Value, fValue, GlobalConfiguration::CONSTRAINT_COMPARISON_TOLERANCE ); } String BilinearConstraint::serializeToString() const diff --git a/src/engine/BlandsRule.cpp b/src/engine/BlandsRule.cpp index 838cafd15c..98c645cc20 100644 --- a/src/engine/BlandsRule.cpp +++ b/src/engine/BlandsRule.cpp @@ -14,6 +14,7 @@ **/ #include "BlandsRule.h" + #include "ITableau.h" #include "MarabouError.h" diff --git a/src/engine/BlandsRule.h b/src/engine/BlandsRule.h index 37dd1f7ce0..3c384c9515 100644 --- a/src/engine/BlandsRule.h +++ b/src/engine/BlandsRule.h @@ -25,9 +25,8 @@ class BlandsRule : public EntrySelectionStrategy Apply Bland's rule: choose the candidate associated with the variable that has the smallest lexicographical index. */ - bool select( ITableau &tableau, - const List &candidates, - const Set &excluded ); + bool + select( ITableau &tableau, const List &candidates, const Set &excluded ); }; #endif // __BlandsRule_h__ diff --git a/src/engine/BoundManager.cpp b/src/engine/BoundManager.cpp index bc84185078..7b167778e0 100644 --- a/src/engine/BoundManager.cpp +++ b/src/engine/BoundManager.cpp @@ -18,9 +18,9 @@ #include "Debug.h" #include "FloatUtils.h" #include "InfeasibleQueryException.h" +#include "MarabouError.h" #include "Tableau.h" #include "Tightening.h" -#include "MarabouError.h" using namespace CVC4::context; @@ -96,10 +96,10 @@ void BoundManager::allocateLocalBounds( unsigned size ) _allocated = size; if ( _tableau ) - _tableau->setBoundsPointers( _lowerBounds, _upperBounds ); + _tableau->setBoundsPointers( _lowerBounds, _upperBounds ); if ( _rowBoundTightener ) - _rowBoundTightener->setBoundsPointers( _lowerBounds, _upperBounds ); + _rowBoundTightener->setBoundsPointers( _lowerBounds, _upperBounds ); } unsigned BoundManager::registerNewVariable() @@ -113,16 +113,16 @@ unsigned BoundManager::registerNewVariable() if ( _allocated < _size ) { - double * oldLowerBounds = _upperBounds; - double * oldUpperBounds = _lowerBounds; + double *oldLowerBounds = _upperBounds; + double *oldUpperBounds = _lowerBounds; - allocateLocalBounds( 2*_allocated ); - std::memcpy( _lowerBounds, oldLowerBounds, _allocated ); - std::memcpy( _upperBounds, oldUpperBounds, _allocated ); - _allocated *= 2; + allocateLocalBounds( 2 * _allocated ); + std::memcpy( _lowerBounds, oldLowerBounds, _allocated ); + std::memcpy( _upperBounds, oldUpperBounds, _allocated ); + _allocated *= 2; - delete[] oldLowerBounds; - delete[] oldUpperBounds; + delete[] oldLowerBounds; + delete[] oldUpperBounds; } _storedLowerBounds.append( new ( true ) CDO( &_context ) ); @@ -159,13 +159,15 @@ bool BoundManager::tightenUpperBound( unsigned variable, double value ) return tightened; } -void BoundManager::recordInconsistentBound( unsigned variable, double value, Tightening::BoundType type ) +void BoundManager::recordInconsistentBound( unsigned variable, + double value, + Tightening::BoundType type ) { - if ( _consistentBounds ) - { - _consistentBounds = false; - _firstInconsistentTightening = Tightening( variable, value, type ); - } + if ( _consistentBounds ) + { + _consistentBounds = false; + _firstInconsistentTightening = Tightening( variable, value, type ); + } } bool BoundManager::setLowerBound( unsigned variable, double value ) @@ -191,7 +193,7 @@ bool BoundManager::setUpperBound( unsigned variable, double value ) _upperBounds[variable] = value; *_tightenedUpper[variable] = true; if ( !consistentBounds( variable ) ) - recordInconsistentBound( variable, value, Tightening::UB ); + recordInconsistentBound( variable, value, Tightening::UB ); return true; } return false; @@ -209,12 +211,12 @@ double BoundManager::getUpperBound( unsigned variable ) const return _upperBounds[variable]; } -const double * BoundManager::getLowerBounds() const +const double *BoundManager::getLowerBounds() const { return _lowerBounds; } -const double * BoundManager::getUpperBounds() const +const double *BoundManager::getUpperBounds() const { return _upperBounds; } @@ -223,8 +225,8 @@ void BoundManager::storeLocalBounds() { for ( unsigned i = 0; i < _size; ++i ) { - *_storedLowerBounds[i]=_lowerBounds[i]; - *_storedUpperBounds[i]=_upperBounds[i]; + *_storedLowerBounds[i] = _lowerBounds[i]; + *_storedUpperBounds[i] = _upperBounds[i]; } } @@ -232,8 +234,8 @@ void BoundManager::restoreLocalBounds() { for ( unsigned i = 0; i < _size; ++i ) { - _lowerBounds[i]=*_storedLowerBounds[i]; - _upperBounds[i]=*_storedUpperBounds[i]; + _lowerBounds[i] = *_storedLowerBounds[i]; + _upperBounds[i] = *_storedUpperBounds[i]; } } @@ -259,8 +261,8 @@ void BoundManager::clearTightenings() { for ( unsigned i = 0; i < _size; ++i ) { - *_tightenedLower[i]=false; - *_tightenedUpper[i]=false; + *_tightenedLower[i] = false; + *_tightenedUpper[i] = false; } } @@ -268,17 +270,17 @@ void BoundManager::propagateTightenings() { for ( unsigned i = 0; i < _size; ++i ) { - if ( *_tightenedLower[i] ) - { - _tableau->notifyLowerBound( i, getLowerBound( i ) ); - *_tightenedLower[i] = false; - } + if ( *_tightenedLower[i] ) + { + _tableau->notifyLowerBound( i, getLowerBound( i ) ); + *_tightenedLower[i] = false; + } - if ( *_tightenedUpper[i] ) - { - _tableau->notifyUpperBound( i, getUpperBound( i ) ); - *_tightenedUpper[i] = false; - } + if ( *_tightenedUpper[i] ) + { + _tableau->notifyUpperBound( i, getUpperBound( i ) ); + *_tightenedUpper[i] = false; + } } } @@ -341,7 +343,9 @@ bool BoundManager::tightenUpperBound( unsigned variable, double value, const Tab return tightened; } -bool BoundManager::tightenLowerBound( unsigned variable, double value, const SparseUnsortedList &row ) +bool BoundManager::tightenLowerBound( unsigned variable, + double value, + const SparseUnsortedList &row ) { bool tightened = setLowerBound( variable, value ); @@ -356,7 +360,9 @@ bool BoundManager::tightenLowerBound( unsigned variable, double value, const Spa return tightened; } -bool BoundManager::tightenUpperBound( unsigned variable, double value, const SparseUnsortedList &row ) +bool BoundManager::tightenUpperBound( unsigned variable, + double value, + const SparseUnsortedList &row ) { bool tightened = setUpperBound( variable, value ); @@ -377,7 +383,9 @@ void BoundManager::resetExplanation( const unsigned var, const bool isUpper ) co _boundExplainer->resetExplanation( var, isUpper ); } -void BoundManager::setExplanation( const SparseUnsortedList &explanation, unsigned var, bool isUpper ) const +void BoundManager::setExplanation( const SparseUnsortedList &explanation, + unsigned var, + bool isUpper ) const { _boundExplainer->setExplanation( explanation, var, isUpper ); } @@ -397,14 +405,19 @@ void BoundManager::updateBoundExplanation( const TableauRow &row, bool isUpper, _boundExplainer->updateBoundExplanation( row, isUpper, var ); } -void BoundManager::updateBoundExplanationSparse( const SparseUnsortedList &row, bool isUpper, unsigned var ) +void BoundManager::updateBoundExplanationSparse( const SparseUnsortedList &row, + bool isUpper, + unsigned var ) { _boundExplainer->updateBoundExplanationSparse( row, isUpper, var ); } -bool BoundManager::addLemmaExplanationAndTightenBound( unsigned var, double value, BoundType affectedVarBound, - const List &causingVars, BoundType causingVarBound, - PiecewiseLinearFunctionType constraintType ) +bool BoundManager::addLemmaExplanationAndTightenBound( unsigned var, + double value, + BoundType affectedVarBound, + const List &causingVars, + BoundType causingVarBound, + PiecewiseLinearFunctionType constraintType ) { if ( !shouldProduceProofs() ) return false; @@ -414,7 +427,8 @@ bool BoundManager::addLemmaExplanationAndTightenBound( unsigned var, double valu // Register new ground bound, update certificate, and reset explanation Vector allExplanations( 0 ); - bool tightened = affectedVarBound == BoundType::UPPER ? tightenUpperBound( var, value ) : tightenLowerBound( var, value ); + bool tightened = affectedVarBound == BoundType::UPPER ? tightenUpperBound( var, value ) + : tightenLowerBound( var, value ); if ( tightened ) { @@ -431,11 +445,13 @@ bool BoundManager::addLemmaExplanationAndTightenBound( unsigned var, double valu { // Used for two cases: // 1. Lemma of the type _f = max(upperBound(b), -lowerBound(b)). - // Two explanations are stored so the checker could check that f has the maximal value of the two. + // Two explanations are stored so the checker could check that f has the maximal + // value of the two. // 2. Lemmas of the type lowerBound(f) > -lowerBound(b) or upperBound(b). // Again, two explanations are involved in the proof. // Add zero vectors to maintain consistency of explanations size - allExplanations.append( getExplanation( causingVars.front(), causingVarBound == BoundType::UPPER ) ); + allExplanations.append( + getExplanation( causingVars.front(), causingVarBound == BoundType::UPPER ) ); allExplanations.append( getExplanation( causingVars.back(), BoundType::LOWER ) ); } @@ -446,15 +462,22 @@ bool BoundManager::addLemmaExplanationAndTightenBound( unsigned var, double valu else throw MarabouError( MarabouError::FEATURE_NOT_YET_SUPPORTED ); - std::shared_ptr PLCExpl = std::make_shared( causingVars, var, value, causingVarBound, affectedVarBound, allExplanations, constraintType ); - _engine->getUNSATCertificateCurrentPointer()->addPLCLemma(PLCExpl ); - affectedVarBound == BoundType::UPPER ? _engine->updateGroundUpperBound( var, value ) : _engine->updateGroundLowerBound( var, value ); + std::shared_ptr PLCExpl = std::make_shared( causingVars, + var, + value, + causingVarBound, + affectedVarBound, + allExplanations, + constraintType ); + _engine->getUNSATCertificateCurrentPointer()->addPLCLemma( PLCExpl ); + affectedVarBound == BoundType::UPPER ? _engine->updateGroundUpperBound( var, value ) + : _engine->updateGroundLowerBound( var, value ); resetExplanation( var, affectedVarBound ); } return true; } -void BoundManager::registerEngine( IEngine *engine) +void BoundManager::registerEngine( IEngine *engine ) { _engine = engine; } @@ -484,7 +507,10 @@ double BoundManager::computeRowBound( const TableauRow &row, const bool isUpper if ( FloatUtils::isZero( row[i] ) ) continue; - multiplier = ( isUpper && FloatUtils::isPositive( row[i] ) ) || ( !isUpper && FloatUtils::isNegative( row[i] ) ) ? _upperBounds[var] : _lowerBounds[var]; + multiplier = ( isUpper && FloatUtils::isPositive( row[i] ) ) || + ( !isUpper && FloatUtils::isNegative( row[i] ) ) + ? _upperBounds[var] + : _lowerBounds[var]; multiplier = FloatUtils::isZero( multiplier ) ? 0 : multiplier * row[i]; bound += FloatUtils::isZero( multiplier ) ? 0 : multiplier; } @@ -493,7 +519,9 @@ double BoundManager::computeRowBound( const TableauRow &row, const bool isUpper return bound; } -double BoundManager::computeSparseRowBound( const SparseUnsortedList &row, const bool isUpper, const unsigned var ) const +double BoundManager::computeSparseRowBound( const SparseUnsortedList &row, + const bool isUpper, + const unsigned var ) const { ASSERT( !row.empty() && var < _size ); @@ -528,7 +556,9 @@ double BoundManager::computeSparseRowBound( const SparseUnsortedList &row, const if ( FloatUtils::isZero( realCoefficient ) ) continue; - multiplier = ( isUpper && realCoefficient > 0 ) || ( !isUpper && realCoefficient < 0 ) ? _upperBounds[curVar] : _lowerBounds[curVar]; + multiplier = ( isUpper && realCoefficient > 0 ) || ( !isUpper && realCoefficient < 0 ) + ? _upperBounds[curVar] + : _lowerBounds[curVar]; multiplier = FloatUtils::isZero( multiplier ) ? 0 : multiplier * realCoefficient; bound += FloatUtils::isZero( multiplier ) ? 0 : multiplier; } diff --git a/src/engine/BoundManager.h b/src/engine/BoundManager.h index ceff107f89..54aabe4783 100644 --- a/src/engine/BoundManager.h +++ b/src/engine/BoundManager.h @@ -39,17 +39,17 @@ #ifndef __BoundManager_h__ #define __BoundManager_h__ -#include "context/cdo.h" -#include "context/context.h" #include "IBoundManager.h" +#include "IEngine.h" #include "IRowBoundTightener.h" #include "ITableau.h" -#include "IEngine.h" #include "List.h" #include "PlcLemma.h" #include "Tightening.h" #include "UnsatCertificateNode.h" #include "Vector.h" +#include "context/cdo.h" +#include "context/context.h" class ITableau; class IEngine; @@ -98,8 +98,8 @@ class BoundManager : public IBoundManager /* Get pointers to latest bounds used for access by tableau and tighteners */ - const double * getLowerBounds() const; - const double * getUpperBounds() const; + const double *getLowerBounds() const; + const double *getUpperBounds() const; /* Store and restore local bounds after context advances/backtracks. @@ -145,7 +145,8 @@ class BoundManager : public IBoundManager void registerRowBoundTightener( IRowBoundTightener *ptrRowBoundTightener ); /* - Return the content of the object containing all explanations for variable bounds in the tableau. + Return the content of the object containing all explanations for variable bounds in the + tableau. */ const BoundExplainer *getBoundExplainer() const; @@ -165,7 +166,8 @@ class BoundManager : public IBoundManager void updateBoundExplanation( const TableauRow &row, bool isUpper, unsigned var ); /* - Given a row as SparseUnsortedList, updates the values of the bound explanations of a var according to the row + Given a row as SparseUnsortedList, updates the values of the bound explanations of a var + according to the row */ void updateBoundExplanationSparse( const SparseUnsortedList &row, bool isUpper, unsigned var ); @@ -182,12 +184,12 @@ class BoundManager : public IBoundManager /* Artificially update an explanation, without using the recursive rule */ - void setExplanation( const SparseUnsortedList &explanation, unsigned var, bool isUpper ) const; + void setExplanation( const SparseUnsortedList &explanation, unsigned var, bool isUpper ) const; /* Register Engine pointer for callbacks */ - void registerEngine( IEngine *engine); + void registerEngine( IEngine *engine ); /* Get the index of a variable with inconsistent bounds, if exists, or -1 otherwise @@ -218,15 +220,15 @@ class BoundManager : public IBoundManager CVC4::context::Context &_context; unsigned _size; unsigned _allocated; - ITableau *_tableau; // Used only by callbacks + ITableau *_tableau; // Used only by callbacks IRowBoundTightener *_rowBoundTightener; // Used only by callbacks IEngine *_engine; CVC4::context::CDO _consistentBounds; Tightening _firstInconsistentTightening; - double * _lowerBounds; - double * _upperBounds; + double *_lowerBounds; + double *_upperBounds; Vector *> _storedLowerBounds; Vector *> _storedUpperBounds; @@ -253,9 +255,12 @@ class BoundManager : public IBoundManager /* Adds a lemma to the UNSATCertificateNode object */ - bool addLemmaExplanationAndTightenBound( unsigned var, double value, BoundType affectedVarBound, - const List &causingVars, BoundType causingVarBound, - PiecewiseLinearFunctionType constraintType ); + bool addLemmaExplanationAndTightenBound( unsigned var, + double value, + BoundType affectedVarBound, + const List &causingVars, + BoundType causingVarBound, + PiecewiseLinearFunctionType constraintType ); /* Explainer of all bounds diff --git a/src/engine/CDSmtCore.cpp b/src/engine/CDSmtCore.cpp index 46888c1b57..44dd5209e0 100644 --- a/src/engine/CDSmtCore.cpp +++ b/src/engine/CDSmtCore.cpp @@ -35,10 +35,8 @@ CDSmtCore::CDSmtCore( IEngine *engine, Context &ctx ) , _engine( engine ) , _needToSplit( false ) , _constraintForSplitting( NULL ) - , _constraintViolationThreshold - ( Options::CONSTRAINT_VIOLATION_THRESHOLD ) - , _deepSoIRejectionThreshold( Options::get()->getInt - ( Options::DEEP_SOI_REJECTION_THRESHOLD ) ) + , _constraintViolationThreshold( Options::CONSTRAINT_VIOLATION_THRESHOLD ) + , _deepSoIRejectionThreshold( Options::get()->getInt( Options::DEEP_SOI_REJECTION_THRESHOLD ) ) , _branchingHeuristic( Options::get()->getDivideStrategy() ) , _scoreTracker( nullptr ) , _numRejectedPhasePatternProposal( 0 ) @@ -58,12 +56,11 @@ void CDSmtCore::reportViolatedConstraint( PiecewiseLinearConstraint *constraint ++_constraintToViolationCount[constraint]; - if ( _constraintToViolationCount[constraint] >= - _constraintViolationThreshold ) + if ( _constraintToViolationCount[constraint] >= _constraintViolationThreshold ) { _needToSplit = true; - if ( GlobalConfiguration::SPLITTING_HEURISTICS == - DivideStrategy::ReLUViolation || !pickSplitPLConstraint() ) + if ( GlobalConfiguration::SPLITTING_HEURISTICS == DivideStrategy::ReLUViolation || + !pickSplitPLConstraint() ) // If pickSplitConstraint failed to pick one, use the native // relu-violation based splitting heuristic. _constraintForSplitting = constraint; @@ -79,33 +76,30 @@ unsigned CDSmtCore::getViolationCounts( PiecewiseLinearConstraint *constraint ) return _constraintToViolationCount[constraint]; } -void CDSmtCore::initializeScoreTrackerIfNeeded( const - List - &plConstraints ) +void CDSmtCore::initializeScoreTrackerIfNeeded( + const List &plConstraints ) { if ( GlobalConfiguration::USE_DEEPSOI_LOCAL_SEARCH ) - { - _scoreTracker = std::unique_ptr - ( new PseudoImpactTracker() ); - _scoreTracker->initialize( plConstraints ); + { + _scoreTracker = std::unique_ptr( new PseudoImpactTracker() ); + _scoreTracker->initialize( plConstraints ); - SMT_LOG( "\tTracking Pseudo Impact..." ); - } + SMT_LOG( "\tTracking Pseudo Impact..." ); + } } void CDSmtCore::reportRejectedPhasePatternProposal() { ++_numRejectedPhasePatternProposal; - if ( _numRejectedPhasePatternProposal >= - _deepSoIRejectionThreshold ) - { - _needToSplit = true; - if ( !pickSplitPLConstraint() ) - // If pickSplitConstraint failed to pick one, use the native - // relu-violation based splitting heuristic. - _constraintForSplitting = _scoreTracker->topUnfixed(); - } + if ( _numRejectedPhasePatternProposal >= _deepSoIRejectionThreshold ) + { + _needToSplit = true; + if ( !pickSplitPLConstraint() ) + // If pickSplitConstraint failed to pick one, use the native + // relu-violation based splitting heuristic. + _constraintForSplitting = _scoreTracker->topUnfixed(); + } } bool CDSmtCore::needToSplit() const @@ -113,7 +107,7 @@ bool CDSmtCore::needToSplit() const return _needToSplit; } -void CDSmtCore::pushDecision( PiecewiseLinearConstraint *constraint, PhaseStatus decision ) +void CDSmtCore::pushDecision( PiecewiseLinearConstraint *constraint, PhaseStatus decision ) { SMT_LOG( Stringf( "Decision @ %d )", _context.getLevel() + 1 ).ascii() ); TrailEntry te( constraint, decision ); @@ -188,15 +182,13 @@ void CDSmtCore::decideSplit( PiecewiseLinearConstraint *constraint ) if ( _statistics ) { unsigned level = _context.getLevel(); - _statistics->setUnsignedAttribute( Statistics::CURRENT_DECISION_LEVEL, - level ); - if ( level > _statistics->getUnsignedAttribute - ( Statistics::MAX_DECISION_LEVEL ) ) - _statistics->setUnsignedAttribute( Statistics::MAX_DECISION_LEVEL, - level ); + _statistics->setUnsignedAttribute( Statistics::CURRENT_DECISION_LEVEL, level ); + if ( level > _statistics->getUnsignedAttribute( Statistics::MAX_DECISION_LEVEL ) ) + _statistics->setUnsignedAttribute( Statistics::MAX_DECISION_LEVEL, level ); struct timespec end = TimeUtils::sampleMicro(); - _statistics->incLongAttribute( Statistics::TOTAL_TIME_SMT_CORE_MICRO, TimeUtils::timePassed( start, end ) ); + _statistics->incLongAttribute( Statistics::TOTAL_TIME_SMT_CORE_MICRO, + TimeUtils::timePassed( start, end ) ); } SMT_LOG( "Performing a ReLU split - DONE" ); } @@ -209,7 +201,7 @@ unsigned CDSmtCore::getDecisionLevel() const bool CDSmtCore::popDecisionLevel( TrailEntry &lastDecision ) { - //ASSERT( static_cast( _context.getLevel() ) == _decisions.size() ); + // ASSERT( static_cast( _context.getLevel() ) == _decisions.size() ); if ( _decisions.empty() ) return false; @@ -284,14 +276,12 @@ bool CDSmtCore::backtrackAndContinueSearch() if ( _statistics ) { unsigned level = _context.getLevel(); - _statistics->setUnsignedAttribute( Statistics::CURRENT_DECISION_LEVEL, - level ); - if ( level > _statistics->getUnsignedAttribute - ( Statistics::MAX_DECISION_LEVEL ) ) - _statistics->setUnsignedAttribute( Statistics::MAX_DECISION_LEVEL, - level ); + _statistics->setUnsignedAttribute( Statistics::CURRENT_DECISION_LEVEL, level ); + if ( level > _statistics->getUnsignedAttribute( Statistics::MAX_DECISION_LEVEL ) ) + _statistics->setUnsignedAttribute( Statistics::MAX_DECISION_LEVEL, level ); struct timespec end = TimeUtils::sampleMicro(); - _statistics->incLongAttribute( Statistics::TOTAL_TIME_SMT_CORE_MICRO, TimeUtils::timePassed( start, end ) ); + _statistics->incLongAttribute( Statistics::TOTAL_TIME_SMT_CORE_MICRO, + TimeUtils::timePassed( start, end ) ); } checkSkewFromDebuggingSolution(); @@ -351,7 +341,8 @@ bool CDSmtCore::checkSkewFromDebuggingSolution() { if ( !splitAllowsStoredSolution( caseSplit, error ) ) { - printf( "Error with one of the splits implied at root level:\n\t%s\n", error.ascii() ); + printf( "Error with one of the splits implied at root level:\n\t%s\n", + error.ascii() ); throw MarabouError( MarabouError::DEBUGGING_ERROR ); } } @@ -381,7 +372,8 @@ bool CDSmtCore::checkSkewFromDebuggingSolution() return true; } -bool CDSmtCore::splitAllowsStoredSolution( const PiecewiseLinearCaseSplit &split, String &error ) const +bool CDSmtCore::splitAllowsStoredSolution( const PiecewiseLinearCaseSplit &split, + String &error ) const { // False if the split prevents one of the values in the stored solution, true otherwise. error = ""; @@ -403,18 +395,20 @@ bool CDSmtCore::splitAllowsStoredSolution( const PiecewiseLinearCaseSplit &split if ( ( bound._type == Tightening::LB ) && FloatUtils::gt( boundValue, solutionValue ) ) { - error = Stringf( "Variable %u: new LB is %.5lf, which contradicts possible solution %.5lf", - variable, - boundValue, - solutionValue ); + error = + Stringf( "Variable %u: new LB is %.5lf, which contradicts possible solution %.5lf", + variable, + boundValue, + solutionValue ); return false; } else if ( ( bound._type == Tightening::UB ) && FloatUtils::lt( boundValue, solutionValue ) ) { - error = Stringf( "Variable %u: new UB is %.5lf, which contradicts possible solution %.5lf", - variable, - boundValue, - solutionValue ); + error = + Stringf( "Variable %u: new UB is %.5lf, which contradicts possible solution %.5lf", + variable, + boundValue, + solutionValue ); return false; } } @@ -427,7 +421,8 @@ void CDSmtCore::setConstraintViolationThreshold( unsigned threshold ) _constraintViolationThreshold = threshold; } -PiecewiseLinearConstraint *CDSmtCore::chooseViolatedConstraintForFixing( List &_violatedPlConstraints ) const +PiecewiseLinearConstraint *CDSmtCore::chooseViolatedConstraintForFixing( + List &_violatedPlConstraints ) const { ASSERT( !_violatedPlConstraints.empty() ); @@ -463,8 +458,7 @@ PiecewiseLinearConstraint *CDSmtCore::chooseViolatedConstraintForFixing( ListpickSplitPLConstraint - ( _branchingHeuristic ); + _constraintForSplitting = _engine->pickSplitPLConstraint( _branchingHeuristic ); return _constraintForSplitting != NULL; } diff --git a/src/engine/CDSmtCore.h b/src/engine/CDSmtCore.h index 31dedf9813..14e6715543 100644 --- a/src/engine/CDSmtCore.h +++ b/src/engine/CDSmtCore.h @@ -67,9 +67,9 @@ #define __CDSmtCore_h__ #include "Options.h" +#include "PLConstraintScoreTracker.h" #include "PiecewiseLinearCaseSplit.h" #include "PiecewiseLinearConstraint.h" -#include "PLConstraintScoreTracker.h" #include "Stack.h" #include "Statistics.h" #include "TrailEntry.h" @@ -96,8 +96,7 @@ class CDSmtCore /* Initialize the score tracker with the given list of pl constraints. */ - void initializeScoreTrackerIfNeeded( const List - &plConstraints ); + void initializeScoreTrackerIfNeeded( const List &plConstraints ); /* Inform the SMT core that a SoI phase pattern proposal is rejected. @@ -107,8 +106,7 @@ class CDSmtCore /* Update the score of the constraint with the given score in the costTracker. */ - inline void updatePLConstraintScore( PiecewiseLinearConstraint *constraint, - double score ) + inline void updatePLConstraintScore( PiecewiseLinearConstraint *constraint, double score ) { ASSERT( _scoreTracker != nullptr ); _scoreTracker->updateScore( constraint, score ); @@ -146,7 +144,7 @@ class CDSmtCore /* Push TrailEntry representing the decision onto the trail. */ - void pushDecision( PiecewiseLinearConstraint *constraint, PhaseStatus decision ); + void pushDecision( PiecewiseLinearConstraint *constraint, PhaseStatus decision ); /* Inform SmtCore of an implied (formerly valid) case split that was discovered. @@ -228,7 +226,8 @@ class CDSmtCore Have the SMT core choose, among a set of violated PL constraints, which constraint should be repaired (without splitting) */ - PiecewiseLinearConstraint *chooseViolatedConstraintForFixing( List &_violatedPlConstraints ) const; + PiecewiseLinearConstraint *chooseViolatedConstraintForFixing( + List &_violatedPlConstraints ) const; void setConstraintViolationThreshold( unsigned threshold ); @@ -258,6 +257,7 @@ class CDSmtCore bool checkSkewFromDebuggingSolution(); bool splitAllowsStoredSolution( const PiecewiseLinearCaseSplit &split, String &error ) const; void interruptIfCompliantWithDebugSolution(); + private: /* Collect and print various statistics. @@ -327,7 +327,6 @@ class CDSmtCore current search state. */ unsigned _numRejectedPhasePatternProposal; - }; #endif // __CDSmtCore_h__ diff --git a/src/engine/ConstraintMatrixAnalyzer.cpp b/src/engine/ConstraintMatrixAnalyzer.cpp index f941dde378..fb28e832db 100644 --- a/src/engine/ConstraintMatrixAnalyzer.cpp +++ b/src/engine/ConstraintMatrixAnalyzer.cpp @@ -14,6 +14,7 @@ **/ #include "ConstraintMatrixAnalyzer.h" + #include "FloatUtils.h" #include "List.h" #include "MStringf.h" @@ -103,9 +104,7 @@ void ConstraintMatrixAnalyzer::analyze( const double *matrix, unsigned m, unsign gaussianElimination(); } -void ConstraintMatrixAnalyzer::analyze( const SparseUnsortedList **matrix, - unsigned m, - unsigned n ) +void ConstraintMatrixAnalyzer::analyze( const SparseUnsortedList **matrix, unsigned m, unsigned n ) { freeMemoryIfNeeded(); diff --git a/src/engine/CostFunctionManager.cpp b/src/engine/CostFunctionManager.cpp index 2cb7fda9cb..9ea4c6582f 100644 --- a/src/engine/CostFunctionManager.cpp +++ b/src/engine/CostFunctionManager.cpp @@ -14,6 +14,7 @@ **/ #include "CostFunctionManager.h" + #include "Debug.h" #include "FloatUtils.h" #include "ITableau.h" @@ -117,8 +118,7 @@ void CostFunctionManager::computeCostFunction( const Map &heur computeReducedCosts(); } -void CostFunctionManager::computeGivenCostFunction( const Map - &heuristicCost ) +void CostFunctionManager::computeGivenCostFunction( const Map &heuristicCost ) { /* The heuristic cost may include variables that are basic and variables @@ -155,15 +155,15 @@ void CostFunctionManager::computeGivenCostFunction( const Map _costFunctionStatus = ICostFunctionManager::COST_FUNCTION_JUST_COMPUTED; } -double CostFunctionManager::computeGivenCostFunctionDirectly( const Map - &heuristicCost ) +double +CostFunctionManager::computeGivenCostFunctionDirectly( const Map &heuristicCost ) { double cost = 0; for ( const auto &pair : heuristicCost ) - { - double value = _tableau->getValue( pair.first ); - cost += pair.second * value; - } + { + double value = _tableau->getValue( pair.first ); + cost += pair.second * value; + } return cost; } @@ -218,10 +218,9 @@ void CostFunctionManager::adjustBasicCostAccuracy() if ( _basicCosts[i] < 0 ) { lb = _tableau->getLowerBound( variable ); - relaxedLb = - lb - - ( GlobalConfiguration::BASIC_COSTS_ADDITIVE_TOLERANCE + - GlobalConfiguration::BASIC_COSTS_MULTIPLICATIVE_TOLERANCE * FloatUtils::abs( lb ) ); + relaxedLb = lb - ( GlobalConfiguration::BASIC_COSTS_ADDITIVE_TOLERANCE + + GlobalConfiguration::BASIC_COSTS_MULTIPLICATIVE_TOLERANCE * + FloatUtils::abs( lb ) ); // Current basic cost is negative, assignment should be too small if ( assignment >= relaxedLb ) @@ -233,10 +232,9 @@ void CostFunctionManager::adjustBasicCostAccuracy() else if ( _basicCosts[i] > 0 ) { ub = _tableau->getUpperBound( variable ); - relaxedUb = - ub + - ( GlobalConfiguration::BASIC_COSTS_ADDITIVE_TOLERANCE + - GlobalConfiguration::BASIC_COSTS_MULTIPLICATIVE_TOLERANCE * FloatUtils::abs( ub ) ); + relaxedUb = ub + ( GlobalConfiguration::BASIC_COSTS_ADDITIVE_TOLERANCE + + GlobalConfiguration::BASIC_COSTS_MULTIPLICATIVE_TOLERANCE * + FloatUtils::abs( ub ) ); // Current basic cost is positive, assignment should be too large if ( assignment <= relaxedUb ) @@ -252,7 +250,6 @@ void CostFunctionManager::adjustBasicCostAccuracy() 1 or -1, but apparently this leads to cycling. */ } - } if ( needToRecompute ) @@ -274,10 +271,9 @@ void CostFunctionManager::computeBasicOOBCosts() assignment = _tableau->getBasicAssignment( i ); lb = _tableau->getLowerBound( variable ); - relaxedLb = - lb - - ( GlobalConfiguration::BASIC_COSTS_ADDITIVE_TOLERANCE + - GlobalConfiguration::BASIC_COSTS_MULTIPLICATIVE_TOLERANCE * FloatUtils::abs( lb ) ); + relaxedLb = lb - ( GlobalConfiguration::BASIC_COSTS_ADDITIVE_TOLERANCE + + GlobalConfiguration::BASIC_COSTS_MULTIPLICATIVE_TOLERANCE * + FloatUtils::abs( lb ) ); if ( assignment < relaxedLb ) { @@ -286,10 +282,9 @@ void CostFunctionManager::computeBasicOOBCosts() } ub = _tableau->getUpperBound( variable ); - relaxedUb = - ub + - ( GlobalConfiguration::BASIC_COSTS_ADDITIVE_TOLERANCE + - GlobalConfiguration::BASIC_COSTS_MULTIPLICATIVE_TOLERANCE * FloatUtils::abs( ub ) ); + relaxedUb = ub + ( GlobalConfiguration::BASIC_COSTS_ADDITIVE_TOLERANCE + + GlobalConfiguration::BASIC_COSTS_MULTIPLICATIVE_TOLERANCE * + FloatUtils::abs( ub ) ); if ( assignment > relaxedUb ) { @@ -358,8 +353,7 @@ double CostFunctionManager::updateCostFunctionForPivot( unsigned enteringVariabl unsigned leavingVariableIndex, double pivotElement, const TableauRow *pivotRow, - const double *changeColumn - ) + const double *changeColumn ) { /* This method is invoked when the non-basic _enteringVariable and @@ -403,7 +397,7 @@ double CostFunctionManager::updateCostFunctionForPivot( unsigned enteringVariabl for ( unsigned i = 0; i < _n - _m; ++i ) { if ( i != enteringVariableIndex ) - _costFunction[i] -= (*pivotRow)[i] * _costFunction[enteringVariableIndex]; + _costFunction[i] -= ( *pivotRow )[i] * _costFunction[enteringVariableIndex]; } /* @@ -439,13 +433,16 @@ double CostFunctionManager::getBasicCost( unsigned basicIndex ) const return _basicCosts[basicIndex]; } -const SparseUnsortedList* CostFunctionManager::createRowOfCostFunction() const +const SparseUnsortedList *CostFunctionManager::createRowOfCostFunction() const { - SparseUnsortedList* costRow = new SparseUnsortedList( 0 ); + SparseUnsortedList *costRow = new SparseUnsortedList( 0 ); for ( unsigned i = 0; i < _m; ++i ) if ( !FloatUtils::isZero( _basicCosts[i] ) ) { - costRow->append( _tableau->basicIndexToVariable( i ), -_basicCosts[i] ); //Minus sign since we are used to think about basics in lhs (while the row has all variables in rhs). + costRow->append( _tableau->basicIndexToVariable( i ), + -_basicCosts[i] ); // Minus sign since we are used to think about + // basics in lhs (while the row has all variables in + // rhs). costRow->incrementSize(); } diff --git a/src/engine/CostFunctionManager.h b/src/engine/CostFunctionManager.h index 56359e19d7..8ed7acaf21 100644 --- a/src/engine/CostFunctionManager.h +++ b/src/engine/CostFunctionManager.h @@ -50,8 +50,7 @@ class CostFunctionManager : public ICostFunctionManager Directly compute the given heuristicCost with respect to the current assignment in the tableau. */ - double computeGivenCostFunctionDirectly( const Map - &heuristicCost ); + double computeGivenCostFunctionDirectly( const Map &heuristicCost ); /* Get the current cost function. @@ -94,9 +93,11 @@ class CostFunctionManager : public ICostFunctionManager void dumpCostFunction() const; /* - Returns the cost function as a SparseUnsortedList object, so it can be viewed as a Tableau row. + Returns the cost function as a SparseUnsortedList object, so it can be viewed as a Tableau + row. */ - const SparseUnsortedList* createRowOfCostFunction() const; + const SparseUnsortedList *createRowOfCostFunction() const; + private: /* The tableau. diff --git a/src/engine/DantzigsRule.cpp b/src/engine/DantzigsRule.cpp index 717e4fb9d6..fb952f4f61 100644 --- a/src/engine/DantzigsRule.cpp +++ b/src/engine/DantzigsRule.cpp @@ -14,6 +14,7 @@ **/ #include "DantzigsRule.h" + #include "FloatUtils.h" #include "ITableau.h" #include "MStringf.h" @@ -50,7 +51,7 @@ bool DantzigsRule::select( ITableau &tableau, continue; if ( FloatUtils::isPositive( costFunction[i] ) ) - cost += "+"; + cost += "+"; cost += Stringf( "%.3lf*nb[%u] ", costFunction[i], i ); } DANTZIG_LOG( Stringf( "Cost function: %s\n", cost.ascii() ).ascii() ); @@ -71,7 +72,9 @@ bool DantzigsRule::select( ITableau &tableau, ++candidate; } - DANTZIG_LOG( Stringf( "Largest coefficient: %.3lf. Corresponding variable: %u\n", maxValue, maxIndex ).ascii() ); + DANTZIG_LOG( + Stringf( "Largest coefficient: %.3lf. Corresponding variable: %u\n", maxValue, maxIndex ) + .ascii() ); tableau.setEnteringVariableIndex( maxIndex ); return true; diff --git a/src/engine/DantzigsRule.h b/src/engine/DantzigsRule.h index 5dc01ee024..5d3330f6ef 100644 --- a/src/engine/DantzigsRule.h +++ b/src/engine/DantzigsRule.h @@ -18,7 +18,8 @@ #include "EntrySelectionStrategy.h" -#define DANTZIG_LOG( x, ... ) LOG( GlobalConfiguration::DANTZIGS_RULE_LOGGING, "DantzigsRule: %s\n", x ) +#define DANTZIG_LOG( x, ... ) \ + LOG( GlobalConfiguration::DANTZIGS_RULE_LOGGING, "DantzigsRule: %s\n", x ) class String; @@ -29,9 +30,8 @@ class DantzigsRule : public EntrySelectionStrategy Apply Dantzig's rule: choose the candidate associated with the largest coefficient (in absolute value) in the cost function. */ - bool select( ITableau &tableau, - const List &candidates, - const Set &excluded ); + bool + select( ITableau &tableau, const List &candidates, const Set &excluded ); }; #endif // __DantzigsRule_h__ diff --git a/src/engine/DegradationChecker.cpp b/src/engine/DegradationChecker.cpp index 2ad4a83de1..80f1f8a6c0 100644 --- a/src/engine/DegradationChecker.cpp +++ b/src/engine/DegradationChecker.cpp @@ -14,6 +14,7 @@ **/ #include "DegradationChecker.h" + #include "FloatUtils.h" #include "InputQuery.h" diff --git a/src/engine/DisjunctionConstraint.cpp b/src/engine/DisjunctionConstraint.cpp index d44b097338..a8cfbab6b4 100644 --- a/src/engine/DisjunctionConstraint.cpp +++ b/src/engine/DisjunctionConstraint.cpp @@ -46,28 +46,28 @@ DisjunctionConstraint::DisjunctionConstraint( const Vector disjuncts; - String serializedValues = serializedDisjunction.substring - ( 5, serializedDisjunction.length() - 5 ); + String serializedValues = + serializedDisjunction.substring( 5, serializedDisjunction.length() - 5 ); List values = serializedValues.tokenize( "," ); auto val = values.begin(); - unsigned numDisjuncts = atoi(val->ascii()); + unsigned numDisjuncts = atoi( val->ascii() ); ++val; for ( unsigned i = 0; i < numDisjuncts; ++i ) { PiecewiseLinearCaseSplit split; - unsigned numBounds = atoi(val->ascii()); + unsigned numBounds = atoi( val->ascii() ); ++val; for ( unsigned bi = 0; bi < numBounds; ++bi ) { - Tightening::BoundType type = ( *val == "l") ? Tightening::LB : Tightening::UB; + Tightening::BoundType type = ( *val == "l" ) ? Tightening::LB : Tightening::UB; ++val; - unsigned var = atoi(val->ascii()); + unsigned var = atoi( val->ascii() ); ++val; - double bd = atof(val->ascii()); + double bd = atof( val->ascii() ); ++val; - split.storeBoundTightening( Tightening(var, bd, type) ); + split.storeBoundTightening( Tightening( var, bd, type ) ); } - unsigned numEquations = atoi(val->ascii()); + unsigned numEquations = atoi( val->ascii() ); ++val; for ( unsigned ei = 0; ei < numEquations; ++ei ) @@ -79,29 +79,29 @@ DisjunctionConstraint::DisjunctionConstraint( const String &serializedDisjunctio type = Equation::GE; else { - ASSERT( *val == "e"); + ASSERT( *val == "e" ); } - Equation eq(type); + Equation eq( type ); ++val; - unsigned numAddends = atoi(val->ascii()); + unsigned numAddends = atoi( val->ascii() ); ++val; for ( unsigned ai = 0; ai < numAddends; ++ai ) { - double coef = atof(val->ascii()); + double coef = atof( val->ascii() ); ++val; - unsigned var = atoi(val->ascii()); + unsigned var = atoi( val->ascii() ); ++val; eq.addAddend( coef, var ); } - eq.setScalar(atof(val->ascii())); + eq.setScalar( atof( val->ascii() ) ); ++val; - split.addEquation(eq); + split.addEquation( eq ); } - disjuncts.append(split); + disjuncts.append( split ); } _disjuncts = disjuncts; - for ( unsigned ind = 0; ind < disjuncts.size(); ++ind ) + for ( unsigned ind = 0; ind < disjuncts.size(); ++ind ) _feasibleDisjuncts.append( ind ); extractParticipatingVariables(); @@ -152,7 +152,7 @@ void DisjunctionConstraint::notifyLowerBound( unsigned variable, double bound ) if ( _boundManager == nullptr && existsLowerBound( variable ) && !FloatUtils::gt( bound, getLowerBound( variable ) ) ) - return; + return; setLowerBound( variable, bound ); @@ -166,7 +166,7 @@ void DisjunctionConstraint::notifyUpperBound( unsigned variable, double bound ) if ( _boundManager == nullptr && existsUpperBound( variable ) && !FloatUtils::lt( bound, getUpperBound( variable ) ) ) - return; + return; setUpperBound( variable, bound ); @@ -204,7 +204,8 @@ List DisjunctionConstraint::getPossibleFixes() c return List(); } -List DisjunctionConstraint::getSmartFixes( ITableau */* tableau */ ) const +List +DisjunctionConstraint::getSmartFixes( ITableau * /* tableau */ ) const { // Reluplex does not currently work with Gurobi. ASSERT( _gurobi == NULL ); @@ -245,8 +246,7 @@ PiecewiseLinearCaseSplit DisjunctionConstraint::getValidCaseSplit() const return getImpliedCaseSplit(); } -void DisjunctionConstraint::transformToUseAuxVariables( InputQuery - &inputQuery ) +void DisjunctionConstraint::transformToUseAuxVariables( InputQuery &inputQuery ) { Vector newDisjuncts; for ( const auto &disjunct : _disjuncts ) @@ -295,23 +295,21 @@ void DisjunctionConstraint::transformToUseAuxVariables( InputQuery switch ( equation._type ) { - case Equation::EQ: - { - ASSERT( false ); - break; - } - case Equation::GE: - { - newDisjunct.storeBoundTightening - ( Tightening( aux, 0, Tightening::UB ) ); - break; - } - case Equation::LE: - { - newDisjunct.storeBoundTightening - ( Tightening( aux, 0, Tightening::LB ) ); - break; - } + case Equation::EQ: + { + ASSERT( false ); + break; + } + case Equation::GE: + { + newDisjunct.storeBoundTightening( Tightening( aux, 0, Tightening::UB ) ); + break; + } + case Equation::LE: + { + newDisjunct.storeBoundTightening( Tightening( aux, 0, Tightening::LB ) ); + break; + } } } newDisjuncts.append( newDisjunct ); @@ -398,32 +396,32 @@ void DisjunctionConstraint::getEntailedTightenings( List &tightening String DisjunctionConstraint::serializeToString() const { String s = "disj,"; - s += Stringf("%u,", _disjuncts.size()); + s += Stringf( "%u,", _disjuncts.size() ); for ( const auto &disjunct : _disjuncts ) { - s += Stringf("%u,", disjunct.getBoundTightenings().size()); + s += Stringf( "%u,", disjunct.getBoundTightenings().size() ); for ( const auto &bound : disjunct.getBoundTightenings() ) { if ( bound._type == Tightening::LB ) - s += Stringf("l,%u,%f,", bound._variable, bound._value); + s += Stringf( "l,%u,%f,", bound._variable, bound._value ); else if ( bound._type == Tightening::UB ) - s += Stringf("u,%u,%f,", bound._variable, bound._value); + s += Stringf( "u,%u,%f,", bound._variable, bound._value ); } - s += Stringf("%u,", disjunct.getEquations().size()); + s += Stringf( "%u,", disjunct.getEquations().size() ); for ( const auto &equation : disjunct.getEquations() ) { if ( equation._type == Equation::LE ) - s += Stringf("l,"); + s += Stringf( "l," ); else if ( equation._type == Equation::GE ) - s += Stringf("g,"); + s += Stringf( "g," ); else - s += Stringf("e,"); - s += Stringf("%u,", equation._addends.size()); + s += Stringf( "e," ); + s += Stringf( "%u,", equation._addends.size() ); for ( const auto &addend : equation._addends ) { - s += Stringf("%f,%u,", addend._coefficient, addend._variable); + s += Stringf( "%f,%u,", addend._coefficient, addend._variable ); } - s += Stringf("%f,", equation._scalar ); + s += Stringf( "%f,", equation._scalar ); } } return s; @@ -491,7 +489,8 @@ void DisjunctionConstraint::updateFeasibleDisjuncts() markInfeasible( indToPhaseStatus( ind ) ); } - if ( _feasibleDisjuncts.size() == 0 ) throw InfeasibleQueryException(); + if ( _feasibleDisjuncts.size() == 0 ) + throw InfeasibleQueryException(); } bool DisjunctionConstraint::disjunctIsFeasible( unsigned ind ) const @@ -533,7 +532,7 @@ List DisjunctionConstraint::getFeasibleDisjuncts() con return validDisjuncts; } -bool DisjunctionConstraint::removeFeasibleDisjunct(const PiecewiseLinearCaseSplit &disjunct ) +bool DisjunctionConstraint::removeFeasibleDisjunct( const PiecewiseLinearCaseSplit &disjunct ) { for ( unsigned i = 0; i < _disjuncts.size(); ++i ) if ( _disjuncts[i] == disjunct ) @@ -558,7 +557,8 @@ bool DisjunctionConstraint::addFeasibleDisjunct( const PiecewiseLinearCaseSplit } // No aux vars in disjunction constraint, so the function is suppressed -void DisjunctionConstraint::addTableauAuxVar( unsigned /* tableauAuxVar */, unsigned /* constraintAuxVar */ ) +void DisjunctionConstraint::addTableauAuxVar( unsigned /* tableauAuxVar */, + unsigned /* constraintAuxVar */ ) { } diff --git a/src/engine/DisjunctionConstraint.h b/src/engine/DisjunctionConstraint.h index 9eab5ab232..002306bdc7 100644 --- a/src/engine/DisjunctionConstraint.h +++ b/src/engine/DisjunctionConstraint.h @@ -28,13 +28,13 @@ #ifndef __DisjunctionConstraint_h__ #define __DisjunctionConstraint_h__ -#include "Vector.h" #include "PiecewiseLinearConstraint.h" +#include "Vector.h" class DisjunctionConstraint : public PiecewiseLinearConstraint { public: - ~DisjunctionConstraint() {}; + ~DisjunctionConstraint(){}; DisjunctionConstraint( const List &disjuncts ); DisjunctionConstraint( const Vector &disjuncts ); DisjunctionConstraint( const String &serializedDisjunction ); @@ -153,7 +153,7 @@ class DisjunctionConstraint : public PiecewiseLinearConstraint virtual bool supportVariableElimination() const override { - return false; + return false; } /* @@ -224,7 +224,7 @@ class DisjunctionConstraint : public PiecewiseLinearConstraint */ void updateFeasibleDisjuncts(); bool disjunctIsFeasible( unsigned ind ) const; - bool caseSplitIsFeasible( const PiecewiseLinearCaseSplit & caseSplit ) const; + bool caseSplitIsFeasible( const PiecewiseLinearCaseSplit &caseSplit ) const; inline PhaseStatus indToPhaseStatus( unsigned ind ) const { @@ -233,7 +233,7 @@ class DisjunctionConstraint : public PiecewiseLinearConstraint inline unsigned phaseStatusToInd( PhaseStatus phase ) const { - //ASSERT( phase != PHASE_NOT_FIXED ); + // ASSERT( phase != PHASE_NOT_FIXED ); return static_cast( phase ) - 1; } diff --git a/src/engine/DivideStrategy.h b/src/engine/DivideStrategy.h index 9aec37ead0..e3e27fadcc 100644 --- a/src/engine/DivideStrategy.h +++ b/src/engine/DivideStrategy.h @@ -16,15 +16,15 @@ #ifndef __DivideStrategy_h__ #define __DivideStrategy_h__ -enum class DivideStrategy -{ +enum class DivideStrategy { // Relu splitting - Polarity = 0, // Pick the ReLU with the polarity closest to 0 among the first K nodes - EarliestReLU, // Pick a ReLU that appears in the earliest layer - ReLUViolation, // Pick the ReLU that has been violated for the most times - LargestInterval, // Pick the largest interval every K split steps, use ReLUViolation in other steps - PseudoImpact, // The pseudo-impact heuristic associated with SoI. - Auto, // See decideBranchingHeursitics() in Engine.h + Polarity = 0, // Pick the ReLU with the polarity closest to 0 among the first K nodes + EarliestReLU, // Pick a ReLU that appears in the earliest layer + ReLUViolation, // Pick the ReLU that has been violated for the most times + LargestInterval, // Pick the largest interval every K split steps, use ReLUViolation in other + // steps + PseudoImpact, // The pseudo-impact heuristic associated with SoI. + Auto, // See decideBranchingHeursitics() in Engine.h }; #endif // __DivideStrategy_h__ diff --git a/src/engine/DnCManager.cpp b/src/engine/DnCManager.cpp index afab60bbe1..42b2c521eb 100644 --- a/src/engine/DnCManager.cpp +++ b/src/engine/DnCManager.cpp @@ -13,9 +13,9 @@ **/ -#include "Debug.h" -#include "SnCDivideStrategy.h" #include "DnCManager.h" + +#include "Debug.h" #include "DnCWorker.h" #include "GetCPUData.h" #include "GlobalConfiguration.h" @@ -26,8 +26,10 @@ #include "PiecewiseLinearCaseSplit.h" #include "PolarityBasedDivider.h" #include "QueryDivider.h" +#include "SnCDivideStrategy.h" #include "TimeUtils.h" #include "Vector.h" + #include #include #include @@ -37,18 +39,23 @@ #include "cblas.h" #endif -void DnCManager::dncSolve( WorkerQueue *workload, std::shared_ptr engine, +void DnCManager::dncSolve( WorkerQueue *workload, + std::shared_ptr engine, std::unique_ptr inputQuery, std::atomic_int &numUnsolvedSubQueries, std::atomic_bool &shouldQuitSolving, - unsigned threadId, unsigned onlineDivides, - float timeoutFactor, SnCDivideStrategy divideStrategy, - bool restoreTreeStates, unsigned verbosity, - unsigned seed, bool parallelDeepSoI ) + unsigned threadId, + unsigned onlineDivides, + float timeoutFactor, + SnCDivideStrategy divideStrategy, + bool restoreTreeStates, + unsigned verbosity, + unsigned seed, + bool parallelDeepSoI ) { unsigned cpuId = 0; - (void) threadId; - (void) cpuId; + (void)threadId; + (void)cpuId; getCPUId( cpuId ); DNC_MANAGER_LOG( Stringf( "Thread #%u on CPU %u", threadId, cpuId ).ascii() ); @@ -57,9 +64,16 @@ void DnCManager::dncSolve( WorkerQueue *workload, std::shared_ptr engine if ( threadId != 0 ) engine->processInputQuery( *inputQuery, false ); - DnCWorker worker( workload, engine, std::ref( numUnsolvedSubQueries ), - std::ref( shouldQuitSolving ), threadId, onlineDivides, - timeoutFactor, divideStrategy, verbosity, parallelDeepSoI ); + DnCWorker worker( workload, + engine, + std::ref( numUnsolvedSubQueries ), + std::ref( shouldQuitSolving ), + threadId, + onlineDivides, + timeoutFactor, + divideStrategy, + verbosity, + parallelDeepSoI ); while ( !shouldQuitSolving.load() ) { worker.popOneSubQueryAndSolve( restoreTreeStates ); @@ -80,7 +94,7 @@ DnCManager::DnCManager( InputQuery *inputQuery ) { DNC_MANAGER_LOG( Stringf( "Deciding splitting strategy automatically...\n" ).ascii() ); if ( inputQuery->getNumInputVariables() < - GlobalConfiguration::INTERVAL_SPLITTING_THRESHOLD || + GlobalConfiguration::INTERVAL_SPLITTING_THRESHOLD || inputQuery->getPiecewiseLinearConstraints().empty() ) { DNC_MANAGER_LOG( Stringf( "\tUsing Largest Interval Heuristics\n" ).ascii() ); @@ -124,8 +138,9 @@ void DnCManager::solve() }; unsigned timeoutInSeconds = Options::get()->getInt( Options::TIMEOUT ); - unsigned long long timeoutInMicroSeconds = (unsigned long long)timeoutInSeconds * (unsigned long long)MICROSECONDS_IN_SECOND; - DNC_MANAGER_LOG( Stringf( "timeout in micro seconds: %llu", timeoutInMicroSeconds ).ascii()); + unsigned long long timeoutInMicroSeconds = + (unsigned long long)timeoutInSeconds * (unsigned long long)MICROSECONDS_IN_SECOND; + DNC_MANAGER_LOG( Stringf( "timeout in micro seconds: %llu", timeoutInMicroSeconds ).ascii() ); struct timespec startTime = TimeUtils::sampleMicro(); @@ -170,8 +185,7 @@ void DnCManager::solve() // Create empty case splits to get each worker started. SubQuery *subQuery = new SubQuery; subQuery->_queryId = Stringf( "%u", i ); - auto split = std::unique_ptr - ( new PiecewiseLinearCaseSplit ); + auto split = std::unique_ptr( new PiecewiseLinearCaseSplit ); subQuery->_split = std::move( split ); subQuery->_timeoutInSeconds = timeoutInSeconds; subQuery->_depth = 0; @@ -197,8 +211,8 @@ void DnCManager::solve() bool restoreTreeStates = Options::get()->getBool( Options::RESTORE_TREE_STATES ); unsigned seed = Options::get()->getInt( Options::SEED ); - auto baseInputQuery = std::unique_ptr - ( new InputQuery( *( _baseEngine->getInputQuery() ) ) ); + auto baseInputQuery = + std::unique_ptr( new InputQuery( *( _baseEngine->getInputQuery() ) ) ); // Spawn threads and start solving std::list threads; @@ -207,19 +221,22 @@ void DnCManager::solve() std::unique_ptr inputQuery = nullptr; if ( threadId != 0 ) // Get the processed input query from the base engine - inputQuery = std::unique_ptr - ( new InputQuery( *( baseInputQuery ) ) ); + inputQuery = std::unique_ptr( new InputQuery( *( baseInputQuery ) ) ); - threads.push_back( std::thread( dncSolve, workload, _engines[ threadId ], + threads.push_back( std::thread( dncSolve, + workload, + _engines[threadId], threadId != 0 ? std::move( inputQuery ) : nullptr, std::ref( _numUnsolvedSubQueries ), std::ref( shouldQuitSolving ), - threadId, onlineDivides, - timeoutFactor, _sncSplittingStrategy, - restoreTreeStates, _verbosity, + threadId, + onlineDivides, + timeoutFactor, + _sncSplittingStrategy, + restoreTreeStates, + _verbosity, _runParallelDeepSoI ? seed + threadId : seed, - _runParallelDeepSoI - ) ); + _runParallelDeepSoI ) ); } // Wait until either all subQueries are solved or a satisfying assignment is @@ -230,8 +247,7 @@ void DnCManager::solve() if ( _timeoutReached ) shouldQuitSolving = true; else - std::this_thread::sleep_for( std::chrono::milliseconds - ( numWorkers ) ); + std::this_thread::sleep_for( std::chrono::milliseconds( numWorkers ) ); } @@ -309,8 +325,7 @@ String DnCManager::getResultString() } } -void DnCManager::getSolution( std::map &ret, - InputQuery &inputQuery ) +void DnCManager::getSolution( std::map &ret, InputQuery &inputQuery ) { ASSERT( _engineWithSATAssignment != nullptr ); InputQuery *solvedInputQuery = _engineWithSATAssignment->getInputQuery(); @@ -375,7 +390,9 @@ void DnCManager::printResult() printf( "Input assignment:\n" ); for ( unsigned i = 0; i < inputQuery->getNumInputVariables(); ++i ) { - printf( "\tx%u = %lf\n", i, inputQuery->getSolutionValue( inputQuery->inputVariableByIndex( i ) ) ); + printf( "\tx%u = %lf\n", + i, + inputQuery->getSolutionValue( inputQuery->inputVariableByIndex( i ) ) ); inputs[i] = inputQuery->getSolutionValue( inputQuery->inputVariableByIndex( i ) ); } @@ -390,7 +407,9 @@ void DnCManager::printResult() if ( nlr ) printf( "\tnlr y%u = %lf\n", i, outputs[i] ); else - printf( "\ty%u = %lf\n", i, inputQuery->getSolutionValue( inputQuery->outputVariableByIndex( i ) ) ); + printf( "\ty%u = %lf\n", + i, + inputQuery->getSolutionValue( inputQuery->outputVariableByIndex( i ) ) ); } printf( "\n" ); break; @@ -439,29 +458,25 @@ bool DnCManager::createEngines( unsigned numberOfEngines ) void DnCManager::initialDivide( SubQueries &subQueries ) { - auto split = std::unique_ptr - ( new PiecewiseLinearCaseSplit() ); + auto split = std::unique_ptr( new PiecewiseLinearCaseSplit() ); std::unique_ptr queryDivider = nullptr; if ( _sncSplittingStrategy == SnCDivideStrategy::Polarity ) { - queryDivider = std::unique_ptr - ( new PolarityBasedDivider( _baseEngine ) ); + queryDivider = std::unique_ptr( new PolarityBasedDivider( _baseEngine ) ); } else // Default is LargestInterval { const List inputVariables( _baseEngine->getInputVariables() ); - queryDivider = std::unique_ptr - ( new LargestIntervalDivider( inputVariables ) ); + queryDivider = + std::unique_ptr( new LargestIntervalDivider( inputVariables ) ); InputQuery *inputQuery = _baseEngine->getInputQuery(); // Add bound as equations for each input variable for ( const auto &variable : inputVariables ) { double lb = inputQuery->getLowerBounds()[variable]; double ub = inputQuery->getUpperBounds()[variable]; - split->storeBoundTightening( Tightening( variable, lb, - Tightening::LB ) ); - split->storeBoundTightening( Tightening( variable, ub, - Tightening::UB ) ); + split->storeBoundTightening( Tightening( variable, lb, Tightening::LB ) ); + split->storeBoundTightening( Tightening( variable, ub, Tightening::UB ) ); } } @@ -471,16 +486,15 @@ void DnCManager::initialDivide( SubQueries &subQueries ) String queryId; // Create subqueries - queryDivider->createSubQueries( pow( 2, initialDivides ), queryId, 0, - *split, initialTimeout, subQueries ); + queryDivider->createSubQueries( + pow( 2, initialDivides ), queryId, 0, *split, initialTimeout, subQueries ); } -void DnCManager::updateTimeoutReached( timespec startTime, unsigned long long - timeoutInMicroSeconds ) +void DnCManager::updateTimeoutReached( timespec startTime, + unsigned long long timeoutInMicroSeconds ) { if ( timeoutInMicroSeconds == 0 ) return; struct timespec now = TimeUtils::sampleMicro(); - _timeoutReached = TimeUtils::timePassed( startTime, now ) >= - timeoutInMicroSeconds; + _timeoutReached = TimeUtils::timePassed( startTime, now ) >= timeoutInMicroSeconds; } diff --git a/src/engine/DnCManager.h b/src/engine/DnCManager.h index 9c82fdc530..5b0152166b 100644 --- a/src/engine/DnCManager.h +++ b/src/engine/DnCManager.h @@ -16,30 +16,29 @@ #ifndef __DnCManager_h__ #define __DnCManager_h__ -#include "SnCDivideStrategy.h" #include "Engine.h" #include "InputQuery.h" +#include "SnCDivideStrategy.h" #include "SubQuery.h" #include "Vector.h" #include -#define DNC_MANAGER_LOG( x, ... ) LOG( GlobalConfiguration::DNC_MANAGER_LOGGING, "DnCManager: %s\n", x ) +#define DNC_MANAGER_LOG( x, ... ) \ + LOG( GlobalConfiguration::DNC_MANAGER_LOGGING, "DnCManager: %s\n", x ) class DnCManager { public: + enum DnCExitCode { + UNSAT = 0, + SAT = 1, + ERROR = 2, + TIMEOUT = 3, + QUIT_REQUESTED = 4, - enum DnCExitCode - { - UNSAT = 0, - SAT = 1, - ERROR = 2, - TIMEOUT = 3, - QUIT_REQUESTED = 4, - - NOT_DONE = 999, - }; + NOT_DONE = 999, + }; DnCManager( InputQuery *inputQuery ); @@ -76,14 +75,19 @@ class DnCManager /* Create and run a DnCWorker */ - static void dncSolve( WorkerQueue *workload, std::shared_ptr engine, + static void dncSolve( WorkerQueue *workload, + std::shared_ptr engine, std::unique_ptr inputQuery, std::atomic_int &numUnsolvedSubQueries, std::atomic_bool &shouldQuitSolving, - unsigned threadId, unsigned onlineDivides, - float timeoutFactor, SnCDivideStrategy divideStrategy, - bool restoreTreeStates, unsigned verbosity, - unsigned seed, bool parallelDeepSoI ); + unsigned threadId, + unsigned onlineDivides, + float timeoutFactor, + SnCDivideStrategy divideStrategy, + bool restoreTreeStates, + unsigned verbosity, + unsigned seed, + bool parallelDeepSoI ); /* Create the base engine from the network and property files, @@ -106,8 +110,7 @@ class DnCManager /* Set _timeoutReached to true if timeout has been reached */ - void updateTimeoutReached( timespec startTime, - unsigned long long timeoutInMicroSeconds ); + void updateTimeoutReached( timespec startTime, unsigned long long timeoutInMicroSeconds ); /* The base engine that is used to perform the initial divides diff --git a/src/engine/DnCMarabou.cpp b/src/engine/DnCMarabou.cpp index 0d3792549f..75045e62ec 100644 --- a/src/engine/DnCMarabou.cpp +++ b/src/engine/DnCMarabou.cpp @@ -14,12 +14,13 @@ ** [[ Add lengthier description here ]] **/ +#include "DnCMarabou.h" + #include "AcasParser.h" #include "DnCManager.h" -#include "DnCMarabou.h" #include "File.h" -#include "MarabouError.h" #include "MStringf.h" +#include "MarabouError.h" #include "OnnxParser.h" #include "Options.h" #include "PropertyParser.h" @@ -42,7 +43,8 @@ void DnCMarabou::run() */ if ( !File::exists( inputQueryFilePath ) ) { - printf( "Error: the specified inputQuery file (%s) doesn't exist!\n", inputQueryFilePath.ascii() ); + printf( "Error: the specified inputQuery file (%s) doesn't exist!\n", + inputQueryFilePath.ascii() ); throw MarabouError( MarabouError::FILE_DOESNT_EXIST, inputQueryFilePath.ascii() ); } @@ -60,19 +62,18 @@ void DnCMarabou::run() { printf( "Error: the specified network file (%s) doesn't exist!\n", networkFilePath.ascii() ); - throw MarabouError( MarabouError::FILE_DOESNT_EXIST, - networkFilePath.ascii() ); + throw MarabouError( MarabouError::FILE_DOESNT_EXIST, networkFilePath.ascii() ); } printf( "Network: %s\n", networkFilePath.ascii() ); - if ( ((String) networkFilePath).endsWith( ".onnx" ) ) + if ( ( (String)networkFilePath ).endsWith( ".onnx" ) ) { - OnnxParser* _onnxParser = new OnnxParser( networkFilePath ); + OnnxParser *_onnxParser = new OnnxParser( networkFilePath ); _onnxParser->generateQuery( _inputQuery ); } else { - AcasParser* _acasParser = new AcasParser( networkFilePath ); + AcasParser *_acasParser = new AcasParser( networkFilePath ); _acasParser->generateQuery( _inputQuery ); } @@ -85,7 +86,7 @@ void DnCMarabou::run() if ( propertyFilePath != "" ) { printf( "Property: %s\n", propertyFilePath.ascii() ); - if ( propertyFilePath.endsWith( ".vnnlib" )) + if ( propertyFilePath.endsWith( ".vnnlib" ) ) { VnnLibParser().parse( propertyFilePath, _inputQuery ); } @@ -110,8 +111,7 @@ void DnCMarabou::run() /* Step 3: initialize the DNC core */ - _dncManager = std::unique_ptr - ( new DnCManager( &_inputQuery ) ); + _dncManager = std::unique_ptr( new DnCManager( &_inputQuery ) ); struct timespec start = TimeUtils::sampleMicro(); diff --git a/src/engine/DnCMarabou.h b/src/engine/DnCMarabou.h index 6de6a94154..c313045fbe 100644 --- a/src/engine/DnCMarabou.h +++ b/src/engine/DnCMarabou.h @@ -17,8 +17,8 @@ #define __DnCMarabou_h__ #include "DnCManager.h" -#include "Options.h" #include "InputQuery.h" +#include "Options.h" class DnCMarabou { diff --git a/src/engine/DnCWorker.cpp b/src/engine/DnCWorker.cpp index 2683fa1003..ecb93c7660 100644 --- a/src/engine/DnCWorker.cpp +++ b/src/engine/DnCWorker.cpp @@ -13,16 +13,17 @@ **/ -#include "Debug.h" -#include "SnCDivideStrategy.h" #include "DnCWorker.h" -#include "IEngine.h" + +#include "Debug.h" #include "EngineState.h" +#include "IEngine.h" #include "LargestIntervalDivider.h" -#include "MarabouError.h" #include "MStringf.h" +#include "MarabouError.h" #include "PiecewiseLinearCaseSplit.h" #include "PolarityBasedDivider.h" +#include "SnCDivideStrategy.h" #include "SubQuery.h" #include "TableauStateStorageLevel.h" @@ -31,12 +32,16 @@ #include #include -DnCWorker::DnCWorker( WorkerQueue *workload, std::shared_ptr engine, +DnCWorker::DnCWorker( WorkerQueue *workload, + std::shared_ptr engine, std::atomic_int &numUnsolvedSubQueries, std::atomic_bool &shouldQuitSolving, - unsigned threadId, unsigned onlineDivides, - float timeoutFactor, SnCDivideStrategy divideStrategy, - unsigned verbosity, bool parallelDeepSoI ) + unsigned threadId, + unsigned onlineDivides, + float timeoutFactor, + SnCDivideStrategy divideStrategy, + unsigned verbosity, + bool parallelDeepSoI ) : _workload( workload ) , _engine( engine ) , _numUnsolvedSubQueries( &numUnsolvedSubQueries ) @@ -53,21 +58,19 @@ DnCWorker::DnCWorker( WorkerQueue *workload, std::shared_ptr engine, if ( !_parallelDeepSoI ) { _initialState = std::make_shared(); - _engine->storeState( *_initialState, - TableauStateStorageLevel::STORE_ENTIRE_TABLEAU_STATE ); + _engine->storeState( *_initialState, TableauStateStorageLevel::STORE_ENTIRE_TABLEAU_STATE ); } } void DnCWorker::setQueryDivider( SnCDivideStrategy divideStrategy ) { if ( divideStrategy == SnCDivideStrategy::Polarity ) - _queryDivider = std::unique_ptr - ( new PolarityBasedDivider( _engine ) ); + _queryDivider = std::unique_ptr( new PolarityBasedDivider( _engine ) ); else { const List &inputVariables = _engine->getInputVariables(); - _queryDivider = std::unique_ptr - ( new LargestIntervalDivider( inputVariables ) ); + _queryDivider = + std::unique_ptr( new LargestIntervalDivider( inputVariables ) ); } } @@ -129,8 +132,9 @@ void DnCWorker::popOneSubQueryAndSolve( bool restoreTreeStates ) // If TIMEOUT, split the current input region and add the // new subQueries to the current queue SubQueries subQueries; - unsigned newTimeout = ( depth >= GlobalConfiguration::DNC_DEPTH_THRESHOLD - 1 ? - 0 : ( unsigned ) timeoutInSeconds * _timeoutFactor ); + unsigned newTimeout = ( depth >= GlobalConfiguration::DNC_DEPTH_THRESHOLD - 1 + ? 0 + : (unsigned)timeoutInSeconds * _timeoutFactor ); unsigned numNewSubQueries = pow( 2, _onlineDivides ); std::vector> newSmtStates; if ( restoreTreeStates ) @@ -138,14 +142,13 @@ void DnCWorker::popOneSubQueryAndSolve( bool restoreTreeStates ) // create |numNewSubQueries| copies of the current SmtState for ( unsigned i = 0; i < numNewSubQueries; ++i ) { - newSmtStates.push_back( std::unique_ptr - ( new SmtState() ) ); + newSmtStates.push_back( std::unique_ptr( new SmtState() ) ); _engine->storeSmtState( *( newSmtStates[i] ) ); } } - _queryDivider->createSubQueries( numNewSubQueries, queryId, depth, - *split, newTimeout, subQueries ); + _queryDivider->createSubQueries( + numNewSubQueries, queryId, depth, *split, newTimeout, subQueries ); unsigned i = 0; for ( auto &newSubQuery : subQueries ) @@ -209,8 +212,10 @@ void DnCWorker::popOneSubQueryAndSolve( bool restoreTreeStates ) void DnCWorker::printProgress( String queryId, IEngine::ExitCode result ) const { - printf( "Worker %d: Query %s %s, %d tasks remaining\n", _threadId, - queryId.ascii(), exitCodeToString( result ).ascii(), + printf( "Worker %d: Query %s %s, %d tasks remaining\n", + _threadId, + queryId.ascii(), + exitCodeToString( result ).ascii(), _numUnsolvedSubQueries->load() ); } diff --git a/src/engine/DnCWorker.h b/src/engine/DnCWorker.h index 01b0b384e9..4cbe85e483 100644 --- a/src/engine/DnCWorker.h +++ b/src/engine/DnCWorker.h @@ -16,21 +16,25 @@ #ifndef __DnCWorker_h__ #define __DnCWorker_h__ -#include "SnCDivideStrategy.h" #include "Engine.h" #include "PiecewiseLinearCaseSplit.h" #include "QueryDivider.h" +#include "SnCDivideStrategy.h" #include class DnCWorker { public: - DnCWorker( WorkerQueue *workload, std::shared_ptr engine, + DnCWorker( WorkerQueue *workload, + std::shared_ptr engine, std::atomic_int &numUnsolvedSubqueries, - std::atomic_bool &shouldQuitSolving, unsigned threadId, - unsigned onlineDivides, float timeoutFactor, - SnCDivideStrategy divideStrategy, unsigned verbosity, + std::atomic_bool &shouldQuitSolving, + unsigned threadId, + unsigned onlineDivides, + float timeoutFactor, + SnCDivideStrategy divideStrategy, + unsigned verbosity, bool parallelDeepSoI ); /* diff --git a/src/engine/Engine.cpp b/src/engine/Engine.cpp index 082a56a68d..1a80b98792 100644 --- a/src/engine/Engine.cpp +++ b/src/engine/Engine.cpp @@ -14,10 +14,11 @@ ** [[ Add lengthier description here ]] **/ +#include "Engine.h" + #include "AutoConstraintMatrixAnalyzer.h" #include "Debug.h" #include "DisjunctionConstraint.h" -#include "Engine.h" #include "EngineState.h" #include "InfeasibleQueryException.h" #include "InputQuery.h" @@ -63,7 +64,8 @@ Engine::Engine() , _soiManager( nullptr ) , _simulationSize( Options::get()->getInt( Options::NUMBER_OF_SIMULATIONS ) ) , _isGurobyEnabled( Options::get()->gurobiEnabled() ) - , _performLpTighteningAfterSplit( Options::get()->getBool( Options::PERFORM_LP_TIGHTENING_AFTER_SPLIT ) ) + , _performLpTighteningAfterSplit( + Options::get()->getBool( Options::PERFORM_LP_TIGHTENING_AFTER_SPLIT ) ) , _milpSolverBoundTighteningType( Options::get()->getMILPSolverBoundTighteningType() ) , _sncMode( false ) , _queryId( "" ) @@ -83,12 +85,14 @@ Engine::Engine() _boundManager.registerEngine( this ); _groundBoundManager.registerEngine( this ); - _statisticsPrintingFrequency = - ( _lpSolverType == LPSolverType::NATIVE ) ? - GlobalConfiguration::STATISTICS_PRINTING_FREQUENCY : - GlobalConfiguration::STATISTICS_PRINTING_FREQUENCY_GUROBI; + _statisticsPrintingFrequency = ( _lpSolverType == LPSolverType::NATIVE ) + ? GlobalConfiguration::STATISTICS_PRINTING_FREQUENCY + : GlobalConfiguration::STATISTICS_PRINTING_FREQUENCY_GUROBI; - _UNSATCertificateCurrentPointer = _produceUNSATProofs ? new ( true ) CVC4::context::CDO( &_context, NULL ) : NULL; + _UNSATCertificateCurrentPointer = + _produceUNSATProofs ? new ( true ) + CVC4::context::CDO( &_context, NULL ) + : NULL; } Engine::~Engine() @@ -162,10 +166,11 @@ InputQuery Engine::prepareSnCInputQuery() switch ( bound._type ) { case Tightening::LB: - sncIPQ.setLowerBound( bound._variable, bound._value ); break; + sncIPQ.setLowerBound( bound._variable, bound._value ); + break; case Tightening::UB: - sncIPQ.setUpperBound( bound._variable, bound._value ); + sncIPQ.setUpperBound( bound._variable, bound._value ); } } @@ -176,7 +181,10 @@ void Engine::exportInputQueryWithError( String errorMessage ) { String ipqFileName = ( _queryId.length() > 0 ) ? _queryId + ".ipq" : "failedMarabouQuery.ipq"; prepareSnCInputQuery().saveQuery( ipqFileName ); - printf( "Engine: %s!\nInput query has been saved as %s. Please attach the input query when you open the issue on GitHub.\n", errorMessage.ascii(), ipqFileName.ascii() ); + printf( "Engine: %s!\nInput query has been saved as %s. Please attach the input query when you " + "open the issue on GitHub.\n", + errorMessage.ascii(), + ipqFileName.ascii() ); } bool Engine::solve( unsigned timeoutInSeconds ) @@ -198,14 +206,13 @@ bool Engine::solve( unsigned timeoutInSeconds ) storeInitialEngineState(); else if ( _lpSolverType == LPSolverType::GUROBI ) { - ENGINE_LOG( "Encoding convex relaxation into Gurobi..."); + ENGINE_LOG( "Encoding convex relaxation into Gurobi..." ); _gurobi = std::unique_ptr( new GurobiWrapper() ); _tableau->setGurobi( &( *_gurobi ) ); - _milpEncoder = std::unique_ptr - ( new MILPEncoder( *_tableau ) ); + _milpEncoder = std::unique_ptr( new MILPEncoder( *_tableau ) ); _milpEncoder->setStatistics( &_statistics ); _milpEncoder->encodeInputQuery( *_gurobi, *_preprocessedQuery, true ); - ENGINE_LOG( "Encoding convex relaxation into Gurobi - done"); + ENGINE_LOG( "Encoding convex relaxation into Gurobi - done" ); } mainLoopStatistics(); @@ -224,8 +231,7 @@ bool Engine::solve( unsigned timeoutInSeconds ) { struct timespec mainLoopEnd = TimeUtils::sampleMicro(); _statistics.incLongAttribute( Statistics::TIME_MAIN_LOOP_MICRO, - TimeUtils::timePassed( mainLoopStart, - mainLoopEnd ) ); + TimeUtils::timePassed( mainLoopStart, mainLoopEnd ) ); mainLoopStart = mainLoopEnd; if ( shouldExitDueToTimeout( timeoutInSeconds ) ) @@ -261,9 +267,9 @@ bool Engine::solve( unsigned timeoutInSeconds ) mainLoopStatistics(); if ( _verbosity > 1 && - _statistics.getLongAttribute - ( Statistics::NUM_MAIN_LOOP_ITERATIONS ) % - _statisticsPrintingFrequency == 0 ) + _statistics.getLongAttribute( Statistics::NUM_MAIN_LOOP_ITERATIONS ) % + _statisticsPrintingFrequency == + 0 ) _statistics.print(); if ( _lpSolverType == LPSolverType::NATIVE ) @@ -315,28 +321,27 @@ bool Engine::solve( unsigned timeoutInSeconds ) // The linear portion of the problem has been solved. // Check the status of the PL constraints - bool solutionFound = - adjustAssignmentToSatisfyNonLinearConstraints(); + bool solutionFound = adjustAssignmentToSatisfyNonLinearConstraints(); if ( solutionFound ) { mainLoopEnd = TimeUtils::sampleMicro(); - _statistics.incLongAttribute - ( Statistics::TIME_MAIN_LOOP_MICRO, - TimeUtils::timePassed( mainLoopStart, - mainLoopEnd ) ); + _statistics.incLongAttribute( + Statistics::TIME_MAIN_LOOP_MICRO, + TimeUtils::timePassed( mainLoopStart, mainLoopEnd ) ); if ( _verbosity > 0 ) { printf( "\nEngine::solve: sat assignment found\n" ); _statistics.print(); } - // Allows checking proofs produced for UNSAT leaves of satisfiable query search tree + // Allows checking proofs produced for UNSAT leaves of satisfiable query search + // tree if ( _produceUNSATProofs ) { ASSERT( _UNSATCertificateCurrentPointer ); ( **_UNSATCertificateCurrentPointer ).setSATSolutionFlag(); } - _exitCode = Engine::SAT; + _exitCode = Engine::SAT; return true; } else @@ -349,7 +354,7 @@ bool Engine::solve( unsigned timeoutInSeconds ) else { ENGINE_LOG( "Checking LP feasibility with Gurobi..." ); - DEBUG({ checkGurobiBoundConsistency(); }); + DEBUG( { checkGurobiBoundConsistency(); } ); ASSERT( _lpSolverType == LPSolverType::GUROBI ); LinearExpression dontCare; minimizeCostWithGurobi( dontCare ); @@ -365,10 +370,8 @@ bool Engine::solve( unsigned timeoutInSeconds ) _exitCode = Engine::ERROR; exportInputQueryWithError( "Cannot restore tableau" ); mainLoopEnd = TimeUtils::sampleMicro(); - _statistics.incLongAttribute - ( Statistics::TIME_MAIN_LOOP_MICRO, - TimeUtils::timePassed( mainLoopStart, - mainLoopEnd ) ); + _statistics.incLongAttribute( Statistics::TIME_MAIN_LOOP_MICRO, + TimeUtils::timePassed( mainLoopStart, mainLoopEnd ) ); return false; } } @@ -383,10 +386,8 @@ bool Engine::solve( unsigned timeoutInSeconds ) if ( !_smtCore.popSplit() ) { mainLoopEnd = TimeUtils::sampleMicro(); - _statistics.incLongAttribute - ( Statistics::TIME_MAIN_LOOP_MICRO, - TimeUtils::timePassed( mainLoopStart, - mainLoopEnd ) ); + _statistics.incLongAttribute( Statistics::TIME_MAIN_LOOP_MICRO, + TimeUtils::timePassed( mainLoopStart, mainLoopEnd ) ); if ( _verbosity > 0 ) { printf( "\nEngine::solve: unsat query\n" ); @@ -407,16 +408,13 @@ bool Engine::solve( unsigned timeoutInSeconds ) } catch ( MarabouError &e ) { - String message = - Stringf( "Caught a MarabouError. Code: %u. Message: %s ", - e.getCode(), e.getUserMessage() ); + String message = Stringf( + "Caught a MarabouError. Code: %u. Message: %s ", e.getCode(), e.getUserMessage() ); _exitCode = Engine::ERROR; exportInputQueryWithError( message ); mainLoopEnd = TimeUtils::sampleMicro(); - _statistics.incLongAttribute - ( Statistics::TIME_MAIN_LOOP_MICRO, - TimeUtils::timePassed( mainLoopStart, - mainLoopEnd ) ); + _statistics.incLongAttribute( Statistics::TIME_MAIN_LOOP_MICRO, + TimeUtils::timePassed( mainLoopStart, mainLoopEnd ) ); return false; } catch ( ... ) @@ -424,10 +422,8 @@ bool Engine::solve( unsigned timeoutInSeconds ) _exitCode = Engine::ERROR; exportInputQueryWithError( "Unknown error" ); mainLoopEnd = TimeUtils::sampleMicro(); - _statistics.incLongAttribute - ( Statistics::TIME_MAIN_LOOP_MICRO, - TimeUtils::timePassed( mainLoopStart, - mainLoopEnd ) ); + _statistics.incLongAttribute( Statistics::TIME_MAIN_LOOP_MICRO, + TimeUtils::timePassed( mainLoopStart, mainLoopEnd ) ); return false; } } @@ -442,13 +438,12 @@ void Engine::mainLoopStatistics() if ( constraint->isActive() ) ++activeConstraints; - _statistics.setUnsignedAttribute( Statistics::NUM_ACTIVE_PL_CONSTRAINTS, - activeConstraints ); + _statistics.setUnsignedAttribute( Statistics::NUM_ACTIVE_PL_CONSTRAINTS, activeConstraints ); _statistics.setUnsignedAttribute( Statistics::NUM_PL_VALID_SPLITS, _numPlConstraintsDisabledByValidSplits ); _statistics.setUnsignedAttribute( Statistics::NUM_PL_SMT_ORIGINATED_SPLITS, - _plConstraints.size() - activeConstraints - - _numPlConstraintsDisabledByValidSplits ); + _plConstraints.size() - activeConstraints - + _numPlConstraintsDisabledByValidSplits ); _statistics.incLongAttribute( Statistics::NUM_MAIN_LOOP_ITERATIONS ); @@ -468,9 +463,9 @@ void Engine::performBoundTighteningAfterCaseSplit() while ( applyAllValidConstraintCaseSplits() ); // Tighten bounds of an output layer with MILP solver - if ( _networkLevelReasoner ) // to avoid failing of system test. - performMILPSolverBoundedTighteningForSingleLayer - ( _networkLevelReasoner->getLayerIndexToLayer().size() - 1 ); + if ( _networkLevelReasoner ) // to avoid failing of system test. + performMILPSolverBoundedTighteningForSingleLayer( + _networkLevelReasoner->getLayerIndexToLayer().size() - 1 ); } bool Engine::adjustAssignmentToSatisfyNonLinearConstraints() @@ -483,8 +478,7 @@ bool Engine::adjustAssignmentToSatisfyNonLinearConstraints() if ( allPlConstraintsHold() && allNonlinearConstraintsHold() ) { if ( _lpSolverType == LPSolverType::NATIVE && - _tableau->getBasicAssignmentStatus() != - ITableau::BASIC_ASSIGNMENT_JUST_COMPUTED ) + _tableau->getBasicAssignmentStatus() != ITableau::BASIC_ASSIGNMENT_JUST_COMPUTED ) { if ( _verbosity > 0 ) { @@ -564,8 +558,7 @@ bool Engine::handleMalformedBasisException() if ( _basisRestorationPerformed == Engine::NO_RESTORATION_PERFORMED ) { if ( _numVisitedStatesAtPreviousRestoration != - _statistics.getUnsignedAttribute - ( Statistics::NUM_VISITED_TREE_STATES ) ) + _statistics.getUnsignedAttribute( Statistics::NUM_VISITED_TREE_STATES ) ) { // We've tried a strong restoration before, and it didn't work. Do a weak restoration _basisRestorationRequired = Engine::WEAK_RESTORATION_NEEDED; @@ -623,41 +616,40 @@ bool Engine::performSimplexStep() */ if ( _tableau->isOptimizing() ) - _costFunctionManager->computeGivenCostFunction - ( _heuristicCost._addends ); + _costFunctionManager->computeGivenCostFunction( _heuristicCost._addends ); if ( _costFunctionManager->costFunctionInvalid() ) _costFunctionManager->computeCoreCostFunction(); else _costFunctionManager->adjustBasicCostAccuracy(); - DEBUG({ - // Since we're performing a simplex step, there are out-of-bounds variables. - // Therefore, if the cost function is fresh, it should not be zero. - if ( _costFunctionManager->costFunctionJustComputed() ) + DEBUG( { + // Since we're performing a simplex step, there are out-of-bounds variables. + // Therefore, if the cost function is fresh, it should not be zero. + if ( _costFunctionManager->costFunctionJustComputed() ) + { + const double *costFunction = _costFunctionManager->getCostFunction(); + unsigned size = _tableau->getN() - _tableau->getM(); + bool found = false; + for ( unsigned i = 0; i < size; ++i ) { - const double *costFunction = _costFunctionManager->getCostFunction(); - unsigned size = _tableau->getN() - _tableau->getM(); - bool found = false; - for ( unsigned i = 0; i < size; ++i ) + if ( !FloatUtils::isZero( costFunction[i] ) ) { - if ( !FloatUtils::isZero( costFunction[i] ) ) - { - found = true; - break; - } + found = true; + break; } + } - if ( !found ) - { - printf( "Error! Have OOB vars but cost function is zero.\n" - "Recomputing cost function. New one is:\n" ); - _costFunctionManager->computeCoreCostFunction(); - _costFunctionManager->dumpCostFunction(); - throw MarabouError( MarabouError::DEBUGGING_ERROR, - "Have OOB vars but cost function is zero" ); - } + if ( !found ) + { + printf( "Error! Have OOB vars but cost function is zero.\n" + "Recomputing cost function. New one is:\n" ); + _costFunctionManager->computeCoreCostFunction(); + _costFunctionManager->dumpCostFunction(); + throw MarabouError( MarabouError::DEBUGGING_ERROR, + "Have OOB vars but cost function is zero" ); } - }); + } + } ); // Obtain all eligible entering variables List enteringVariableCandidates; @@ -676,9 +668,8 @@ bool Engine::performSimplexStep() --tries; // Attempt to pick the best entering variable from the available candidates - if ( !_activeEntryStrategy->select( _tableau, - enteringVariableCandidates, - excludedEnteringVariables ) ) + if ( !_activeEntryStrategy->select( + _tableau, enteringVariableCandidates, excludedEnteringVariables ) ) { // No additional candidates can be found. break; @@ -701,7 +692,7 @@ bool Engine::performSimplexStep() bestEntering = _tableau->getEnteringVariableIndex(); bestLeaving = _tableau->getLeavingVariableIndex(); bestChangeRatio = _tableau->getChangeRatio(); - memcpy( _work, _tableau->getChangeColumn(), sizeof(double) * _tableau->getM() ); + memcpy( _work, _tableau->getChangeColumn(), sizeof( double ) * _tableau->getM() ); break; } @@ -714,7 +705,7 @@ bool Engine::performSimplexStep() bestPivotEntry = pivotEntry; bestLeaving = leavingIndex; bestChangeRatio = _tableau->getChangeRatio(); - memcpy( _work, _tableau->getChangeColumn(), sizeof(double) * _tableau->getM() ); + memcpy( _work, _tableau->getChangeColumn(), sizeof( double ) * _tableau->getM() ); } // If the pivot is greater than the sought-after threshold, we @@ -722,8 +713,8 @@ bool Engine::performSimplexStep() if ( bestPivotEntry >= GlobalConfiguration::ACCEPTABLE_SIMPLEX_PIVOT_THRESHOLD ) break; else - _statistics.incLongAttribute - ( Statistics::NUM_SIMPLEX_PIVOT_SELECTIONS_IGNORED_FOR_STABILITY ); + _statistics.incLongAttribute( + Statistics::NUM_SIMPLEX_PIVOT_SELECTIONS_IGNORED_FOR_STABILITY ); } // If we don't have any candidates, this simplex step has failed. @@ -773,8 +764,7 @@ bool Engine::performSimplexStep() bool fakePivot = _tableau->performingFakePivot(); - if ( !fakePivot && - bestPivotEntry < GlobalConfiguration::ACCEPTABLE_SIMPLEX_PIVOT_THRESHOLD ) + if ( !fakePivot && bestPivotEntry < GlobalConfiguration::ACCEPTABLE_SIMPLEX_PIVOT_THRESHOLD ) { /* Despite our efforts, we are stuck with a small pivot. If basis factorization @@ -804,7 +794,8 @@ bool Engine::performSimplexStep() _costFunctionManager->invalidateCostFunction(); struct timespec end = TimeUtils::sampleMicro(); - _statistics.incLongAttribute( Statistics::TIME_SIMPLEX_STEPS_MICRO, TimeUtils::timePassed( start, end ) ); + _statistics.incLongAttribute( Statistics::TIME_SIMPLEX_STEPS_MICRO, + TimeUtils::timePassed( start, end ) ); return false; } @@ -823,11 +814,11 @@ void Engine::fixViolatedPlConstraintIfPossible() { if ( !_tableau->isBasic( fix._variable ) ) { - if ( _tableau->checkValueWithinBounds( fix._variable, fix._value ) ) - { + if ( _tableau->checkValueWithinBounds( fix._variable, fix._value ) ) + { _tableau->setNonBasicAssignment( fix._variable, fix._value, true ); return; - } + } } } @@ -840,8 +831,8 @@ void Engine::fixViolatedPlConstraintIfPossible() { if ( _tableau->isBasic( it->_variable ) ) { - if ( _tableau->checkValueWithinBounds( it->_variable, it->_value ) ) - { + if ( _tableau->checkValueWithinBounds( it->_variable, it->_value ) ) + { found = true; } } @@ -920,9 +911,9 @@ bool Engine::calculateBounds( InputQuery &inputQuery ) initializeNetworkLevelReasoning(); - performSymbolicBoundTightening( &(*_preprocessedQuery) ); + performSymbolicBoundTightening( &( *_preprocessedQuery ) ); performSimulation(); - performMILPSolverBoundedTightening( &(*_preprocessedQuery) ); + performMILPSolverBoundedTightening( &( *_preprocessedQuery ) ); if ( _networkLevelReasoner && Options::get()->getBool( Options::DUMP_BOUNDS ) ) _networkLevelReasoner->dumpBounds(); @@ -989,11 +980,10 @@ void Engine::invokePreprocessor( const InputQuery &inputQuery, bool preprocess ) // If processing is enabled, invoke the preprocessor _preprocessingEnabled = preprocess; if ( _preprocessingEnabled ) - _preprocessedQuery = _preprocessor.preprocess - ( inputQuery, GlobalConfiguration::PREPROCESSOR_ELIMINATE_VARIABLES ); + _preprocessedQuery = _preprocessor.preprocess( + inputQuery, GlobalConfiguration::PREPROCESSOR_ELIMINATE_VARIABLES ); else - _preprocessedQuery = std::unique_ptr - ( new InputQuery( inputQuery ) ); + _preprocessedQuery = std::unique_ptr( new InputQuery( inputQuery ) ); if ( _verbosity > 0 ) printf( "Engine::processInputQuery: Input query (after preprocessing): " @@ -1006,7 +996,7 @@ void Engine::invokePreprocessor( const InputQuery &inputQuery, bool preprocess ) { _exitCode = Engine::ERROR; throw MarabouError( MarabouError::UNBOUNDED_VARIABLES_NOT_YET_SUPPORTED, - Stringf( "Error! Have %u infinite bounds", infiniteBounds ).ascii() ); + Stringf( "Error! Have %u infinite bounds", infiniteBounds ).ascii() ); } } @@ -1064,10 +1054,10 @@ double *Engine::createConstraintMatrix() unsigned n = _preprocessedQuery->getNumberOfVariables(); // Step 1: create a constraint matrix from the equations - double *constraintMatrix = new double[n*m]; + double *constraintMatrix = new double[n * m]; if ( !constraintMatrix ) throw MarabouError( MarabouError::ALLOCATION_FAILED, "Engine::constraintMatrix" ); - std::fill_n( constraintMatrix, n*m, 0.0 ); + std::fill_n( constraintMatrix, n * m, 0.0 ); unsigned equationIndex = 0; for ( const auto &equation : equations ) @@ -1079,7 +1069,7 @@ double *Engine::createConstraintMatrix() } for ( const auto &addend : equation._addends ) - constraintMatrix[equationIndex*n + addend._variable] = addend._coefficient; + constraintMatrix[equationIndex * n + addend._variable] = addend._coefficient; ++equationIndex; } @@ -1097,8 +1087,9 @@ void Engine::removeRedundantEquations( const double *constraintMatrix ) AutoConstraintMatrixAnalyzer analyzer; analyzer->analyze( constraintMatrix, m, n ); - ENGINE_LOG( Stringf( "Number of redundant rows: %u out of %u", - analyzer->getRedundantRows().size(), m ).ascii() ); + ENGINE_LOG( + Stringf( "Number of redundant rows: %u out of %u", analyzer->getRedundantRows().size(), m ) + .ascii() ); // Step 2: remove any equations corresponding to redundant rows Set redundantRows = analyzer->getRedundantRows(); @@ -1110,7 +1101,9 @@ void Engine::removeRedundantEquations( const double *constraintMatrix ) } } -void Engine::selectInitialVariablesForBasis( const double *constraintMatrix, List &initialBasis, List &basicRows ) +void Engine::selectInitialVariablesForBasis( const double *constraintMatrix, + List &initialBasis, + List &basicRows ) { /* This method permutes rows and columns in the constraint matrix (prior @@ -1156,7 +1149,7 @@ void Engine::selectInitialVariablesForBasis( const double *constraintMatrix, Lis { for ( unsigned j = 0; j < n; ++j ) { - if ( !FloatUtils::isZero( constraintMatrix[i*n + j] ) ) + if ( !FloatUtils::isZero( constraintMatrix[i * n + j] ) ) { ++nnzInRow[i]; ++nnzInColumn[j]; @@ -1164,12 +1157,12 @@ void Engine::selectInitialVariablesForBasis( const double *constraintMatrix, Lis } } - DEBUG({ - for ( unsigned i = 0; i < m; ++i ) - { - ASSERT( nnzInRow[i] > 0 ); - } - }); + DEBUG( { + for ( unsigned i = 0; i < m; ++i ) + { + ASSERT( nnzInRow[i] > 0 ); + } + } ); unsigned numExcluded = 0; unsigned numTriangularRows = 0; @@ -1203,7 +1196,8 @@ void Engine::selectInitialVariablesForBasis( const double *constraintMatrix, Lis DEBUG( bool foundNonZero = false ); for ( unsigned i = numTriangularRows; i < n - numExcluded; ++i ) { - if ( !FloatUtils::isZero( constraintMatrix[rowOrdering[numTriangularRows] * n + columnOrdering[i]] ) ) + if ( !FloatUtils::isZero( constraintMatrix[rowOrdering[numTriangularRows] * n + + columnOrdering[i]] ) ) { temp = columnOrdering[i]; columnOrdering[i] = columnOrdering[numTriangularRows]; @@ -1223,7 +1217,8 @@ void Engine::selectInitialVariablesForBasis( const double *constraintMatrix, Lis // Remove all entries under the diagonal entry from the row counters for ( unsigned i = numTriangularRows + 1; i < m; ++i ) { - if ( !FloatUtils::isZero( constraintMatrix[rowOrdering[i] * n + columnOrdering[numTriangularRows]] ) ) + if ( !FloatUtils::isZero( constraintMatrix[rowOrdering[i] * n + + columnOrdering[numTriangularRows]] ) ) --nnzInRow[i]; } @@ -1247,7 +1242,7 @@ void Engine::selectInitialVariablesForBasis( const double *constraintMatrix, Lis // Update the row counters to account for the excluded column for ( unsigned i = numTriangularRows; i < m; ++i ) { - double element = constraintMatrix[rowOrdering[i]*n + columnOrdering[column]]; + double element = constraintMatrix[rowOrdering[i] * n + columnOrdering[column]]; if ( !FloatUtils::isZero( element ) ) { ASSERT( nnzInRow[i] > 1 ); @@ -1307,7 +1302,8 @@ void Engine::addAuxiliaryVariables() } } -void Engine::augmentInitialBasisIfNeeded( List &initialBasis, const List &basicRows ) +void Engine::augmentInitialBasisIfNeeded( List &initialBasis, + const List &basicRows ) { unsigned m = _preprocessedQuery->getEquations().size(); unsigned n = _preprocessedQuery->getNumberOfVariables(); @@ -1354,8 +1350,7 @@ void Engine::initializeTableau( const double *constraintMatrix, const Listinitialize( _tableau ); } -void Engine::initializeBoundsAndConstraintWatchersInTableau( unsigned - numberOfVariables ) +void Engine::initializeBoundsAndConstraintWatchersInTableau( unsigned numberOfVariables ) { _plConstraints = _preprocessedQuery->getPiecewiseLinearConstraints(); for ( const auto &constraint : _plConstraints ) @@ -1363,11 +1358,13 @@ void Engine::initializeBoundsAndConstraintWatchersInTableau( unsigned constraint->registerAsWatcher( _tableau ); constraint->setStatistics( &_statistics ); - // Assuming aux var is use, add the constraint's auxiliary variable assigned to it in the tableau, to the constraint - if ( _produceUNSATProofs ) + // Assuming aux var is use, add the constraint's auxiliary variable assigned to it in the + // tableau, to the constraint + if ( _produceUNSATProofs ) for ( unsigned var : constraint->getNativeAuxVars() ) if ( _preprocessedQuery->_lastAddendToAux.exists( var ) ) - constraint->addTableauAuxVar( _preprocessedQuery->_lastAddendToAux.at( var ), var ); + constraint->addTableauAuxVar( _preprocessedQuery->_lastAddendToAux.at( var ), + var ); } _nlConstraints = _preprocessedQuery->getNonlinearConstraints(); @@ -1384,8 +1381,7 @@ void Engine::initializeBoundsAndConstraintWatchersInTableau( unsigned } _boundManager.storeLocalBounds(); - _statistics.setUnsignedAttribute( Statistics::NUM_PL_CONSTRAINTS, - _plConstraints.size() ); + _statistics.setUnsignedAttribute( Statistics::NUM_PL_CONSTRAINTS, _plConstraints.size() ); } void Engine::initializeNetworkLevelReasoning() @@ -1418,36 +1414,36 @@ bool Engine::processInputQuery( InputQuery &inputQuery, bool preprocess ) initializeNetworkLevelReasoning(); if ( preprocess ) { - performSymbolicBoundTightening( &(*_preprocessedQuery) ); + performSymbolicBoundTightening( &( *_preprocessedQuery ) ); performSimulation(); - performMILPSolverBoundedTightening( &(*_preprocessedQuery) ); + performMILPSolverBoundedTightening( &( *_preprocessedQuery ) ); } if ( GlobalConfiguration::PL_CONSTRAINTS_ADD_AUX_EQUATIONS_AFTER_PREPROCESSING ) for ( auto &plConstraint : _preprocessedQuery->getPiecewiseLinearConstraints() ) - plConstraint->addAuxiliaryEquationsAfterPreprocessing - ( *_preprocessedQuery ); + plConstraint->addAuxiliaryEquationsAfterPreprocessing( *_preprocessedQuery ); if ( GlobalConfiguration::NL_CONSTRAINTS_ADD_AUX_EQUATIONS_AFTER_PREPROCESSING ) for ( auto &nlConstraint : _preprocessedQuery->getNonlinearConstraints() ) - nlConstraint->addAuxiliaryEquationsAfterPreprocessing - ( *_preprocessedQuery ); + nlConstraint->addAuxiliaryEquationsAfterPreprocessing( *_preprocessedQuery ); if ( _produceUNSATProofs ) { for ( auto &plConstraint : _preprocessedQuery->getPiecewiseLinearConstraints() ) { - if ( !UNSATCertificateUtils::getSupportedActivations().exists( plConstraint->getType() ) ) + if ( !UNSATCertificateUtils::getSupportedActivations().exists( + plConstraint->getType() ) ) { _produceUNSATProofs = false; Options::get()->setBool( Options::PRODUCE_PROOFS, false ); - String activationType = plConstraint->serializeToString().tokenize(",").back(); - printf( "Turning off proof production since activation %s is not yet supported\n", activationType.ascii() ); + String activationType = + plConstraint->serializeToString().tokenize( "," ).back(); + printf( + "Turning off proof production since activation %s is not yet supported\n", + activationType.ascii() ); break; } } - - } if ( _lpSolverType == LPSolverType::NATIVE ) @@ -1499,7 +1495,7 @@ bool Engine::processInputQuery( InputQuery &inputQuery, bool preprocess ) ASSERT( GlobalConfiguration::USE_DEEPSOI_LOCAL_SEARCH == true ); if ( _verbosity > 0 ) - printf("Using Gurobi to solve LP...\n"); + printf( "Using Gurobi to solve LP...\n" ); unsigned n = _preprocessedQuery->getNumberOfVariables(); unsigned m = _preprocessedQuery->getEquations().size(); @@ -1519,9 +1515,8 @@ bool Engine::processInputQuery( InputQuery &inputQuery, bool preprocess ) if ( GlobalConfiguration::USE_DEEPSOI_LOCAL_SEARCH ) { - _soiManager = std::unique_ptr - ( new SumOfInfeasibilitiesManager( *_preprocessedQuery, - *_tableau ) ); + _soiManager = std::unique_ptr( + new SumOfInfeasibilitiesManager( *_preprocessedQuery, *_tableau ) ); _soiManager->setStatistics( &_statistics ); } @@ -1554,13 +1549,13 @@ bool Engine::processInputQuery( InputQuery &inputQuery, bool preprocess ) ENGINE_LOG( "processInputQuery done\n" ); - DEBUG({ - // Initially, all constraints should be active - for ( const auto &plc : _plConstraints ) - { - ASSERT( plc->isActive() ); - } - }); + DEBUG( { + // Initially, all constraints should be active + for ( const auto &plc : _plConstraints ) + { + ASSERT( plc->isActive() ); + } + } ); _smtCore.storeDebuggingSolution( _preprocessedQuery->_debuggingSolution ); return true; @@ -1573,17 +1568,19 @@ void Engine::performMILPSolverBoundedTightening( InputQuery *inputQuery ) if ( _networkLevelReasoner && Options::get()->gurobiEnabled() ) { - // Obtain from and store bounds into inputquery if it is not null. + // Obtain from and store bounds into inputquery if it is not null. if ( inputQuery ) _networkLevelReasoner->obtainCurrentBounds( *inputQuery ); else _networkLevelReasoner->obtainCurrentBounds(); - // TODO: Remove this block after getting ready to support sigmoid with MILP Bound Tightening. - if ( Options::get()->getMILPSolverBoundTighteningType() != MILPSolverBoundTighteningType::NONE - && _preprocessedQuery->getNonlinearConstraints().size() > 0 ) + // TODO: Remove this block after getting ready to support sigmoid with MILP Bound + // Tightening. + if ( Options::get()->getMILPSolverBoundTighteningType() != + MILPSolverBoundTighteningType::NONE && + _preprocessedQuery->getNonlinearConstraints().size() > 0 ) throw MarabouError( MarabouError::FEATURE_NOT_YET_SUPPORTED, - "Marabou doesn't support sigmoid with MILP Bound Tightening" ); + "Marabou doesn't support sigmoid with MILP Bound Tightening" ); switch ( Options::get()->getMILPSolverBoundTighteningType() ) { @@ -1610,19 +1607,14 @@ void Engine::performMILPSolverBoundedTightening( InputQuery *inputQuery ) { for ( const auto &tightening : tightenings ) { - if ( tightening._type == Tightening::LB && FloatUtils::gt( tightening._value, - inputQuery->getLowerBound - ( tightening._variable ) ) ) - inputQuery->setLowerBound( tightening._variable, - tightening._value ); + inputQuery->getLowerBound( tightening._variable ) ) ) + inputQuery->setLowerBound( tightening._variable, tightening._value ); if ( tightening._type == Tightening::UB && FloatUtils::lt( tightening._value, - inputQuery->getUpperBound - ( tightening._variable ) ) ) - inputQuery->setUpperBound( tightening._variable, - tightening._value ); + inputQuery->getUpperBound( tightening._variable ) ) ) + inputQuery->setUpperBound( tightening._variable, tightening._value ); } } else @@ -1644,8 +1636,8 @@ void Engine::performMILPSolverBoundedTighteningForSingleLayer( unsigned targetIn if ( _produceUNSATProofs ) return; - if ( _networkLevelReasoner && _isGurobyEnabled && !_performLpTighteningAfterSplit - && _milpSolverBoundTighteningType != MILPSolverBoundTighteningType::NONE ) + if ( _networkLevelReasoner && _isGurobyEnabled && !_performLpTighteningAfterSplit && + _milpSolverBoundTighteningType != MILPSolverBoundTighteningType::NONE ) { _networkLevelReasoner->obtainCurrentBounds(); _networkLevelReasoner->clearConstraintTightenings(); @@ -1795,8 +1787,7 @@ void Engine::restoreState( const EngineState &state ) throw MarabouError( MarabouError::RESTORING_ENGINE_FROM_INVALID_STATE ); ENGINE_LOG( "\tRestoring tableau state" ); - _tableau->restoreState( state._tableauState, - state._tableauStateStorageLevel ); + _tableau->restoreState( state._tableauState, state._tableauStateStorageLevel ); ENGINE_LOG( "\tRestoring constraint states" ); for ( auto &constraint : _plConstraints ) @@ -1989,8 +1980,7 @@ void Engine::applySplit( const PiecewiseLinearCaseSplit &split ) equation.isVariableMergingEquation( x1, x2 ) && // And only if the variables are not out of bounds ( !_tableau->isBasic( x1 ) || - !_tableau->basicOutOfBounds( _tableau->variableToIndex( x1 ) ) ) - && + !_tableau->basicOutOfBounds( _tableau->variableToIndex( x1 ) ) ) && ( !_tableau->isBasic( x2 ) || !_tableau->basicOutOfBounds( _tableau->variableToIndex( x2 ) ) ); @@ -2037,8 +2027,10 @@ void Engine::applySplit( const PiecewiseLinearCaseSplit &split ) if ( bound._type == Tightening::LB ) { - ENGINE_LOG( Stringf( "x%u: lower bound set to %.3lf", variable, bound._value ).ascii() ); - if ( _produceUNSATProofs && FloatUtils::gt( bound._value, _boundManager.getLowerBound( bound._variable ) ) ) + ENGINE_LOG( + Stringf( "x%u: lower bound set to %.3lf", variable, bound._value ).ascii() ); + if ( _produceUNSATProofs && + FloatUtils::gt( bound._value, _boundManager.getLowerBound( bound._variable ) ) ) { _boundManager.resetExplanation( variable, BoundType::LOWER ); updateGroundLowerBound( variable, bound._value ); @@ -2049,8 +2041,10 @@ void Engine::applySplit( const PiecewiseLinearCaseSplit &split ) } else { - ENGINE_LOG( Stringf( "x%u: upper bound set to %.3lf", variable, bound._value ).ascii() ); - if ( _produceUNSATProofs && FloatUtils::lt( bound._value, _boundManager.getUpperBound( bound._variable ) ) ) + ENGINE_LOG( + Stringf( "x%u: upper bound set to %.3lf", variable, bound._value ).ascii() ); + if ( _produceUNSATProofs && + FloatUtils::lt( bound._value, _boundManager.getUpperBound( bound._variable ) ) ) { _boundManager.resetExplanation( variable, BoundType::UPPER ); updateGroundUpperBound( variable, bound._value ); @@ -2128,7 +2122,8 @@ bool Engine::applyValidConstraintCaseSplit( PiecewiseLinearConstraint *constrain String constraintString; constraint->dump( constraintString ); ENGINE_LOG( Stringf( "A constraint has become valid. Dumping constraint: %s", - constraintString.ascii() ).ascii() ); + constraintString.ascii() ) + .ascii() ); constraint->setActiveConstraint( false ); PiecewiseLinearCaseSplit validSplit = constraint->getValidCaseSplit(); @@ -2147,7 +2142,8 @@ bool Engine::applyValidConstraintCaseSplit( PiecewiseLinearConstraint *constrain bool Engine::shouldCheckDegradation() { return _statistics.getLongAttribute( Statistics::NUM_MAIN_LOOP_ITERATIONS ) % - GlobalConfiguration::DEGRADATION_CHECKING_FREQUENCY == 0 ; + GlobalConfiguration::DEGRADATION_CHECKING_FREQUENCY == + 0; } bool Engine::highDegradation() @@ -2157,10 +2153,8 @@ bool Engine::highDegradation() double degradation = _degradationChecker.computeDegradation( *_tableau ); _statistics.setDoubleAttribute( Statistics::CURRENT_DEGRADATION, degradation ); if ( FloatUtils::gt( degradation, - _statistics.getDoubleAttribute - ( Statistics::MAX_DEGRADATION ) ) ) - _statistics.setDoubleAttribute( Statistics::MAX_DEGRADATION, - degradation ); + _statistics.getDoubleAttribute( Statistics::MAX_DEGRADATION ) ) ) + _statistics.setDoubleAttribute( Statistics::MAX_DEGRADATION, degradation ); bool result = FloatUtils::gt( degradation, GlobalConfiguration::DEGRADATION_THRESHOLD ); @@ -2181,17 +2175,16 @@ void Engine::tightenBoundsOnConstraintMatrix() struct timespec start = TimeUtils::sampleMicro(); if ( _statistics.getLongAttribute( Statistics::NUM_MAIN_LOOP_ITERATIONS ) % - GlobalConfiguration::BOUND_TIGHTING_ON_CONSTRAINT_MATRIX_FREQUENCY == 0 ) + GlobalConfiguration::BOUND_TIGHTING_ON_CONSTRAINT_MATRIX_FREQUENCY == + 0 ) { _rowBoundTightener->examineConstraintMatrix( true ); - _statistics.incLongAttribute - ( Statistics::NUM_BOUND_TIGHTENINGS_ON_CONSTRAINT_MATRIX ); + _statistics.incLongAttribute( Statistics::NUM_BOUND_TIGHTENINGS_ON_CONSTRAINT_MATRIX ); } struct timespec end = TimeUtils::sampleMicro(); - _statistics.incLongAttribute - ( Statistics::TOTAL_TIME_CONSTRAINT_MATRIX_BOUND_TIGHTENING_MICRO, - TimeUtils::timePassed( start, end ) ); + _statistics.incLongAttribute( Statistics::TOTAL_TIME_CONSTRAINT_MATRIX_BOUND_TIGHTENING_MICRO, + TimeUtils::timePassed( start, end ) ); } void Engine::explicitBasisBoundTightening() @@ -2217,9 +2210,8 @@ void Engine::explicitBasisBoundTightening() } struct timespec end = TimeUtils::sampleMicro(); - _statistics.incLongAttribute - ( Statistics::TOTAL_TIME_EXPLICIT_BASIS_BOUND_TIGHTENING_MICRO, - TimeUtils::timePassed( start, end ) ); + _statistics.incLongAttribute( Statistics::TOTAL_TIME_EXPLICIT_BASIS_BOUND_TIGHTENING_MICRO, + TimeUtils::timePassed( start, end ) ); } void Engine::performPrecisionRestoration( PrecisionRestorer::RestoreBasics restoreBasics ) @@ -2250,8 +2242,8 @@ void Engine::performPrecisionRestoration( PrecisionRestorer::RestoreBasics resto // First round, with basic restoration, still resulted in high degradation. // Try again! start = TimeUtils::sampleMicro(); - _precisionRestorer.restorePrecision( *this, *_tableau, _smtCore, - PrecisionRestorer::DO_NOT_RESTORE_BASICS ); + _precisionRestorer.restorePrecision( + *this, *_tableau, _smtCore, PrecisionRestorer::DO_NOT_RESTORE_BASICS ); end = TimeUtils::sampleMicro(); _statistics.incLongAttribute( Statistics::TOTAL_TIME_PRECISION_RESTORATION, TimeUtils::timePassed( start, end ) ); @@ -2260,9 +2252,10 @@ void Engine::performPrecisionRestoration( PrecisionRestorer::RestoreBasics resto // debug double afterSecond = _degradationChecker.computeDegradation( *_tableau ); if ( _verbosity > 0 ) - printf( "Performing 2nd precision restoration. Degradation before: %.15lf. After: %.15lf\n", - after, - afterSecond ); + printf( + "Performing 2nd precision restoration. Degradation before: %.15lf. After: %.15lf\n", + after, + afterSecond ); if ( highDegradation() ) throw MarabouError( MarabouError::RESTORATION_FAILED_TO_RESTORE_PRECISION ); @@ -2280,9 +2273,8 @@ void Engine::storeInitialEngineState() bool Engine::basisRestorationNeeded() const { - return - _basisRestorationRequired == Engine::STRONG_RESTORATION_NEEDED || - _basisRestorationRequired == Engine::WEAK_RESTORATION_NEEDED; + return _basisRestorationRequired == Engine::STRONG_RESTORATION_NEEDED || + _basisRestorationRequired == Engine::WEAK_RESTORATION_NEEDED; } const Statistics *Engine::getStatistics() const @@ -2352,9 +2344,10 @@ List Engine::getInputVariables() const void Engine::performSimulation() { if ( _simulationSize == 0 || !_networkLevelReasoner || - _milpSolverBoundTighteningType == MILPSolverBoundTighteningType::NONE || _produceUNSATProofs ) + _milpSolverBoundTighteningType == MILPSolverBoundTighteningType::NONE || + _produceUNSATProofs ) { - ENGINE_LOG( Stringf( "Skip simulation...").ascii() ); + ENGINE_LOG( Stringf( "Skip simulation..." ).ascii() ); return; } @@ -2366,8 +2359,9 @@ void Engine::performSimulation() for ( unsigned i = 0; i < _networkLevelReasoner->getLayer( 0 )->getSize(); ++i ) { - std::uniform_real_distribution distribution( _networkLevelReasoner->getLayer( 0 )->getLb( i ), - _networkLevelReasoner->getLayer( 0 )->getUb( i ) ); + std::uniform_real_distribution distribution( + _networkLevelReasoner->getLayer( 0 )->getLb( i ), + _networkLevelReasoner->getLayer( 0 )->getUb( i ) ); Vector simulationInput( _simulationSize ); for ( unsigned j = 0; j < _simulationSize; ++j ) @@ -2390,21 +2384,19 @@ void Engine::performSymbolicBoundTightening( InputQuery *inputQuery ) // Step 1: tell the NLR about the current bounds if ( inputQuery ) { - // Obtain from and store bounds into inputquery if it is not null. + // Obtain from and store bounds into inputquery if it is not null. _networkLevelReasoner->obtainCurrentBounds( *inputQuery ); } else - { + { // Get bounds from Tableau. _networkLevelReasoner->obtainCurrentBounds(); - } + } // Step 2: perform SBT - if ( _symbolicBoundTighteningType == - SymbolicBoundTighteningType::SYMBOLIC_BOUND_TIGHTENING ) + if ( _symbolicBoundTighteningType == SymbolicBoundTighteningType::SYMBOLIC_BOUND_TIGHTENING ) _networkLevelReasoner->symbolicBoundPropagation(); - else if ( _symbolicBoundTighteningType == - SymbolicBoundTighteningType::DEEP_POLY ) + else if ( _symbolicBoundTighteningType == SymbolicBoundTighteningType::DEEP_POLY ) _networkLevelReasoner->deepPolyPropagation(); // Step 3: Extract the bounds @@ -2415,24 +2407,19 @@ void Engine::performSymbolicBoundTightening( InputQuery *inputQuery ) { for ( const auto &tightening : tightenings ) { - if ( tightening._type == Tightening::LB && FloatUtils::gt( tightening._value, - inputQuery->getLowerBound - ( tightening._variable ) ) ) + inputQuery->getLowerBound( tightening._variable ) ) ) { - inputQuery->setLowerBound( tightening._variable, - tightening._value ); + inputQuery->setLowerBound( tightening._variable, tightening._value ); ++numTightenedBounds; } if ( tightening._type == Tightening::UB && FloatUtils::lt( tightening._value, - inputQuery->getUpperBound - ( tightening._variable ) ) ) + inputQuery->getUpperBound( tightening._variable ) ) ) { - inputQuery->setUpperBound( tightening._variable, - tightening._value ); + inputQuery->setUpperBound( tightening._variable, tightening._value ); ++numTightenedBounds; } } @@ -2441,16 +2428,17 @@ void Engine::performSymbolicBoundTightening( InputQuery *inputQuery ) { for ( const auto &tightening : tightenings ) { - if ( tightening._type == Tightening::LB && - FloatUtils::gt( tightening._value, _tableau->getLowerBound( tightening._variable ) ) ) + FloatUtils::gt( tightening._value, + _tableau->getLowerBound( tightening._variable ) ) ) { _tableau->tightenLowerBound( tightening._variable, tightening._value ); ++numTightenedBounds; } if ( tightening._type == Tightening::UB && - FloatUtils::lt( tightening._value, _tableau->getUpperBound( tightening._variable ) ) ) + FloatUtils::lt( tightening._value, + _tableau->getUpperBound( tightening._variable ) ) ) { _tableau->tightenUpperBound( tightening._variable, tightening._value ); ++numTightenedBounds; @@ -2482,7 +2470,8 @@ void Engine::preContextPushHook() _groundBoundManager.storeLocalBounds(); struct timespec end = TimeUtils::sampleMicro(); - _statistics.incLongAttribute( Statistics::TIME_CONTEXT_PUSH_HOOK, TimeUtils::timePassed( start, end ) ); + _statistics.incLongAttribute( Statistics::TIME_CONTEXT_PUSH_HOOK, + TimeUtils::timePassed( start, end ) ); } void Engine::postContextPopHook() @@ -2495,7 +2484,8 @@ void Engine::postContextPopHook() _tableau->postContextPopHook(); struct timespec end = TimeUtils::sampleMicro(); - _statistics.incLongAttribute( Statistics::TIME_CONTEXT_POP_HOOK, TimeUtils::timePassed( start, end ) ); + _statistics.incLongAttribute( Statistics::TIME_CONTEXT_POP_HOOK, + TimeUtils::timePassed( start, end ) ); } void Engine::reset() @@ -2600,9 +2590,9 @@ void Engine::checkOverallProgress() { // Get fresh statistics unsigned numVisitedStates = - _statistics.getUnsignedAttribute( Statistics::NUM_VISITED_TREE_STATES); - unsigned long long currentIteration = _statistics.getLongAttribute - ( Statistics::NUM_MAIN_LOOP_ITERATIONS ); + _statistics.getUnsignedAttribute( Statistics::NUM_VISITED_TREE_STATES ); + unsigned long long currentIteration = + _statistics.getLongAttribute( Statistics::NUM_MAIN_LOOP_ITERATIONS ); if ( numVisitedStates > _lastNumVisitedStates ) { @@ -2614,10 +2604,10 @@ void Engine::checkOverallProgress() { // No progress has been made. If it's been too long, request a restoration if ( currentIteration > - _lastIterationWithProgress + - GlobalConfiguration::MAX_ITERATIONS_WITHOUT_PROGRESS ) + _lastIterationWithProgress + GlobalConfiguration::MAX_ITERATIONS_WITHOUT_PROGRESS ) { - ENGINE_LOG( "checkOverallProgress detected cycling. Requesting a precision restoration" ); + ENGINE_LOG( + "checkOverallProgress detected cycling. Requesting a precision restoration" ); _basisRestorationRequired = Engine::STRONG_RESTORATION_NEEDED; _lastIterationWithProgress = currentIteration; } @@ -2628,8 +2618,8 @@ void Engine::updateDirections() { if ( GlobalConfiguration::USE_POLARITY_BASED_DIRECTION_HEURISTICS ) for ( const auto &constraint : _plConstraints ) - if ( constraint->supportPolarity() && - constraint->isActive() && !constraint->phaseFixed() ) + if ( constraint->supportPolarity() && constraint->isActive() && + !constraint->phaseFixed() ) constraint->updateDirection(); } @@ -2643,7 +2633,7 @@ void Engine::decideBranchingHeuristics() { divideStrategy = DivideStrategy::LargestInterval; if ( _verbosity >= 2 ) - printf("Branching heuristics set to LargestInterval\n"); + printf( "Branching heuristics set to LargestInterval\n" ); } else { @@ -2651,13 +2641,13 @@ void Engine::decideBranchingHeuristics() { divideStrategy = DivideStrategy::PseudoImpact; if ( _verbosity >= 2 ) - printf("Branching heuristics set to PseudoImpact\n"); + printf( "Branching heuristics set to PseudoImpact\n" ); } else { divideStrategy = DivideStrategy::ReLUViolation; if ( _verbosity >= 2 ) - printf("Branching heuristics set to ReLUViolation\n"); + printf( "Branching heuristics set to ReLUViolation\n" ); } } } @@ -2679,21 +2669,20 @@ PiecewiseLinearConstraint *Engine::pickSplitPLConstraintBasedOnPolarity() Map scoreToConstraint; for ( auto &plConstraint : constraints ) { - if ( plConstraint->supportPolarity() && - plConstraint->isActive() && !plConstraint->phaseFixed() ) + if ( plConstraint->supportPolarity() && plConstraint->isActive() && + !plConstraint->phaseFixed() ) { plConstraint->updateScoreBasedOnPolarity(); scoreToConstraint[plConstraint->getScore()] = plConstraint; - if ( scoreToConstraint.size() >= - GlobalConfiguration::POLARITY_CANDIDATES_THRESHOLD ) + if ( scoreToConstraint.size() >= GlobalConfiguration::POLARITY_CANDIDATES_THRESHOLD ) break; } } if ( scoreToConstraint.size() > 0 ) { - ENGINE_LOG( Stringf( "Score of the picked ReLU: %f", - ( *scoreToConstraint.begin() ).first ).ascii() ); - return (*scoreToConstraint.begin()).second; + ENGINE_LOG( Stringf( "Score of the picked ReLU: %f", ( *scoreToConstraint.begin() ).first ) + .ascii() ); + return ( *scoreToConstraint.begin() ).second; } else return NULL; @@ -2727,8 +2716,7 @@ PiecewiseLinearConstraint *Engine::pickSplitPLConstraintBasedOnIntervalWidth() double largestIntervalSoFar = 0; for ( const auto &variable : _preprocessedQuery->getInputVariables() ) { - double interval = _tableau->getUpperBound( variable ) - - _tableau->getLowerBound( variable ); + double interval = _tableau->getUpperBound( variable ) - _tableau->getLowerBound( variable ); if ( interval > largestIntervalSoFar ) { inputVariableWithLargestInterval = variable; @@ -2740,27 +2728,26 @@ PiecewiseLinearConstraint *Engine::pickSplitPLConstraintBasedOnIntervalWidth() return NULL; else { - double mid = ( _tableau->getLowerBound( inputVariableWithLargestInterval ) - + _tableau->getUpperBound( inputVariableWithLargestInterval ) - ) / 2; + double mid = ( _tableau->getLowerBound( inputVariableWithLargestInterval ) + + _tableau->getUpperBound( inputVariableWithLargestInterval ) ) / + 2; PiecewiseLinearCaseSplit s1; - s1.storeBoundTightening( Tightening( inputVariableWithLargestInterval, - mid, Tightening::UB ) ); + s1.storeBoundTightening( + Tightening( inputVariableWithLargestInterval, mid, Tightening::UB ) ); PiecewiseLinearCaseSplit s2; - s2.storeBoundTightening( Tightening( inputVariableWithLargestInterval, - mid, Tightening::LB ) ); + s2.storeBoundTightening( + Tightening( inputVariableWithLargestInterval, mid, Tightening::LB ) ); List splits; splits.append( s1 ); splits.append( s2 ); - _disjunctionForSplitting = std::unique_ptr - ( new DisjunctionConstraint( splits ) ); + _disjunctionForSplitting = + std::unique_ptr( new DisjunctionConstraint( splits ) ); return _disjunctionForSplitting.get(); } } -PiecewiseLinearConstraint *Engine::pickSplitPLConstraint( DivideStrategy - strategy ) +PiecewiseLinearConstraint *Engine::pickSplitPLConstraint( DivideStrategy strategy ) { ENGINE_LOG( Stringf( "Picking a split PLConstraint..." ).ascii() ); @@ -2780,16 +2767,16 @@ PiecewiseLinearConstraint *Engine::pickSplitPLConstraint( DivideStrategy else if ( strategy == DivideStrategy::EarliestReLU ) candidatePLConstraint = pickSplitPLConstraintBasedOnTopology(); else if ( strategy == DivideStrategy::LargestInterval && - ( _smtCore.getStackDepth() % - GlobalConfiguration::INTERVAL_SPLITTING_FREQUENCY == 0 ) - ) + ( _smtCore.getStackDepth() % GlobalConfiguration::INTERVAL_SPLITTING_FREQUENCY == + 0 ) ) { // Conduct interval splitting periodically. candidatePLConstraint = pickSplitPLConstraintBasedOnIntervalWidth(); } - ENGINE_LOG( Stringf( ( candidatePLConstraint ? - "Picked..." : - "Unable to pick using the current strategy..." ) ).ascii() ); + ENGINE_LOG( + Stringf( ( candidatePLConstraint ? "Picked..." + : "Unable to pick using the current strategy..." ) ) + .ascii() ); return candidatePLConstraint; } @@ -2802,13 +2789,14 @@ PiecewiseLinearConstraint *Engine::pickSplitPLConstraintSnC( SnCDivideStrategy s candidatePLConstraint = pickSplitPLConstraintBasedOnTopology(); ENGINE_LOG( Stringf( "Done updating scores..." ).ascii() ); - ENGINE_LOG( Stringf( ( candidatePLConstraint ? - "Picked..." : - "Unable to pick using the current strategy..." ) ).ascii() ); + ENGINE_LOG( + Stringf( ( candidatePLConstraint ? "Picked..." + : "Unable to pick using the current strategy..." ) ) + .ascii() ); return candidatePLConstraint; } -bool Engine::restoreSmtState( SmtState & smtState ) +bool Engine::restoreSmtState( SmtState &smtState ) { try { @@ -2842,7 +2830,6 @@ bool Engine::restoreSmtState( SmtState & smtState ) do performSymbolicBoundTightening(); while ( applyAllValidConstraintCaseSplits() ); - } _boundManager.propagateTightenings(); } @@ -2869,7 +2856,7 @@ bool Engine::restoreSmtState( SmtState & smtState ) return true; } -void Engine::storeSmtState( SmtState & smtState ) +void Engine::storeSmtState( SmtState &smtState ) { _smtCore.storeSmtState( smtState ); } @@ -2903,8 +2890,7 @@ bool Engine::solveWithMILPEncoding( unsigned timeoutInSeconds ) _milpEncoder->encodeInputQuery( *_gurobi, *_preprocessedQuery ); ENGINE_LOG( "Query encoded in Gurobi...\n" ); - double timeoutForGurobi = ( timeoutInSeconds == 0 ? FloatUtils::infinity() - : timeoutInSeconds ); + double timeoutForGurobi = ( timeoutInSeconds == 0 ? FloatUtils::infinity() : timeoutInSeconds ); ENGINE_LOG( Stringf( "Gurobi timeout set to %f\n", timeoutForGurobi ).ascii() ) _gurobi->setTimeLimit( timeoutForGurobi ); if ( !_sncMode ) @@ -2995,8 +2981,7 @@ bool Engine::performDeepSoILocalSearch() // Update the cost function _soiManager->initializePhasePattern(); - LinearExpression initialPhasePattern = - _soiManager->getCurrentSoIPhasePattern(); + LinearExpression initialPhasePattern = _soiManager->getCurrentSoIPhasePattern(); if ( initialPhasePattern.isZero() ) { @@ -3010,8 +2995,8 @@ bool Engine::performDeepSoILocalSearch() _soiManager->updateCurrentPhasePatternForSatisfiedPLConstraints(); // Always accept the first phase pattern. _soiManager->acceptCurrentPhasePattern(); - double costOfLastAcceptedPhasePattern = computeHeuristicCost - ( _soiManager->getCurrentSoIPhasePattern() ); + double costOfLastAcceptedPhasePattern = + computeHeuristicCost( _soiManager->getCurrentSoIPhasePattern() ); double costOfProposedPhasePattern = FloatUtils::infinity(); bool lastProposalAccepted = true; @@ -3039,7 +3024,7 @@ bool Engine::performDeepSoILocalSearch() { if ( _lpSolverType == LPSolverType::NATIVE && _tableau->getBasicAssignmentStatus() != - ITableau::BASIC_ASSIGNMENT_JUST_COMPUTED ) + ITableau::BASIC_ASSIGNMENT_JUST_COMPUTED ) { if ( _verbosity > 0 ) { @@ -3074,8 +3059,8 @@ bool Engine::performDeepSoILocalSearch() _soiManager->proposePhasePatternUpdate(); minimizeHeuristicCost( _soiManager->getCurrentSoIPhasePattern() ); _soiManager->updateCurrentPhasePatternForSatisfiedPLConstraints(); - costOfProposedPhasePattern = computeHeuristicCost - ( _soiManager->getCurrentSoIPhasePattern() ); + costOfProposedPhasePattern = + computeHeuristicCost( _soiManager->getCurrentSoIPhasePattern() ); // We have the "local" effect of change the cost term of some // PLConstraints in the phase pattern. Use this information to influence @@ -3084,8 +3069,8 @@ bool Engine::performDeepSoILocalSearch() costOfProposedPhasePattern ); // Decide whether to accept the last proposal. - if ( _soiManager->decideToAcceptCurrentProposal - ( costOfLastAcceptedPhasePattern, costOfProposedPhasePattern ) ) + if ( _soiManager->decideToAcceptCurrentProposal( costOfLastAcceptedPhasePattern, + costOfProposedPhasePattern ) ) { _soiManager->acceptCurrentPhasePattern(); costOfLastAcceptedPhasePattern = costOfProposedPhasePattern; @@ -3110,9 +3095,8 @@ void Engine::minimizeHeuristicCost( const LinearExpression &heuristicCost ) { minimizeCostWithGurobi( heuristicCost ); - ENGINE_LOG - ( Stringf( "Current heuristic cost: %f", - _gurobi->getOptimalCostOrObjective() ).ascii() ); + ENGINE_LOG( + Stringf( "Current heuristic cost: %f", _gurobi->getOptimalCostOrObjective() ).ascii() ); } else { @@ -3127,9 +3111,9 @@ void Engine::minimizeHeuristicCost( const LinearExpression &heuristicCost ) mainLoopStatistics(); if ( _verbosity > 1 && - _statistics.getLongAttribute - ( Statistics::NUM_MAIN_LOOP_ITERATIONS ) % - _statisticsPrintingFrequency == 0 ) + _statistics.getLongAttribute( Statistics::NUM_MAIN_LOOP_ITERATIONS ) % + _statisticsPrintingFrequency == + 0 ) _statistics.print(); if ( !allVarsWithinBounds() ) @@ -3143,9 +3127,8 @@ void Engine::minimizeHeuristicCost( const LinearExpression &heuristicCost ) localOptimumReached = performSimplexStep(); } _tableau->toggleOptimization( false ); - ENGINE_LOG - ( Stringf( "Current heuristic cost: %f", - computeHeuristicCost( heuristicCost ) ).ascii() ); + ENGINE_LOG( Stringf( "Current heuristic cost: %f", computeHeuristicCost( heuristicCost ) ) + .ascii() ); } ENGINE_LOG( "Optimizing w.r.t. the current heuristic cost - done\n" ); @@ -3153,13 +3136,12 @@ void Engine::minimizeHeuristicCost( const LinearExpression &heuristicCost ) double Engine::computeHeuristicCost( const LinearExpression &heuristicCost ) { - return ( _costFunctionManager-> - computeGivenCostFunctionDirectly( heuristicCost._addends ) + + return ( _costFunctionManager->computeGivenCostFunctionDirectly( heuristicCost._addends ) + heuristicCost._constant ); } void Engine::updatePseudoImpactWithSoICosts( double costOfLastAcceptedPhasePattern, - double costOfProposedPhasePattern ) + double costOfProposedPhasePattern ) { ASSERT( _soiManager ); @@ -3169,9 +3151,8 @@ void Engine::updatePseudoImpactWithSoICosts( double costOfLastAcceptedPhasePatte // proposal. In the Sum of Infeasibilities paper, only one constraint // is updated each time. But we might consider alternative proposal // strategy in the future. - double score = ( fabs( costOfLastAcceptedPhasePattern - - costOfProposedPhasePattern ) - / constraintsUpdated.size() ); + double score = ( fabs( costOfLastAcceptedPhasePattern - costOfProposedPhasePattern ) / + constraintsUpdated.size() ); ASSERT( constraintsUpdated.size() > 0 ); // Update the Pseudo-Impact estimation. @@ -3186,8 +3167,8 @@ void Engine::bumpUpPseudoImpactOfPLConstraintsNotInSoI() { if ( plConstraint->isActive() && !plConstraint->supportSoI() && !plConstraint->phaseFixed() && !plConstraint->satisfied() ) - _smtCore.updatePLConstraintScore - ( plConstraint, GlobalConfiguration::SCORE_BUMP_FOR_PL_CONSTRAINTS_NOT_IN_SOI ); + _smtCore.updatePLConstraintScore( + plConstraint, GlobalConfiguration::SCORE_BUMP_FOR_PL_CONSTRAINTS_NOT_IN_SOI ); } } @@ -3204,9 +3185,8 @@ void Engine::informLPSolverOfBounds() } _gurobi->updateModel(); struct timespec end = TimeUtils::sampleMicro(); - _statistics.incLongAttribute - ( Statistics::TIME_ADDING_CONSTRAINTS_TO_MILP_SOLVER_MICRO, - TimeUtils::timePassed( start, end ) ); + _statistics.incLongAttribute( Statistics::TIME_ADDING_CONSTRAINTS_TO_MILP_SOLVER_MICRO, + TimeUtils::timePassed( start, end ) ); } else { @@ -3228,7 +3208,7 @@ bool Engine::minimizeCostWithGurobi( const LinearExpression &costFunction ) struct timespec simplexEnd = TimeUtils::sampleMicro(); _statistics.incLongAttribute( Statistics::TIME_SIMPLEX_STEPS_MICRO, - TimeUtils::timePassed( simplexStart, simplexEnd ) ); + TimeUtils::timePassed( simplexStart, simplexEnd ) ); _statistics.incLongAttribute( Statistics::NUM_SIMPLEX_STEPS, _gurobi->getNumberOfSimplexIterations() ); @@ -3238,8 +3218,7 @@ bool Engine::minimizeCostWithGurobi( const LinearExpression &costFunction ) return true; else throw CommonError( CommonError::UNEXPECTED_GUROBI_STATUS, - Stringf( "Current status: %u", - _gurobi->getStatusCode() ).ascii() ); + Stringf( "Current status: %u", _gurobi->getStatusCode() ).ascii() ); return false; } @@ -3255,22 +3234,26 @@ void Engine::checkGurobiBoundConsistency() const double lowerBound = _tableau->getLowerBound( i ); if ( !FloatUtils::areEqual( gurobiLowerBound, lowerBound ) ) { - throw MarabouError - ( MarabouError::BOUNDS_NOT_UP_TO_DATE_IN_LP_SOLVER, - Stringf( "x%u lower bound inconsistent!" - " Gurobi: %f, Tableau: %f", - i, gurobiLowerBound, lowerBound ).ascii() ); + throw MarabouError( MarabouError::BOUNDS_NOT_UP_TO_DATE_IN_LP_SOLVER, + Stringf( "x%u lower bound inconsistent!" + " Gurobi: %f, Tableau: %f", + i, + gurobiLowerBound, + lowerBound ) + .ascii() ); } double gurobiUpperBound = _gurobi->getUpperBound( iName ); double upperBound = _tableau->getUpperBound( i ); if ( !FloatUtils::areEqual( gurobiUpperBound, upperBound ) ) { - throw MarabouError - ( MarabouError::BOUNDS_NOT_UP_TO_DATE_IN_LP_SOLVER, - Stringf( "x%u upper bound inconsistent!" - " Gurobi: %f, Tableau: %f", - i, gurobiUpperBound, upperBound ).ascii() ); + throw MarabouError( MarabouError::BOUNDS_NOT_UP_TO_DATE_IN_LP_SOLVER, + Stringf( "x%u upper bound inconsistent!" + " Gurobi: %f, Tableau: %f", + i, + gurobiUpperBound, + upperBound ) + .ascii() ); } } } @@ -3281,9 +3264,11 @@ bool Engine::consistentBounds() const return _boundManager.consistentBounds(); } -InputQuery Engine::buildQueryFromCurrentState() const { +InputQuery Engine::buildQueryFromCurrentState() const +{ InputQuery query = *_preprocessedQuery; - for ( unsigned i = 0; i < query.getNumberOfVariables(); ++i ) { + for ( unsigned i = 0; i < query.getNumberOfVariables(); ++i ) + { query.setLowerBound( i, _tableau->getLowerBound( i ) ); query.setUpperBound( i, _tableau->getUpperBound( i ) ); } @@ -3294,20 +3279,21 @@ void Engine::updateGroundUpperBound( const unsigned var, const double value ) { ASSERT( var < _tableau->getN() && _produceUNSATProofs ); if ( FloatUtils::lt( value, _groundBoundManager.getUpperBound( var ) ) ) - _groundBoundManager.setUpperBound( var, value ); + _groundBoundManager.setUpperBound( var, value ); } void Engine::updateGroundLowerBound( const unsigned var, const double value ) { ASSERT( var < _tableau->getN() && _produceUNSATProofs ); if ( FloatUtils::gt( value, _groundBoundManager.getLowerBound( var ) ) ) - _groundBoundManager.setLowerBound( var, value ); + _groundBoundManager.setLowerBound( var, value ); } double Engine::getGroundBound( unsigned var, bool isUpper ) const { ASSERT( var < _tableau->getN() && _produceUNSATProofs ); - return isUpper ? _groundBoundManager.getUpperBound( var ) : _groundBoundManager.getLowerBound( var ); + return isUpper ? _groundBoundManager.getUpperBound( var ) + : _groundBoundManager.getLowerBound( var ); } bool Engine::shouldProduceProofs() const @@ -3323,7 +3309,8 @@ void Engine::explainSimplexFailure() unsigned infeasibleVar = _boundManager.getInconsistentVariable(); - if ( infeasibleVar == IBoundManager::NO_VARIABLE_FOUND || !certifyInfeasibility( infeasibleVar ) ) + if ( infeasibleVar == IBoundManager::NO_VARIABLE_FOUND || + !certifyInfeasibility( infeasibleVar ) ) infeasibleVar = explainFailureWithTableau(); if ( infeasibleVar == IBoundManager::NO_VARIABLE_FOUND ) @@ -3342,7 +3329,8 @@ void Engine::explainSimplexFailure() } ASSERT( infeasibleVar < _tableau->getN() ); - ASSERT( _UNSATCertificateCurrentPointer && !( **_UNSATCertificateCurrentPointer ).getContradiction() ); + ASSERT( _UNSATCertificateCurrentPointer && + !( **_UNSATCertificateCurrentPointer ).getContradiction() ); _statistics.incUnsignedAttribute( Statistics::NUM_CERTIFIED_LEAVES ); writeContradictionToCertificate( infeasibleVar ); @@ -3357,18 +3345,26 @@ bool Engine::certifyInfeasibility( unsigned var ) const Vector contradiction = computeContradiction( var ); if ( contradiction.empty() ) - return FloatUtils::isNegative( _groundBoundManager.getUpperBound( var ) - _groundBoundManager.getLowerBound( var ) ); + return FloatUtils::isNegative( _groundBoundManager.getUpperBound( var ) - + _groundBoundManager.getLowerBound( var ) ); SparseUnsortedList sparseContradiction = SparseUnsortedList(); - contradiction.empty() ? sparseContradiction.initializeToEmpty() : sparseContradiction.initialize( contradiction.data(), contradiction.size() ); + contradiction.empty() + ? sparseContradiction.initializeToEmpty() + : sparseContradiction.initialize( contradiction.data(), contradiction.size() ); // In case contradiction is a vector of zeros if ( sparseContradiction.empty() ) - return FloatUtils::isNegative( _groundBoundManager.getUpperBound( var ) - _groundBoundManager.getLowerBound( var ) ); - - double derivedBound = UNSATCertificateUtils::computeCombinationUpperBound( sparseContradiction, _tableau->getSparseA(), - _groundBoundManager.getUpperBounds(), _groundBoundManager.getLowerBounds(), _tableau->getN() ); + return FloatUtils::isNegative( _groundBoundManager.getUpperBound( var ) - + _groundBoundManager.getLowerBound( var ) ); + + double derivedBound = + UNSATCertificateUtils::computeCombinationUpperBound( sparseContradiction, + _tableau->getSparseA(), + _groundBoundManager.getUpperBounds(), + _groundBoundManager.getLowerBounds(), + _tableau->getN() ); return FloatUtils::isNegative( derivedBound ); } @@ -3382,10 +3378,15 @@ double Engine::explainBound( unsigned var, bool isUpper ) const explanation = _boundManager.getExplanation( var, isUpper ); if ( explanation.empty() ) - return isUpper ? _groundBoundManager.getUpperBound( var ) : _groundBoundManager.getLowerBound( var ); - - return UNSATCertificateUtils::computeBound( var, isUpper, explanation, _tableau->getSparseA(), - _groundBoundManager.getUpperBounds(), _groundBoundManager.getLowerBounds(), + return isUpper ? _groundBoundManager.getUpperBound( var ) + : _groundBoundManager.getLowerBound( var ); + + return UNSATCertificateUtils::computeBound( var, + isUpper, + explanation, + _tableau->getSparseA(), + _groundBoundManager.getUpperBounds(), + _groundBoundManager.getLowerBounds(), _tableau->getN() ); } @@ -3400,16 +3401,24 @@ bool Engine::validateBounds( unsigned var, double epsilon, bool isUpper ) const real = _boundManager.getUpperBound( var ); if ( explained - real > epsilon ) { - ENGINE_LOG( "Var %d. Computed Upper %.5lf, real %.5lf. Difference is %.10lf\n", var, explained, real, abs( explained - real ) ); + ENGINE_LOG( "Var %d. Computed Upper %.5lf, real %.5lf. Difference is %.10lf\n", + var, + explained, + real, + abs( explained - real ) ); return false; } } else { real = _boundManager.getLowerBound( var ); - if ( explained - real < -epsilon ) + if ( explained - real < -epsilon ) { - ENGINE_LOG( "Var %d. Computed Lower %.5lf, real %.5lf. Difference is %.10lf\n", var, explained, real, abs( explained - real ) ); + ENGINE_LOG( "Var %d. Computed Lower %.5lf, real %.5lf. Difference is %.10lf\n", + var, + explained, + real, + abs( explained - real ) ); return false; } } @@ -3423,7 +3432,8 @@ bool Engine::validateAllBounds( double epsilon ) const bool res = true; for ( unsigned var = 0; var < _tableau->getN(); ++var ) - if ( !validateBounds( var, epsilon, BoundType::UPPER ) || !validateBounds( var, epsilon, BoundType::LOWER ) ) + if ( !validateBounds( var, epsilon, BoundType::UPPER ) || + !validateBounds( var, epsilon, BoundType::LOWER ) ) res = false; return res; @@ -3435,8 +3445,10 @@ bool Engine::checkGroundBounds() const for ( unsigned i = 0; i < _tableau->getN(); ++i ) { - if ( FloatUtils::gt( _groundBoundManager.getLowerBound( i ), _boundManager.getLowerBound( i ) ) || - FloatUtils::lt( _groundBoundManager.getUpperBound( i ), _boundManager.getUpperBound( i ) ) ) + if ( FloatUtils::gt( _groundBoundManager.getLowerBound( i ), + _boundManager.getLowerBound( i ) ) || + FloatUtils::lt( _groundBoundManager.getUpperBound( i ), + _boundManager.getUpperBound( i ) ) ) return false; } return true; @@ -3449,7 +3461,8 @@ unsigned Engine::explainFailureWithTableau() // Failure of a simplex step implies infeasible bounds imposed by the row TableauRow boundUpdateRow = TableauRow( _tableau->getN() ); - // For every basic, check that is has no slack and its explanations indeed prove a contradiction + // For every basic, check that is has no slack and its explanations indeed prove a + // contradiction unsigned basicVar; for ( unsigned i = 0; i < _tableau->getM(); ++i ) @@ -3459,12 +3472,14 @@ unsigned Engine::explainFailureWithTableau() _tableau->getTableauRow( i, &boundUpdateRow ); basicVar = boundUpdateRow._lhs; - if ( FloatUtils::gt( _boundManager.computeRowBound( boundUpdateRow, BoundType::LOWER ), _boundManager.getUpperBound( basicVar ) ) - && explainAndCheckContradiction( basicVar, BoundType::LOWER, &boundUpdateRow ) ) + if ( FloatUtils::gt( _boundManager.computeRowBound( boundUpdateRow, BoundType::LOWER ), + _boundManager.getUpperBound( basicVar ) ) && + explainAndCheckContradiction( basicVar, BoundType::LOWER, &boundUpdateRow ) ) return basicVar; - if ( FloatUtils::lt( _boundManager.computeRowBound( boundUpdateRow, BoundType::UPPER ), _boundManager.getLowerBound( basicVar ) ) - && explainAndCheckContradiction( basicVar, BoundType::UPPER, &boundUpdateRow ) ) + if ( FloatUtils::lt( _boundManager.computeRowBound( boundUpdateRow, BoundType::UPPER ), + _boundManager.getLowerBound( basicVar ) ) && + explainAndCheckContradiction( basicVar, BoundType::UPPER, &boundUpdateRow ) ) return basicVar; } } @@ -3494,10 +3509,12 @@ unsigned Engine::explainFailureWithCostFunction() curUpper = ( curCost < 0 ); // Check the basic variable has no slack - if ( !( !curUpper && FloatUtils::gt( _boundManager.computeSparseRowBound( *costRow, BoundType::LOWER, curBasicVar ), - _boundManager.getUpperBound( curBasicVar ) ) ) && - !( curUpper && FloatUtils::lt( _boundManager.computeSparseRowBound( *costRow, BoundType::UPPER, curBasicVar ), - _boundManager.getLowerBound( curBasicVar ) ) ) ) + if ( !( !curUpper && FloatUtils::gt( _boundManager.computeSparseRowBound( + *costRow, BoundType::LOWER, curBasicVar ), + _boundManager.getUpperBound( curBasicVar ) ) ) && + !( curUpper && FloatUtils::lt( _boundManager.computeSparseRowBound( + *costRow, BoundType::UPPER, curBasicVar ), + _boundManager.getLowerBound( curBasicVar ) ) ) ) continue; @@ -3532,7 +3549,9 @@ bool Engine::explainAndCheckContradiction( unsigned var, bool isUpper, const Tab return false; } -bool Engine::explainAndCheckContradiction( unsigned var, bool isUpper, const SparseUnsortedList *row ) +bool Engine::explainAndCheckContradiction( unsigned var, + bool isUpper, + const SparseUnsortedList *row ) { ASSERT( _produceUNSATProofs ); @@ -3574,8 +3593,10 @@ bool Engine::certifyUNSATCertificate() { if ( !UNSATCertificateUtils::getSupportedActivations().exists( constraint->getType() ) ) { - String activationType = constraint->serializeToString().tokenize(",").back(); - printf( "Certification Error! Network contains activation function %s, that is not yet supported by Marabou certification.\n", activationType.ascii() ); + String activationType = constraint->serializeToString().tokenize( "," ).back(); + printf( "Certification Error! Network contains activation function %s, that is not yet " + "supported by Marabou certification.\n", + activationType.ascii() ); return false; } } @@ -3595,35 +3616,50 @@ bool Engine::certifyUNSATCertificate() if ( GlobalConfiguration::WRITE_JSON_PROOF ) { File file( JsonWriter::PROOF_FILENAME ); - JsonWriter::writeProofToJson( _UNSATCertificate, _tableau->getM(), _tableau->getSparseA(), - groundUpperBounds, groundLowerBounds, _plConstraints, file ); - } - - Checker unsatCertificateChecker( _UNSATCertificate, _tableau->getM(), _tableau->getSparseA(), - groundUpperBounds, groundLowerBounds, _plConstraints ); + JsonWriter::writeProofToJson( _UNSATCertificate, + _tableau->getM(), + _tableau->getSparseA(), + groundUpperBounds, + groundLowerBounds, + _plConstraints, + file ); + } + + Checker unsatCertificateChecker( _UNSATCertificate, + _tableau->getM(), + _tableau->getSparseA(), + groundUpperBounds, + groundLowerBounds, + _plConstraints ); bool certificationSucceeded = unsatCertificateChecker.check(); - _statistics.setLongAttribute( Statistics::TOTAL_CERTIFICATION_TIME, TimeUtils::timePassed( certificationStart, TimeUtils::sampleMicro() ) ); + _statistics.setLongAttribute( + Statistics::TOTAL_CERTIFICATION_TIME, + TimeUtils::timePassed( certificationStart, TimeUtils::sampleMicro() ) ); printf( "Certification time: " ); - _statistics.printLongAttributeAsTime( _statistics.getLongAttribute( Statistics::TOTAL_CERTIFICATION_TIME ) ); + _statistics.printLongAttributeAsTime( + _statistics.getLongAttribute( Statistics::TOTAL_CERTIFICATION_TIME ) ); if ( certificationSucceeded ) { - printf("Certified\n"); + printf( "Certified\n" ); if ( _statistics.getUnsignedAttribute( Statistics::NUM_DELEGATED_LEAVES ) ) - printf( "Some leaves were delegated and need to be certified separately by an SMT solver\n" ); + printf( "Some leaves were delegated and need to be certified separately by an SMT " + "solver\n" ); } else printf( "Error certifying UNSAT certificate\n" ); - DEBUG({ + DEBUG( { ASSERT( certificationSucceeded ); if ( _statistics.getUnsignedAttribute( Statistics::NUM_POPS ) ) { - double delegationRatio = _statistics.getUnsignedAttribute( Statistics::NUM_DELEGATED_LEAVES ) / _statistics.getUnsignedAttribute( Statistics::NUM_CERTIFIED_LEAVES ); + double delegationRatio = + _statistics.getUnsignedAttribute( Statistics::NUM_DELEGATED_LEAVES ) / + _statistics.getUnsignedAttribute( Statistics::NUM_CERTIFIED_LEAVES ); ASSERT( FloatUtils::lt( delegationRatio, 0.01 ) ); } - }); + } ); return certificationSucceeded; } @@ -3634,7 +3670,7 @@ void Engine::markLeafToDelegate() // Mark leaf with toDelegate Flag UnsatCertificateNode *currentUnsatCertificateNode = _UNSATCertificateCurrentPointer->get(); - ASSERT( _UNSATCertificateCurrentPointer && ! currentUnsatCertificateNode->getContradiction() ); + ASSERT( _UNSATCertificateCurrentPointer && !currentUnsatCertificateNode->getContradiction() ); currentUnsatCertificateNode->setDelegationStatus( DelegationStatus::DELEGATE_SAVE ); currentUnsatCertificateNode->deletePLCExplanations(); _statistics.incUnsignedAttribute( Statistics::NUM_DELEGATED_LEAVES ); @@ -3679,7 +3715,9 @@ void Engine::writeContradictionToCertificate( unsigned infeasibleVar ) const Vector leafContradictionVec = computeContradiction( infeasibleVar ); - Contradiction *leafContradiction = leafContradictionVec.empty() ? new Contradiction( infeasibleVar ) : new Contradiction( leafContradictionVec ); + Contradiction *leafContradiction = leafContradictionVec.empty() + ? new Contradiction( infeasibleVar ) + : new Contradiction( leafContradictionVec ); ( **_UNSATCertificateCurrentPointer ).setContradiction( leafContradiction ); } diff --git a/src/engine/Engine.h b/src/engine/Engine.h index 038f288cbe..811013f90b 100644 --- a/src/engine/Engine.h +++ b/src/engine/Engine.h @@ -31,32 +31,32 @@ #include "IEngine.h" #include "InputQuery.h" #include "JsonWriter.h" -#include "LinearExpression.h" #include "LPSolverType.h" -#include "Map.h" +#include "LinearExpression.h" #include "MILPEncoder.h" +#include "Map.h" #include "Options.h" #include "PrecisionRestorer.h" #include "Preprocessor.h" #include "SignalHandler.h" #include "SmtCore.h" +#include "SmtLibWriter.h" #include "SnCDivideStrategy.h" #include "SparseUnsortedList.h" #include "Statistics.h" #include "SumOfInfeasibilitiesManager.h" #include "SymbolicBoundTighteningType.h" -#include "SmtLibWriter.h" #include "UnsatCertificateNode.h" -#include #include +#include #ifdef _WIN32 #undef ERROR #endif -#define ENGINE_LOG(x, ...) LOG(GlobalConfiguration::ENGINE_LOGGING, "Engine: %s\n", x) +#define ENGINE_LOG( x, ... ) LOG( GlobalConfiguration::ENGINE_LOGGING, "Engine: %s\n", x ) class EngineState; class InputQuery; @@ -66,11 +66,13 @@ class String; using CVC4::context::Context; -class Engine : public IEngine, public SignalHandler::Signalable +class Engine + : public IEngine + , public SignalHandler::Signalable { public: enum { - MICROSECONDS_TO_SECONDS = 1000000, + MICROSECONDS_TO_SECONDS = 1000000, }; Engine(); @@ -100,7 +102,7 @@ class Engine : public IEngine, public SignalHandler::Signalable bool processInputQuery( InputQuery &inputQuery ); bool processInputQuery( InputQuery &inputQuery, bool preprocess ); - InputQuery prepareSnCInputQuery( ); + InputQuery prepareSnCInputQuery(); void exportInputQueryWithError( String errorMessage ); /* @@ -258,7 +260,7 @@ class Engine : public IEngine, public SignalHandler::Signalable void updateGroundLowerBound( unsigned var, double value ); /* - Return all ground bounds as a vector + Return all ground bounds as a vector */ double getGroundBound( unsigned var, bool isUpper ) const; @@ -270,7 +272,7 @@ class Engine : public IEngine, public SignalHandler::Signalable /* Set the current pointer of the UNSAT certificate */ - void setUNSATCertificateCurrentPointer( UnsatCertificateNode *node ); + void setUNSATCertificateCurrentPointer( UnsatCertificateNode *node ); /* Get the pointer to the root of the UNSAT certificate @@ -278,8 +280,8 @@ class Engine : public IEngine, public SignalHandler::Signalable const UnsatCertificateNode *getUNSATCertificateRoot() const; /* - Certify the UNSAT certificate - */ + Certify the UNSAT certificate + */ bool certifyUNSATCertificate(); /* @@ -296,8 +298,8 @@ class Engine : public IEngine, public SignalHandler::Signalable Propagate bound tightenings stored in the BoundManager */ void propagateBoundManagerTightenings(); -private: +private: enum BasisRestorationRequired { RESTORATION_NOT_NEEDED = 0, STRONG_RESTORATION_NEEDED = 1, @@ -709,13 +711,16 @@ class Engine : public IEngine, public SignalHandler::Signalable void printInputBounds( const InputQuery &inputQuery ) const; void storeEquationsInDegradationChecker(); void removeRedundantEquations( const double *constraintMatrix ); - void selectInitialVariablesForBasis( const double *constraintMatrix, List &initialBasis, List &basicRows ); + void selectInitialVariablesForBasis( const double *constraintMatrix, + List &initialBasis, + List &basicRows ); void initializeTableau( const double *constraintMatrix, const List &initialBasis ); void initializeBoundsAndConstraintWatchersInTableau( unsigned numberOfVariables ); void initializeNetworkLevelReasoning(); double *createConstraintMatrix(); void addAuxiliaryVariables(); - void augmentInitialBasisIfNeeded( List &initialBasis, const List &basicRows ); + void augmentInitialBasisIfNeeded( List &initialBasis, + const List &basicRows ); void performMILPSolverBoundedTightening( InputQuery *inputQuery = nullptr ); /* @@ -800,7 +805,10 @@ class Engine : public IEngine, public SignalHandler::Signalable /* Get Context reference */ - Context &getContext() { return _context; } + Context &getContext() + { + return _context; + } /* Checks whether the current bounds are consistent. Exposed for the SmtCore. @@ -820,7 +828,7 @@ class Engine : public IEngine, public SignalHandler::Signalable bool _produceUNSATProofs; BoundManager _groundBoundManager; UnsatCertificateNode *_UNSATCertificate; - CVC4::context::CDO *_UNSATCertificateCurrentPointer; + CVC4::context::CDO *_UNSATCertificateCurrentPointer; /* Returns true iff there is a variable with bounds that can explain infeasibility of the tableau @@ -830,7 +838,7 @@ class Engine : public IEngine, public SignalHandler::Signalable /* Returns the value of a variable bound, as explained by the BoundExplainer */ - double explainBound( unsigned var, bool isUpper ) const; + double explainBound( unsigned var, bool isUpper ) const; /* Returns true iff both bounds are epsilon close to their explained bounds @@ -848,7 +856,8 @@ class Engine : public IEngine, public SignalHandler::Signalable void explainSimplexFailure(); /* - Sanity check for ground bounds, returns true iff all bounds are at least as tight as their ground bounds + Sanity check for ground bounds, returns true iff all bounds are at least as tight as their + ground bounds */ bool checkGroundBounds() const; @@ -863,8 +872,8 @@ class Engine : public IEngine, public SignalHandler::Signalable unsigned explainFailureWithCostFunction(); /* - Updates an explanation of a bound according to a row, and checks for an explained contradiction. - If a contradiction can be deduced, return true. Else, revert and return false + Updates an explanation of a bound according to a row, and checks for an explained + contradiction. If a contradiction can be deduced, return true. Else, revert and return false */ bool explainAndCheckContradiction( unsigned var, bool isUpper, const TableauRow *row ); bool explainAndCheckContradiction( unsigned var, bool isUpper, const SparseUnsortedList *row ); diff --git a/src/engine/EntrySelectionStrategy.h b/src/engine/EntrySelectionStrategy.h index 8ba23132ae..4948ec58c9 100644 --- a/src/engine/EntrySelectionStrategy.h +++ b/src/engine/EntrySelectionStrategy.h @@ -26,13 +26,13 @@ class EntrySelectionStrategy { public: EntrySelectionStrategy(); - virtual ~EntrySelectionStrategy() {}; + virtual ~EntrySelectionStrategy(){}; /* Perform any necessary initialization work for this strategy. This is done in the engine after the tableau is set up. */ - virtual void initialize( const ITableau & /* tableau */ ) {}; + virtual void initialize( const ITableau & /* tableau */ ){}; /* Choose the entrying variable for the given tableau. Do not pick @@ -46,17 +46,17 @@ class EntrySelectionStrategy This hook gets called after the entering and leaving variables have been selected, but before the actual pivot. */ - virtual void prePivotHook( const ITableau &/* tableau */, bool /* fakePivot */ ) {}; + virtual void prePivotHook( const ITableau & /* tableau */, bool /* fakePivot */ ){}; /* This hook gets called the pivot operation has been performed. */ - virtual void postPivotHook( const ITableau &/* tableau */, bool /* fakePivot */ ) {}; + virtual void postPivotHook( const ITableau & /* tableau */, bool /* fakePivot */ ){}; /* This hook is called when the tableau has been resized. */ - virtual void resizeHook( const ITableau &/* tableau */ ) {}; + virtual void resizeHook( const ITableau & /* tableau */ ){}; /* For reporting statistics diff --git a/src/engine/Equation.cpp b/src/engine/Equation.cpp index 7d5a060bfb..293ad75aaa 100644 --- a/src/engine/Equation.cpp +++ b/src/engine/Equation.cpp @@ -14,6 +14,7 @@ **/ #include "Equation.h" + #include "FloatUtils.h" #include "MStringf.h" #include "Map.h" @@ -89,10 +90,8 @@ void Equation::updateVariableIndex( unsigned oldVar, unsigned newVar ) bool Equation::operator==( const Equation &other ) const { - return - ( _addends == other._addends ) && - ( _scalar == other._scalar ) && - ( _type == other._type ); + return ( _addends == other._addends ) && ( _scalar == other._scalar ) && + ( _type == other._type ); } bool Equation::equivalent( const Equation &other ) const @@ -210,7 +209,7 @@ double Equation::getCoefficient( unsigned variable ) const return 0; } -void Equation::setCoefficient( unsigned variable, double newCoefficient) +void Equation::setCoefficient( unsigned variable, double newCoefficient ) { for ( auto &addend : _addends ) { @@ -221,7 +220,7 @@ void Equation::setCoefficient( unsigned variable, double newCoefficient) } } - addAddend(newCoefficient, variable); + addAddend( newCoefficient, variable ); } void Equation::removeRedundantAddends() @@ -248,8 +247,7 @@ bool Equation::containsRedundantAddends() const Set addends; for ( auto &addend : _addends ) { - if ( addends.exists( addend._variable ) || - FloatUtils::isZero( addend._coefficient ) ) + if ( addends.exists( addend._variable ) || FloatUtils::isZero( addend._coefficient ) ) return true; addends.insert( addend._variable ); } diff --git a/src/engine/IBoundManager.h b/src/engine/IBoundManager.h index 18936cd4d9..b72b481dea 100644 --- a/src/engine/IBoundManager.h +++ b/src/engine/IBoundManager.h @@ -26,13 +26,13 @@ #ifndef __IBoundManager_h__ #define __IBoundManager_h__ -#include #include "List.h" -#include "Vector.h" #include "PiecewiseLinearFunctionType.h" +#include "Vector.h" -enum BoundType : unsigned -{ +#include + +enum BoundType : unsigned { LOWER = 0, UPPER = 1, }; @@ -45,9 +45,9 @@ class IRowBoundTightener; class IBoundManager { public: - const static constexpr unsigned NO_VARIABLE_FOUND = UINT32_MAX -1; + const static constexpr unsigned NO_VARIABLE_FOUND = UINT32_MAX - 1; - virtual ~IBoundManager() {}; + virtual ~IBoundManager(){}; /* Registers a new variable, grows the BoundManager size and bound vectors, @@ -87,8 +87,8 @@ class IBoundManager /* Get pointers to latest bounds used for access by tableau and tighteners */ - virtual const double * getLowerBounds() const = 0; - virtual const double * getUpperBounds() const = 0; + virtual const double *getLowerBounds() const = 0; + virtual const double *getUpperBounds() const = 0; /* * Store and restore bounds after push/pop @@ -122,26 +122,33 @@ class IBoundManager virtual bool tightenLowerBound( unsigned variable, double value, const TableauRow &row ) = 0; virtual bool tightenUpperBound( unsigned variable, double value, const TableauRow &row ) = 0; - virtual bool tightenLowerBound( unsigned variable, double value, const SparseUnsortedList &row ) = 0; - virtual bool tightenUpperBound( unsigned variable, double value, const SparseUnsortedList &row ) = 0; + virtual bool + tightenLowerBound( unsigned variable, double value, const SparseUnsortedList &row ) = 0; + virtual bool + tightenUpperBound( unsigned variable, double value, const SparseUnsortedList &row ) = 0; /* Add a lemma to the UNSATCertificateNode object Return true iff adding the lemma was successful */ - virtual bool addLemmaExplanationAndTightenBound( unsigned var, double value, BoundType affectedVarBound, - const List &causingVars, BoundType causingVarBound, - PiecewiseLinearFunctionType constraintType ) = 0; + virtual bool + addLemmaExplanationAndTightenBound( unsigned var, + double value, + BoundType affectedVarBound, + const List &causingVars, + BoundType causingVarBound, + PiecewiseLinearFunctionType constraintType ) = 0; /* - Return the content of the object containing all explanations for variable bounds in the tableau + Return the content of the object containing all explanations for variable bounds in the + tableau */ virtual const BoundExplainer *getBoundExplainer() const = 0; /* Deep-copy the BoundExplainer object content */ - virtual void copyBoundExplainerContent( const BoundExplainer* boundExplainer ) = 0; + virtual void copyBoundExplainerContent( const BoundExplainer *boundExplainer ) = 0; /* Initialize the boundExplainer @@ -154,9 +161,11 @@ class IBoundManager virtual void updateBoundExplanation( const TableauRow &row, bool isUpper, unsigned var ) = 0; /* - Given a row as SparseUnsortedList, updates the values of the bound explanations of a var according to the row + Given a row as SparseUnsortedList, updates the values of the bound explanations of a var + according to the row */ - virtual void updateBoundExplanationSparse( const SparseUnsortedList &row, bool isUpper, unsigned var ) = 0; + virtual void + updateBoundExplanationSparse( const SparseUnsortedList &row, bool isUpper, unsigned var ) = 0; /* Get the index of a variable with inconsistent bounds, if exists, or -1 otherwise diff --git a/src/engine/IConstraintMatrixAnalyzer.h b/src/engine/IConstraintMatrixAnalyzer.h index 6e703ea717..0b56c02557 100644 --- a/src/engine/IConstraintMatrixAnalyzer.h +++ b/src/engine/IConstraintMatrixAnalyzer.h @@ -24,7 +24,7 @@ class SparseUnsortedList; class IConstraintMatrixAnalyzer { public: - virtual ~IConstraintMatrixAnalyzer() {}; + virtual ~IConstraintMatrixAnalyzer(){}; virtual void analyze( const double *matrix, unsigned m, unsigned n ) = 0; virtual void analyze( const SparseUnsortedList **matrix, unsigned m, unsigned n ) = 0; diff --git a/src/engine/ICostFunctionManager.h b/src/engine/ICostFunctionManager.h index f92bed624c..9bc34a3890 100644 --- a/src/engine/ICostFunctionManager.h +++ b/src/engine/ICostFunctionManager.h @@ -30,13 +30,14 @@ class ICostFunctionManager COST_FUNCTION_UPDATED = 2, }; - virtual ~ICostFunctionManager() {}; + virtual ~ICostFunctionManager(){}; virtual void initialize() = 0; virtual ICostFunctionManager::CostFunctionStatus getCostFunctionStatus() const = 0; virtual void computeCostFunction( const Map &heuristicCost ) = 0; virtual void computeGivenCostFunction( const Map &heuristicCost ) = 0; - virtual double computeGivenCostFunctionDirectly( const Map &heuristicCost ) = 0; + virtual double + computeGivenCostFunctionDirectly( const Map &heuristicCost ) = 0; virtual void computeCoreCostFunction() = 0; virtual const double *getCostFunction() const = 0; virtual void dumpCostFunction() const = 0; diff --git a/src/engine/IEngine.h b/src/engine/IEngine.h index ba28e26d03..6187e40f32 100644 --- a/src/engine/IEngine.h +++ b/src/engine/IEngine.h @@ -18,11 +18,11 @@ #include "BoundExplainer.h" #include "DivideStrategy.h" +#include "List.h" #include "SnCDivideStrategy.h" #include "TableauStateStorageLevel.h" -#include "List.h" -#include "context/context.h" #include "Vector.h" +#include "context/context.h" #ifdef _WIN32 #undef ERROR @@ -39,7 +39,7 @@ class UnsatCertificateNode; class IEngine { public: - virtual ~IEngine() {}; + virtual ~IEngine(){}; enum ExitCode { UNSAT = 0, @@ -107,24 +107,23 @@ class IEngine /* Pick the piecewise linear constraint for internal splitting */ - virtual PiecewiseLinearConstraint *pickSplitPLConstraint( DivideStrategy - strategy ) = 0; + virtual PiecewiseLinearConstraint *pickSplitPLConstraint( DivideStrategy strategy ) = 0; /* Pick the piecewise linear constraint for SnC splitting */ - virtual PiecewiseLinearConstraint *pickSplitPLConstraintSnC( SnCDivideStrategy - strategy ) = 0; + virtual PiecewiseLinearConstraint *pickSplitPLConstraintSnC( SnCDivideStrategy strategy ) = 0; /* - Return the value of a variable bound, as expressed by the bounds explainer and the initial bounds + Return the value of a variable bound, as expressed by the bounds explainer and the initial + bounds */ - virtual double explainBound( unsigned var, bool isUpper ) const = 0; + virtual double explainBound( unsigned var, bool isUpper ) const = 0; - /* - * Update the ground bounds - */ - virtual void updateGroundUpperBound( unsigned var, double value ) = 0; - virtual void updateGroundLowerBound( unsigned var, double value ) = 0; + /* + * Update the ground bounds + */ + virtual void updateGroundUpperBound( unsigned var, double value ) = 0; + virtual void updateGroundLowerBound( unsigned var, double value ) = 0; virtual void applyAllBoundTightenings() = 0; diff --git a/src/engine/IProjectedSteepestEdge.h b/src/engine/IProjectedSteepestEdge.h index 0ad917d52f..82368aaaba 100644 --- a/src/engine/IProjectedSteepestEdge.h +++ b/src/engine/IProjectedSteepestEdge.h @@ -25,7 +25,7 @@ class ITableau; class IProjectedSteepestEdgeRule : public EntrySelectionStrategy { public: - virtual ~IProjectedSteepestEdgeRule() {}; + virtual ~IProjectedSteepestEdgeRule(){}; /* Allocate and initialize data structures according to the size of the tableau. diff --git a/src/engine/IRowBoundTightener.h b/src/engine/IRowBoundTightener.h index c305a27661..cbf75e71bc 100644 --- a/src/engine/IRowBoundTightener.h +++ b/src/engine/IRowBoundTightener.h @@ -19,10 +19,12 @@ #include "ITableau.h" #include "Tightening.h" -class IRowBoundTightener : public ITableau::VariableWatcher, public ITableau::ResizeWatcher +class IRowBoundTightener + : public ITableau::VariableWatcher + , public ITableau::ResizeWatcher { public: - virtual ~IRowBoundTightener() {}; + virtual ~IRowBoundTightener(){}; /* Allocate internal work memory according to the tableau size. @@ -75,7 +77,6 @@ class IRowBoundTightener : public ITableau::VariableWatcher, public ITableau::Re Update pointers to local lower/upper bounds in BoundManager */ virtual void setBoundsPointers( const double *lower, const double *upper ) = 0; - }; #endif // __IRowBoundTightener_h__ diff --git a/src/engine/ITableau.h b/src/engine/ITableau.h index 16c3d9d4bf..ca4d9dc1c3 100644 --- a/src/engine/ITableau.h +++ b/src/engine/ITableau.h @@ -67,8 +67,12 @@ class ITableau These callbacks will be invoked when the variable's lower/upper bounds change. */ - virtual void notifyLowerBound( unsigned /* variable */, double /* bound */ ) {} - virtual void notifyUpperBound( unsigned /* variable */, double /* bound */ ) {} + virtual void notifyLowerBound( unsigned /* variable */, double /* bound */ ) + { + } + virtual void notifyUpperBound( unsigned /* variable */, double /* bound */ ) + { + } }; class ResizeWatcher @@ -78,7 +82,9 @@ class ITableau This callback will be invoked when the tableau size changes, typically when new variables are added. */ - virtual void notifyDimensionChange( unsigned /* m */, unsigned /* n */ ) {} + virtual void notifyDimensionChange( unsigned /* m */, unsigned /* n */ ) + { + } }; virtual void registerToWatchAllVariables( VariableWatcher *watcher ) = 0; @@ -89,7 +95,7 @@ class ITableau virtual void registerCostFunctionManager( ICostFunctionManager *costFunctionManager ) = 0; - virtual ~ITableau() {}; + virtual ~ITableau(){}; virtual void setDimensions( unsigned m, unsigned n ) = 0; virtual void setConstraintMatrix( const double *A ) = 0; @@ -131,7 +137,8 @@ class ITableau virtual void setChangeRatio( double changeRatio ) = 0; virtual bool performingFakePivot() const = 0; virtual void performPivot() = 0; - virtual double ratioConstraintPerBasic( unsigned basicIndex, double coefficient, bool decrease ) = 0; + virtual double + ratioConstraintPerBasic( unsigned basicIndex, double coefficient, bool decrease ) = 0; virtual bool isBasic( unsigned variable ) const = 0; virtual void setNonBasicAssignment( unsigned variable, double value, bool updateBasics ) = 0; virtual void computeCostFunction() = 0; @@ -181,7 +188,10 @@ class ITableau virtual double *getInverseBasisMatrix() const = 0; virtual void refreshBasisFactorization() = 0; virtual void mergeColumns( unsigned x1, unsigned x2 ) = 0; - virtual bool areLinearlyDependent( unsigned x1, unsigned x2, double &coefficient, double &inverseCoefficient ) = 0; + virtual bool areLinearlyDependent( unsigned x1, + unsigned x2, + double &coefficient, + double &inverseCoefficient ) = 0; virtual unsigned getVariableAfterMerging( unsigned variable ) const = 0; virtual void postContextPopHook() = 0; virtual IBoundManager &getBoundManager() const = 0; diff --git a/src/engine/InputQuery.cpp b/src/engine/InputQuery.cpp index 81e9426da2..090a41f39d 100644 --- a/src/engine/InputQuery.cpp +++ b/src/engine/InputQuery.cpp @@ -13,25 +13,27 @@ **/ +#include "InputQuery.h" + #include "AutoFile.h" #include "BilinearConstraint.h" #include "Debug.h" #include "FloatUtils.h" -#include "InputQuery.h" #include "LeakyReluConstraint.h" #include "MStringf.h" #include "MarabouError.h" #include "MaxConstraint.h" -#include "RoundConstraint.h" #include "Options.h" +#include "RoundConstraint.h" #include "SoftmaxConstraint.h" #include "SymbolicBoundTighteningType.h" -#define INPUT_QUERY_LOG( x, ... ) LOG( GlobalConfiguration::INPUT_QUERY_LOGGING, "Input Query: %s\n", x ) +#define INPUT_QUERY_LOG( x, ... ) \ + LOG( GlobalConfiguration::INPUT_QUERY_LOGGING, "Input Query: %s\n", x ) InputQuery::InputQuery() : _ensureSameSourceLayerInNLR( Options::get()->getSymbolicBoundTighteningType() == - SymbolicBoundTighteningType::DEEP_POLY ) + SymbolicBoundTighteningType::DEEP_POLY ) , _networkLevelReasoner( NULL ) { } @@ -56,8 +58,10 @@ void InputQuery::setLowerBound( unsigned variable, double bound ) if ( variable >= _numberOfVariables ) { throw MarabouError( MarabouError::VARIABLE_INDEX_OUT_OF_RANGE, - Stringf( "Variable = %u, number of variables = %u (setLowerBound)", - variable, _numberOfVariables ).ascii() ); + Stringf( "Variable = %u, number of variables = %u (setLowerBound)", + variable, + _numberOfVariables ) + .ascii() ); } _lowerBounds[variable] = bound; @@ -68,8 +72,10 @@ void InputQuery::setUpperBound( unsigned variable, double bound ) if ( variable >= _numberOfVariables ) { throw MarabouError( MarabouError::VARIABLE_INDEX_OUT_OF_RANGE, - Stringf( "Variable = %u, number of variables = %u (setUpperBound)", - variable, _numberOfVariables ).ascii() ); + Stringf( "Variable = %u, number of variables = %u (setUpperBound)", + variable, + _numberOfVariables ) + .ascii() ); } _upperBounds[variable] = bound; @@ -95,8 +101,10 @@ double InputQuery::getLowerBound( unsigned variable ) const if ( variable >= _numberOfVariables ) { throw MarabouError( MarabouError::VARIABLE_INDEX_OUT_OF_RANGE, - Stringf( "Variable = %u, number of variables = %u (getLowerBound)", - variable, _numberOfVariables ).ascii() ); + Stringf( "Variable = %u, number of variables = %u (getLowerBound)", + variable, + _numberOfVariables ) + .ascii() ); } if ( !_lowerBounds.exists( variable ) ) @@ -110,8 +118,10 @@ double InputQuery::getUpperBound( unsigned variable ) const if ( variable >= _numberOfVariables ) { throw MarabouError( MarabouError::VARIABLE_INDEX_OUT_OF_RANGE, - Stringf( "Variable = %u, number of variables = %u (getUpperBound)", - variable, _numberOfVariables ).ascii() ); + Stringf( "Variable = %u, number of variables = %u (getUpperBound)", + variable, + _numberOfVariables ) + .ascii() ); } if ( !_upperBounds.exists( variable ) ) @@ -153,7 +163,7 @@ double InputQuery::getSolutionValue( unsigned variable ) const { if ( !_solution.exists( variable ) ) throw MarabouError( MarabouError::VARIABLE_DOESNT_EXIST_IN_SOLUTION, - Stringf( "Variable: %u", variable ).ascii() ); + Stringf( "Variable: %u", variable ).ascii() ); return _solution.get( variable ); } @@ -163,8 +173,7 @@ void InputQuery::addPiecewiseLinearConstraint( PiecewiseLinearConstraint *constr _plConstraints.append( constraint ); } -void InputQuery::addClipConstraint( unsigned b, unsigned f, - double floor, double ceiling ) +void InputQuery::addClipConstraint( unsigned b, unsigned f, double floor, double ceiling ) { /* f = clip(b, floor, ceiling) @@ -185,7 +194,7 @@ void InputQuery::addClipConstraint( unsigned b, unsigned f, eq1.setScalar( floor ); addEquation( eq1 ); unsigned aux2 = getNewVariable(); - PiecewiseLinearConstraint* r1 = new ReluConstraint( aux1, aux2 ); + PiecewiseLinearConstraint *r1 = new ReluConstraint( aux1, aux2 ); addPiecewiseLinearConstraint( r1 ); // aux2.5 = aux2 + floor // aux3 = -aux2.5 + ceiling @@ -198,7 +207,7 @@ void InputQuery::addClipConstraint( unsigned b, unsigned f, addEquation( eq2 ); unsigned aux4 = getNewVariable(); - PiecewiseLinearConstraint* r2 = new ReluConstraint( aux3, aux4 ); + PiecewiseLinearConstraint *r2 = new ReluConstraint( aux3, aux4 ); addPiecewiseLinearConstraint( r2 ); // aux4.5 = aux4 - ceiling @@ -341,11 +350,15 @@ InputQuery &InputQuery::operator=( const InputQuery &other ) else { INPUT_QUERY_LOG( Stringf( "Number of piecewise linear constraints in input query: %u", - other._plConstraints.size() ).ascii() ); + other._plConstraints.size() ) + .ascii() ); INPUT_QUERY_LOG( Stringf( "Number of nonlinear constraints in input query: %u", - other._nlConstraints.size() ).ascii() ); - INPUT_QUERY_LOG( Stringf( "Number of piecewise linear constraints in topological order %u", - other._networkLevelReasoner->getConstraintsInTopologicalOrder().size() ).ascii() ); + other._nlConstraints.size() ) + .ascii() ); + INPUT_QUERY_LOG( + Stringf( "Number of piecewise linear constraints in topological order %u", + other._networkLevelReasoner->getConstraintsInTopologicalOrder().size() ) + .ascii() ); unsigned numberOfDisjunctions = 0; unsigned numberOfMaxs = 0; @@ -358,22 +371,21 @@ InputQuery &InputQuery::operator=( const InputQuery &other ) ++numberOfDisjunctions; } else if ( constraint->getType() == MAX && - !other._networkLevelReasoner->getConstraintsInTopologicalOrder().exists( constraint ) ) + !other._networkLevelReasoner->getConstraintsInTopologicalOrder().exists( + constraint ) ) { auto *newPlc = constraint->duplicateConstraint(); _plConstraints.append( newPlc ); ++numberOfMaxs; } - } ASSERT( other._networkLevelReasoner->getConstraintsInTopologicalOrder().size() + - numberOfDisjunctions + - numberOfMaxs - == other._plConstraints.size() ); + numberOfDisjunctions + numberOfMaxs == + other._plConstraints.size() ); - for ( const auto &constraint : other._networkLevelReasoner-> - getConstraintsInTopologicalOrder() ) + for ( const auto &constraint : + other._networkLevelReasoner->getConstraintsInTopologicalOrder() ) { auto *newPlc = constraint->duplicateConstraint(); _plConstraints.append( newPlc ); @@ -447,7 +459,8 @@ void InputQuery::saveQuery( const String &fileName ) printf( "Number of lower bounds: %u\n", _lowerBounds.size() ); printf( "Number of upper bounds: %u\n", _upperBounds.size() ); printf( "Number of equations: %u\n", _equations.size() ); - printf( "Number of non-linear constraints: %u\n", _plConstraints.size() + _nlConstraints.size() ); + printf( "Number of non-linear constraints: %u\n", + _plConstraints.size() + _nlConstraints.size() ); // Number of Input Variables queryFile->write( Stringf( "\n%u", getNumInputVariables() ) ); @@ -591,7 +604,6 @@ void InputQuery::printAllBounds() const else printf( "+INF]" ); printf( "\n" ); - } printf( "\n\n" ); @@ -634,7 +646,8 @@ void InputQuery::dump() const printf( "Variable bounds:\n" ); for ( unsigned i = 0; i < _numberOfVariables; ++i ) { - printf( "\t %u: [%s, %s]\n", i, + printf( "\t %u: [%s, %s]\n", + i, _lowerBounds.exists( i ) ? Stringf( "%lf", _lowerBounds[i] ).ascii() : "-inf", _upperBounds.exists( i ) ? Stringf( "%lf", _upperBounds[i] ).ascii() : "inf" ); } @@ -648,10 +661,10 @@ void InputQuery::dump() const } for ( const auto &ts : _nlConstraints ) - { + { ts->dump( constraintString ); printf( "\t%s\n", constraintString.ascii() ); - } + } printf( "Equations:\n" ); for ( const auto &e : _equations ) @@ -671,8 +684,9 @@ void InputQuery::adjustInputOutputMapping( const Map &oldInd for ( const auto &it : _inputIndexToVariable ) { if ( mergedVariables.exists( it.second ) ) - throw MarabouError( MarabouError::MERGED_INPUT_VARIABLE, - Stringf( "Input variable %u has been merged\n", it.second ).ascii() ); + throw MarabouError( + MarabouError::MERGED_INPUT_VARIABLE, + Stringf( "Input variable %u has been merged\n", it.second ).ascii() ); if ( oldIndexToNewIndex.exists( it.second ) ) { @@ -693,8 +707,9 @@ void InputQuery::adjustInputOutputMapping( const Map &oldInd for ( const auto &it : _outputIndexToVariable ) { if ( mergedVariables.exists( it.second ) ) - throw MarabouError( MarabouError::MERGED_OUTPUT_VARIABLE, - Stringf( "Output variable %u has been merged\n", it.second ).ascii() ); + throw MarabouError( + MarabouError::MERGED_OUTPUT_VARIABLE, + Stringf( "Output variable %u has been merged\n", it.second ).ascii() ); if ( oldIndexToNewIndex.exists( it.second ) ) { @@ -748,10 +763,12 @@ bool InputQuery::constructNetworkLevelReasoner() nlr->setNeuronVariable( NLR::NeuronIndex( 0, index ), inputVariable ); handledVariableToLayer[inputVariable] = 0; - inputLayer->setLb( index, _lowerBounds.exists( inputVariable ) ? - _lowerBounds[inputVariable] : FloatUtils::negativeInfinity() ); - inputLayer->setUb( index, _upperBounds.exists( inputVariable ) ? - _upperBounds[inputVariable] : FloatUtils::infinity() ); + inputLayer->setLb( index, + _lowerBounds.exists( inputVariable ) ? _lowerBounds[inputVariable] + : FloatUtils::negativeInfinity() ); + inputLayer->setUb( index, + _upperBounds.exists( inputVariable ) ? _upperBounds[inputVariable] + : FloatUtils::infinity() ); ++index; } @@ -767,8 +784,7 @@ bool InputQuery::constructNetworkLevelReasoner() constructSigmoidLayer( nlr, handledVariableToLayer, newLayerIndex ) || constructMaxLayer( nlr, handledVariableToLayer, newLayerIndex ) || constructBilinearLayer( nlr, handledVariableToLayer, newLayerIndex ) || - constructSoftmaxLayer( nlr, handledVariableToLayer, newLayerIndex ) - ) + constructSoftmaxLayer( nlr, handledVariableToLayer, newLayerIndex ) ) { ++newLayerIndex; } @@ -782,9 +798,10 @@ bool InputQuery::constructNetworkLevelReasoner() count += nlr->getLayer( i )->getSize(); INPUT_QUERY_LOG( Stringf( "successful. Constructed %u layers with %u neurons (out of %u)\n", - newLayerIndex, - count, - getNumberOfVariables() ).ascii() ); + newLayerIndex, + count, + getNumberOfVariables() ) + .ascii() ); _networkLevelReasoner = nlr; } @@ -805,7 +822,6 @@ bool InputQuery::constructWeighedSumLayer( NLR::NetworkLevelReasoner *nlr, struct NeuronInformation { public: - NeuronInformation( unsigned variable, unsigned neuron, const Equation *eq ) : _variable( variable ) , _neuron( neuron ) @@ -864,13 +880,16 @@ bool InputQuery::constructWeighedSumLayer( NLR::NetworkLevelReasoner *nlr, { handledVariableToLayer[newNeuron._variable] = newLayerIndex; - layer->setLb( newNeuron._neuron, _lowerBounds.exists( newNeuron._variable ) ? - _lowerBounds[newNeuron._variable] : FloatUtils::negativeInfinity() ); - layer->setUb( newNeuron._neuron, _upperBounds.exists( newNeuron._variable ) ? - _upperBounds[newNeuron._variable] : FloatUtils::infinity() ); + layer->setLb( newNeuron._neuron, + _lowerBounds.exists( newNeuron._variable ) ? _lowerBounds[newNeuron._variable] + : FloatUtils::negativeInfinity() ); + layer->setUb( newNeuron._neuron, + _upperBounds.exists( newNeuron._variable ) ? _upperBounds[newNeuron._variable] + : FloatUtils::infinity() ); // Add the new neuron - nlr->setNeuronVariable( NLR::NeuronIndex( newLayerIndex, newNeuron._neuron ), newNeuron._variable ); + nlr->setNeuronVariable( NLR::NeuronIndex( newLayerIndex, newNeuron._neuron ), + newNeuron._variable ); /* We assume equations have the form @@ -894,7 +913,8 @@ bool InputQuery::constructWeighedSumLayer( NLR::NetworkLevelReasoner *nlr, continue; unsigned sourceLayer = handledVariableToLayer[addend._variable]; - unsigned sourceNeuron = nlr->getLayer( sourceLayer )->variableToNeuron( addend._variable ); + unsigned sourceNeuron = + nlr->getLayer( sourceLayer )->variableToNeuron( addend._variable ); // Mark the layer dependency nlr->addLayerDependency( sourceLayer, newLayerIndex ); @@ -919,7 +939,6 @@ bool InputQuery::constructReluLayer( NLR::NetworkLevelReasoner *nlr, struct NeuronInformation { public: - NeuronInformation( unsigned variable, unsigned neuron, unsigned sourceVariable ) : _variable( variable ) , _neuron( neuron ) @@ -935,8 +954,7 @@ bool InputQuery::constructReluLayer( NLR::NetworkLevelReasoner *nlr, List newNeurons; // Look for ReLUs where all b variables have already been handled - const List &plConstraints = - getPiecewiseLinearConstraints(); + const List &plConstraints = getPiecewiseLinearConstraints(); unsigned currentSourceLayer = 0; for ( const auto &plc : plConstraints ) @@ -980,25 +998,26 @@ bool InputQuery::constructReluLayer( NLR::NetworkLevelReasoner *nlr, { handledVariableToLayer[newNeuron._variable] = newLayerIndex; - layer->setLb( newNeuron._neuron, _lowerBounds.exists( newNeuron._variable ) ? - _lowerBounds[newNeuron._variable] : FloatUtils::negativeInfinity() ); - layer->setUb( newNeuron._neuron, _upperBounds.exists( newNeuron._variable ) ? - _upperBounds[newNeuron._variable] : FloatUtils::infinity() ); + layer->setLb( newNeuron._neuron, + _lowerBounds.exists( newNeuron._variable ) ? _lowerBounds[newNeuron._variable] + : FloatUtils::negativeInfinity() ); + layer->setUb( newNeuron._neuron, + _upperBounds.exists( newNeuron._variable ) ? _upperBounds[newNeuron._variable] + : FloatUtils::infinity() ); unsigned sourceLayer = handledVariableToLayer[newNeuron._sourceVariable]; - unsigned sourceNeuron = nlr->getLayer( sourceLayer )->variableToNeuron( newNeuron._sourceVariable ); + unsigned sourceNeuron = + nlr->getLayer( sourceLayer )->variableToNeuron( newNeuron._sourceVariable ); // Mark the layer dependency nlr->addLayerDependency( sourceLayer, newLayerIndex ); // Add the new neuron - nlr->setNeuronVariable( NLR::NeuronIndex( newLayerIndex, newNeuron._neuron ), newNeuron._variable ); + nlr->setNeuronVariable( NLR::NeuronIndex( newLayerIndex, newNeuron._neuron ), + newNeuron._variable ); // Mark the activation connection - nlr->addActivationSource( sourceLayer, - sourceNeuron, - newLayerIndex, - newNeuron._neuron ); + nlr->addActivationSource( sourceLayer, sourceNeuron, newLayerIndex, newNeuron._neuron ); } INPUT_QUERY_LOG( "\tSuccessful!" ); @@ -1013,24 +1032,22 @@ bool InputQuery::constructLeakyReluLayer( NLR::NetworkLevelReasoner *nlr, struct NeuronInformation { public: + NeuronInformation( unsigned variable, unsigned neuron, unsigned sourceVariable ) + : _variable( variable ) + , _neuron( neuron ) + , _sourceVariable( sourceVariable ) + { + } - NeuronInformation( unsigned variable, unsigned neuron, unsigned sourceVariable ) - : _variable( variable ) - , _neuron( neuron ) - , _sourceVariable( sourceVariable ) - { - } - - unsigned _variable; - unsigned _neuron; - unsigned _sourceVariable; + unsigned _variable; + unsigned _neuron; + unsigned _sourceVariable; }; List newNeurons; // Look for LeakyReLUs where all b variables have already been handled - const List &plConstraints = - getPiecewiseLinearConstraints(); + const List &plConstraints = getPiecewiseLinearConstraints(); unsigned currentSourceLayer = 0; double alpha = 0; @@ -1060,7 +1077,8 @@ bool InputQuery::constructLeakyReluLayer( NLR::NetworkLevelReasoner *nlr, nlr->addConstraintInTopologicalOrder( plc ); double alphaTemp = leakyRelu->getSlope(); ASSERT( alphaTemp > 0 ); - if ( alpha != 0 && alpha != alphaTemp ) { + if ( alpha != 0 && alpha != alphaTemp ) + { throw NLRError( NLRError::LEAKY_RELU_SLOPES_NOT_UNIFORM ); } alpha = alphaTemp; @@ -1081,25 +1099,26 @@ bool InputQuery::constructLeakyReluLayer( NLR::NetworkLevelReasoner *nlr, { handledVariableToLayer[newNeuron._variable] = newLayerIndex; - layer->setLb( newNeuron._neuron, _lowerBounds.exists( newNeuron._variable ) ? - _lowerBounds[newNeuron._variable] : FloatUtils::negativeInfinity() ); - layer->setUb( newNeuron._neuron, _upperBounds.exists( newNeuron._variable ) ? - _upperBounds[newNeuron._variable] : FloatUtils::infinity() ); + layer->setLb( newNeuron._neuron, + _lowerBounds.exists( newNeuron._variable ) ? _lowerBounds[newNeuron._variable] + : FloatUtils::negativeInfinity() ); + layer->setUb( newNeuron._neuron, + _upperBounds.exists( newNeuron._variable ) ? _upperBounds[newNeuron._variable] + : FloatUtils::infinity() ); unsigned sourceLayer = handledVariableToLayer[newNeuron._sourceVariable]; - unsigned sourceNeuron = nlr->getLayer( sourceLayer )->variableToNeuron( newNeuron._sourceVariable ); + unsigned sourceNeuron = + nlr->getLayer( sourceLayer )->variableToNeuron( newNeuron._sourceVariable ); // Mark the layer dependency nlr->addLayerDependency( sourceLayer, newLayerIndex ); // Add the new neuron - nlr->setNeuronVariable( NLR::NeuronIndex( newLayerIndex, newNeuron._neuron ), newNeuron._variable ); + nlr->setNeuronVariable( NLR::NeuronIndex( newLayerIndex, newNeuron._neuron ), + newNeuron._variable ); // Mark the activation connection - nlr->addActivationSource( sourceLayer, - sourceNeuron, - newLayerIndex, - newNeuron._neuron ); + nlr->addActivationSource( sourceLayer, sourceNeuron, newLayerIndex, newNeuron._neuron ); } INPUT_QUERY_LOG( "\tSuccessful!" ); @@ -1114,7 +1133,6 @@ bool InputQuery::constructRoundLayer( NLR::NetworkLevelReasoner *nlr, struct NeuronInformation { public: - NeuronInformation( unsigned variable, unsigned neuron, unsigned sourceVariable ) : _variable( variable ) , _neuron( neuron ) @@ -1130,8 +1148,7 @@ bool InputQuery::constructRoundLayer( NLR::NetworkLevelReasoner *nlr, List newNeurons; // Look for ReLUs where all b variables have already been handled - const List &nlConstraints = - getNonlinearConstraints(); + const List &nlConstraints = getNonlinearConstraints(); unsigned currentSourceLayer = 0; for ( const auto &plc : nlConstraints ) @@ -1174,25 +1191,26 @@ bool InputQuery::constructRoundLayer( NLR::NetworkLevelReasoner *nlr, { handledVariableToLayer[newNeuron._variable] = newLayerIndex; - layer->setLb( newNeuron._neuron, _lowerBounds.exists( newNeuron._variable ) ? - _lowerBounds[newNeuron._variable] : FloatUtils::negativeInfinity() ); - layer->setUb( newNeuron._neuron, _upperBounds.exists( newNeuron._variable ) ? - _upperBounds[newNeuron._variable] : FloatUtils::infinity() ); + layer->setLb( newNeuron._neuron, + _lowerBounds.exists( newNeuron._variable ) ? _lowerBounds[newNeuron._variable] + : FloatUtils::negativeInfinity() ); + layer->setUb( newNeuron._neuron, + _upperBounds.exists( newNeuron._variable ) ? _upperBounds[newNeuron._variable] + : FloatUtils::infinity() ); unsigned sourceLayer = handledVariableToLayer[newNeuron._sourceVariable]; - unsigned sourceNeuron = nlr->getLayer( sourceLayer )->variableToNeuron( newNeuron._sourceVariable ); + unsigned sourceNeuron = + nlr->getLayer( sourceLayer )->variableToNeuron( newNeuron._sourceVariable ); // Mark the layer dependency nlr->addLayerDependency( sourceLayer, newLayerIndex ); // Add the new neuron - nlr->setNeuronVariable( NLR::NeuronIndex( newLayerIndex, newNeuron._neuron ), newNeuron._variable ); + nlr->setNeuronVariable( NLR::NeuronIndex( newLayerIndex, newNeuron._neuron ), + newNeuron._variable ); // Mark the activation connection - nlr->addActivationSource( sourceLayer, - sourceNeuron, - newLayerIndex, - newNeuron._neuron ); + nlr->addActivationSource( sourceLayer, sourceNeuron, newLayerIndex, newNeuron._neuron ); } INPUT_QUERY_LOG( "\tSuccessful!" ); @@ -1207,7 +1225,6 @@ bool InputQuery::constructSigmoidLayer( NLR::NetworkLevelReasoner *nlr, struct NeuronInformation { public: - NeuronInformation( unsigned variable, unsigned neuron, unsigned sourceVariable ) : _variable( variable ) , _neuron( neuron ) @@ -1223,8 +1240,7 @@ bool InputQuery::constructSigmoidLayer( NLR::NetworkLevelReasoner *nlr, List newNeurons; // Look for Sigmoids where all b variables have already been handled - const List &nlConstraints = - getNonlinearConstraints(); + const List &nlConstraints = getNonlinearConstraints(); unsigned currentSourceLayer = 0; for ( const auto &tsc : nlConstraints ) @@ -1267,25 +1283,26 @@ bool InputQuery::constructSigmoidLayer( NLR::NetworkLevelReasoner *nlr, { handledVariableToLayer[newNeuron._variable] = newLayerIndex; - layer->setLb( newNeuron._neuron, _lowerBounds.exists( newNeuron._variable ) ? - _lowerBounds[newNeuron._variable] : FloatUtils::negativeInfinity() ); - layer->setUb( newNeuron._neuron, _upperBounds.exists( newNeuron._variable ) ? - _upperBounds[newNeuron._variable] : FloatUtils::infinity() ); + layer->setLb( newNeuron._neuron, + _lowerBounds.exists( newNeuron._variable ) ? _lowerBounds[newNeuron._variable] + : FloatUtils::negativeInfinity() ); + layer->setUb( newNeuron._neuron, + _upperBounds.exists( newNeuron._variable ) ? _upperBounds[newNeuron._variable] + : FloatUtils::infinity() ); unsigned sourceLayer = handledVariableToLayer[newNeuron._sourceVariable]; - unsigned sourceNeuron = nlr->getLayer( sourceLayer )->variableToNeuron( newNeuron._sourceVariable ); + unsigned sourceNeuron = + nlr->getLayer( sourceLayer )->variableToNeuron( newNeuron._sourceVariable ); // Mark the layer dependency nlr->addLayerDependency( sourceLayer, newLayerIndex ); // Add the new neuron - nlr->setNeuronVariable( NLR::NeuronIndex( newLayerIndex, newNeuron._neuron ), newNeuron._variable ); + nlr->setNeuronVariable( NLR::NeuronIndex( newLayerIndex, newNeuron._neuron ), + newNeuron._variable ); // Mark the activation connection - nlr->addActivationSource( sourceLayer, - sourceNeuron, - newLayerIndex, - newNeuron._neuron ); + nlr->addActivationSource( sourceLayer, sourceNeuron, newLayerIndex, newNeuron._neuron ); } INPUT_QUERY_LOG( "\tSuccessful!" ); @@ -1300,7 +1317,6 @@ bool InputQuery::constructAbsoluteValueLayer( NLR::NetworkLevelReasoner *nlr, struct NeuronInformation { public: - NeuronInformation( unsigned variable, unsigned neuron, unsigned sourceVariable ) : _variable( variable ) , _neuron( neuron ) @@ -1316,8 +1332,7 @@ bool InputQuery::constructAbsoluteValueLayer( NLR::NetworkLevelReasoner *nlr, List newNeurons; // Look for ABSOLUTE_VALUEs where all b variables have already been handled - const List &plConstraints = - getPiecewiseLinearConstraints(); + const List &plConstraints = getPiecewiseLinearConstraints(); unsigned currentSourceLayer = 0; for ( const auto &plc : plConstraints ) @@ -1361,25 +1376,26 @@ bool InputQuery::constructAbsoluteValueLayer( NLR::NetworkLevelReasoner *nlr, { handledVariableToLayer[newNeuron._variable] = newLayerIndex; - layer->setLb( newNeuron._neuron, _lowerBounds.exists( newNeuron._variable ) ? - _lowerBounds[newNeuron._variable] : FloatUtils::negativeInfinity() ); - layer->setUb( newNeuron._neuron, _upperBounds.exists( newNeuron._variable ) ? - _upperBounds[newNeuron._variable] : FloatUtils::infinity() ); + layer->setLb( newNeuron._neuron, + _lowerBounds.exists( newNeuron._variable ) ? _lowerBounds[newNeuron._variable] + : FloatUtils::negativeInfinity() ); + layer->setUb( newNeuron._neuron, + _upperBounds.exists( newNeuron._variable ) ? _upperBounds[newNeuron._variable] + : FloatUtils::infinity() ); unsigned sourceLayer = handledVariableToLayer[newNeuron._sourceVariable]; - unsigned sourceNeuron = nlr->getLayer( sourceLayer )->variableToNeuron( newNeuron._sourceVariable ); + unsigned sourceNeuron = + nlr->getLayer( sourceLayer )->variableToNeuron( newNeuron._sourceVariable ); // Mark the layer dependency nlr->addLayerDependency( sourceLayer, newLayerIndex ); // Add the new neuron - nlr->setNeuronVariable( NLR::NeuronIndex( newLayerIndex, newNeuron._neuron ), newNeuron._variable ); + nlr->setNeuronVariable( NLR::NeuronIndex( newLayerIndex, newNeuron._neuron ), + newNeuron._variable ); // Mark the activation connection - nlr->addActivationSource( sourceLayer, - sourceNeuron, - newLayerIndex, - newNeuron._neuron ); + nlr->addActivationSource( sourceLayer, sourceNeuron, newLayerIndex, newNeuron._neuron ); } INPUT_QUERY_LOG( "\tSuccessful!" ); @@ -1394,7 +1410,6 @@ bool InputQuery::constructSignLayer( NLR::NetworkLevelReasoner *nlr, struct NeuronInformation { public: - NeuronInformation( unsigned variable, unsigned neuron, unsigned sourceVariable ) : _variable( variable ) , _neuron( neuron ) @@ -1410,8 +1425,7 @@ bool InputQuery::constructSignLayer( NLR::NetworkLevelReasoner *nlr, List newNeurons; // Look for Signs where the b variables have already been handled - const List &plConstraints = - getPiecewiseLinearConstraints(); + const List &plConstraints = getPiecewiseLinearConstraints(); unsigned currentSourceLayer = 0; for ( const auto &plc : plConstraints ) @@ -1455,25 +1469,26 @@ bool InputQuery::constructSignLayer( NLR::NetworkLevelReasoner *nlr, { handledVariableToLayer[newNeuron._variable] = newLayerIndex; - layer->setLb( newNeuron._neuron, _lowerBounds.exists( newNeuron._variable ) ? - _lowerBounds[newNeuron._variable] : FloatUtils::negativeInfinity() ); - layer->setUb( newNeuron._neuron, _upperBounds.exists( newNeuron._variable ) ? - _upperBounds[newNeuron._variable] : FloatUtils::infinity() ); + layer->setLb( newNeuron._neuron, + _lowerBounds.exists( newNeuron._variable ) ? _lowerBounds[newNeuron._variable] + : FloatUtils::negativeInfinity() ); + layer->setUb( newNeuron._neuron, + _upperBounds.exists( newNeuron._variable ) ? _upperBounds[newNeuron._variable] + : FloatUtils::infinity() ); unsigned sourceLayer = handledVariableToLayer[newNeuron._sourceVariable]; - unsigned sourceNeuron = nlr->getLayer( sourceLayer )->variableToNeuron( newNeuron._sourceVariable ); + unsigned sourceNeuron = + nlr->getLayer( sourceLayer )->variableToNeuron( newNeuron._sourceVariable ); // Mark the layer dependency nlr->addLayerDependency( sourceLayer, newLayerIndex ); // Add the new neuron - nlr->setNeuronVariable( NLR::NeuronIndex( newLayerIndex, newNeuron._neuron ), newNeuron._variable ); + nlr->setNeuronVariable( NLR::NeuronIndex( newLayerIndex, newNeuron._neuron ), + newNeuron._variable ); // Mark the activation connection - nlr->addActivationSource( sourceLayer, - sourceNeuron, - newLayerIndex, - newNeuron._neuron ); + nlr->addActivationSource( sourceLayer, sourceNeuron, newLayerIndex, newNeuron._neuron ); } INPUT_QUERY_LOG( "\tSuccessful!" ); @@ -1488,8 +1503,9 @@ bool InputQuery::constructMaxLayer( NLR::NetworkLevelReasoner *nlr, struct NeuronInformation { public: - - NeuronInformation( unsigned variable, unsigned neuron, const List &sourceVariables ) + NeuronInformation( unsigned variable, + unsigned neuron, + const List &sourceVariables ) : _variable( variable ) , _neuron( neuron ) , _sourceVariables( sourceVariables ) @@ -1504,8 +1520,7 @@ bool InputQuery::constructMaxLayer( NLR::NetworkLevelReasoner *nlr, List newNeurons; // Look for Maxes where all the element variables have already been handled - const List &plConstraints = - getPiecewiseLinearConstraints(); + const List &plConstraints = getPiecewiseLinearConstraints(); unsigned currentSourceLayer = 0; for ( const auto &plc : plConstraints ) @@ -1546,11 +1561,8 @@ bool InputQuery::constructMaxLayer( NLR::NetworkLevelReasoner *nlr, // Elements have been handled, f hasn't. Add f if ( _ensureSameSourceLayerInNLR && newNeurons.empty() ) currentSourceLayer = handledVariableToLayer[*max->getElements().begin()]; - newNeurons.append( NeuronInformation( f, - newNeurons.size(), - max->getElements() ) ); + newNeurons.append( NeuronInformation( f, newNeurons.size(), max->getElements() ) ); nlr->addConstraintInTopologicalOrder( plc ); - } // No neurons found for the new layer @@ -1567,27 +1579,28 @@ bool InputQuery::constructMaxLayer( NLR::NetworkLevelReasoner *nlr, { handledVariableToLayer[newNeuron._variable] = newLayerIndex; - layer->setLb( newNeuron._neuron, _lowerBounds.exists( newNeuron._variable ) ? - _lowerBounds[newNeuron._variable] : FloatUtils::negativeInfinity() ); - layer->setUb( newNeuron._neuron, _upperBounds.exists( newNeuron._variable ) ? - _upperBounds[newNeuron._variable] : FloatUtils::infinity() ); + layer->setLb( newNeuron._neuron, + _lowerBounds.exists( newNeuron._variable ) ? _lowerBounds[newNeuron._variable] + : FloatUtils::negativeInfinity() ); + layer->setUb( newNeuron._neuron, + _upperBounds.exists( newNeuron._variable ) ? _upperBounds[newNeuron._variable] + : FloatUtils::infinity() ); // Add the new neuron - nlr->setNeuronVariable( NLR::NeuronIndex( newLayerIndex, newNeuron._neuron ), newNeuron._variable ); + nlr->setNeuronVariable( NLR::NeuronIndex( newLayerIndex, newNeuron._neuron ), + newNeuron._variable ); for ( const auto &sourceVariable : newNeuron._sourceVariables ) { unsigned sourceLayer = handledVariableToLayer[sourceVariable]; - unsigned sourceNeuron = nlr->getLayer( sourceLayer )->variableToNeuron( sourceVariable ); + unsigned sourceNeuron = + nlr->getLayer( sourceLayer )->variableToNeuron( sourceVariable ); // Mark the layer dependency nlr->addLayerDependency( sourceLayer, newLayerIndex ); // Mark the activation connection - nlr->addActivationSource( sourceLayer, - sourceNeuron, - newLayerIndex, - newNeuron._neuron ); + nlr->addActivationSource( sourceLayer, sourceNeuron, newLayerIndex, newNeuron._neuron ); } } @@ -1596,105 +1609,104 @@ bool InputQuery::constructMaxLayer( NLR::NetworkLevelReasoner *nlr, } bool InputQuery::constructBilinearLayer( NLR::NetworkLevelReasoner *nlr, - Map &handledVariableToLayer, - unsigned newLayerIndex ) + Map &handledVariableToLayer, + unsigned newLayerIndex ) { - INPUT_QUERY_LOG( "Attempting to construct BilinearLayer..." ); - struct NeuronInformation - { - public: - - NeuronInformation( unsigned variable, unsigned neuron, const Vector &sourceVariables ) - : _variable( variable ) - , _neuron( neuron ) - , _sourceVariables( sourceVariables ) + INPUT_QUERY_LOG( "Attempting to construct BilinearLayer..." ); + struct NeuronInformation { - } + public: + NeuronInformation( unsigned variable, + unsigned neuron, + const Vector &sourceVariables ) + : _variable( variable ) + , _neuron( neuron ) + , _sourceVariables( sourceVariables ) + { + } - unsigned _variable; - unsigned _neuron; - Vector _sourceVariables; - }; + unsigned _variable; + unsigned _neuron; + Vector _sourceVariables; + }; - List newNeurons; + List newNeurons; - // Look for Bilinear constaints where all the element variables have already been handled - const List &nlConstraints = - getNonlinearConstraints(); + // Look for Bilinear constaints where all the element variables have already been handled + const List &nlConstraints = getNonlinearConstraints(); - for ( const auto &nlc : nlConstraints ) - { - // Only consider bilinear - if ( nlc->getType() != BILINEAR ) - continue; + for ( const auto &nlc : nlConstraints ) + { + // Only consider bilinear + if ( nlc->getType() != BILINEAR ) + continue; - const BilinearConstraint *bilinear = (const BilinearConstraint *)nlc; + const BilinearConstraint *bilinear = (const BilinearConstraint *)nlc; - // Have all elements been handled? - bool missingElement = false; - for ( const auto &element : bilinear->getBs() ) - { - if ( !handledVariableToLayer.exists( element ) ) - { - missingElement = true; - break; - } - } + // Have all elements been handled? + bool missingElement = false; + for ( const auto &element : bilinear->getBs() ) + { + if ( !handledVariableToLayer.exists( element ) ) + { + missingElement = true; + break; + } + } - if ( missingElement ) - continue; + if ( missingElement ) + continue; - // If the f variable has also been handled, ignore this constraint - unsigned f = bilinear->getF(); - if ( handledVariableToLayer.exists( f ) ) - continue; + // If the f variable has also been handled, ignore this constraint + unsigned f = bilinear->getF(); + if ( handledVariableToLayer.exists( f ) ) + continue; - // Elements have been handled, f hasn't. Add f - newNeurons.append( NeuronInformation( f, - newNeurons.size(), - bilinear->getBs() ) ); - } + // Elements have been handled, f hasn't. Add f + newNeurons.append( NeuronInformation( f, newNeurons.size(), bilinear->getBs() ) ); + } - // No neurons found for the new layer - if ( newNeurons.empty() ) - { - INPUT_QUERY_LOG( "\tFailed!" ); - return false; - } + // No neurons found for the new layer + if ( newNeurons.empty() ) + { + INPUT_QUERY_LOG( "\tFailed!" ); + return false; + } - nlr->addLayer( newLayerIndex, NLR::Layer::BILINEAR, newNeurons.size() ); + nlr->addLayer( newLayerIndex, NLR::Layer::BILINEAR, newNeurons.size() ); - NLR::Layer *layer = nlr->getLayer( newLayerIndex ); - for ( const auto &newNeuron : newNeurons ) - { - handledVariableToLayer[newNeuron._variable] = newLayerIndex; + NLR::Layer *layer = nlr->getLayer( newLayerIndex ); + for ( const auto &newNeuron : newNeurons ) + { + handledVariableToLayer[newNeuron._variable] = newLayerIndex; - layer->setLb( newNeuron._neuron, _lowerBounds.exists( newNeuron._variable ) ? - _lowerBounds[newNeuron._variable] : FloatUtils::negativeInfinity() ); - layer->setUb( newNeuron._neuron, _upperBounds.exists( newNeuron._variable ) ? - _upperBounds[newNeuron._variable] : FloatUtils::infinity() ); + layer->setLb( newNeuron._neuron, + _lowerBounds.exists( newNeuron._variable ) ? _lowerBounds[newNeuron._variable] + : FloatUtils::negativeInfinity() ); + layer->setUb( newNeuron._neuron, + _upperBounds.exists( newNeuron._variable ) ? _upperBounds[newNeuron._variable] + : FloatUtils::infinity() ); - // Add the new neuron - nlr->setNeuronVariable( NLR::NeuronIndex( newLayerIndex, newNeuron._neuron ), newNeuron._variable ); + // Add the new neuron + nlr->setNeuronVariable( NLR::NeuronIndex( newLayerIndex, newNeuron._neuron ), + newNeuron._variable ); - for ( const auto &sourceVariable : newNeuron._sourceVariables ) - { - unsigned sourceLayer = handledVariableToLayer[sourceVariable]; - unsigned sourceNeuron = nlr->getLayer( sourceLayer )->variableToNeuron( sourceVariable ); + for ( const auto &sourceVariable : newNeuron._sourceVariables ) + { + unsigned sourceLayer = handledVariableToLayer[sourceVariable]; + unsigned sourceNeuron = + nlr->getLayer( sourceLayer )->variableToNeuron( sourceVariable ); - // Mark the layer dependency - nlr->addLayerDependency( sourceLayer, newLayerIndex ); + // Mark the layer dependency + nlr->addLayerDependency( sourceLayer, newLayerIndex ); - // Mark the activation connection - nlr->addActivationSource( sourceLayer, - sourceNeuron, - newLayerIndex, - newNeuron._neuron ); + // Mark the activation connection + nlr->addActivationSource( sourceLayer, sourceNeuron, newLayerIndex, newNeuron._neuron ); + } } - } - INPUT_QUERY_LOG( "\tSuccessful!" ); - return true; + INPUT_QUERY_LOG( "\tSuccessful!" ); + return true; } bool InputQuery::constructSoftmaxLayer( NLR::NetworkLevelReasoner *nlr, @@ -1705,7 +1717,6 @@ bool InputQuery::constructSoftmaxLayer( NLR::NetworkLevelReasoner *nlr, struct NeuronInformation { public: - NeuronInformation( unsigned variable, unsigned neuron, const Vector &sourceVariables ) @@ -1715,23 +1726,22 @@ bool InputQuery::constructSoftmaxLayer( NLR::NetworkLevelReasoner *nlr, { } - unsigned _variable; - unsigned _neuron; - Vector _sourceVariables; + unsigned _variable; + unsigned _neuron; + Vector _sourceVariables; }; List newNeurons; // Look for Softmaxes where all the element variables have already been handled - const List &nlConstraints = - getNonlinearConstraints(); + const List &nlConstraints = getNonlinearConstraints(); unsigned currentSourceLayer = 0; for ( const auto &ts : nlConstraints ) { // Only consider Softmax if ( ts->getType() != SOFTMAX ) - continue; + continue; const SoftmaxConstraint *softmax = (const SoftmaxConstraint *)ts; @@ -1745,8 +1755,7 @@ bool InputQuery::constructSoftmaxLayer( NLR::NetworkLevelReasoner *nlr, missingInput = true; break; } - else if ( _ensureSameSourceLayerInNLR && - newNeurons.size() && + else if ( _ensureSameSourceLayerInNLR && newNeurons.size() && handledVariableToLayer[input] != currentSourceLayer ) { sourceLayerDiffers = true; @@ -1755,7 +1764,7 @@ bool InputQuery::constructSoftmaxLayer( NLR::NetworkLevelReasoner *nlr, } if ( missingInput || sourceLayerDiffers ) - continue; + continue; // If any output has also been handled, ignore this constraint bool outputHandled = false; @@ -1768,7 +1777,8 @@ bool InputQuery::constructSoftmaxLayer( NLR::NetworkLevelReasoner *nlr, } } - if ( outputHandled ) continue; + if ( outputHandled ) + continue; // inputs have been handled, outputs haven't. Add the outputs // We want the following criteron to hold: @@ -1790,9 +1800,8 @@ bool InputQuery::constructSoftmaxLayer( NLR::NetworkLevelReasoner *nlr, for ( unsigned neuron : neurons ) { unsigned output = softmax->getOutput( neuronToVariable[neuron] ); - newNeurons.append( NeuronInformation( output, - newNeurons.size(), - softmax->getInputs() ) ); + newNeurons.append( + NeuronInformation( output, newNeurons.size(), softmax->getInputs() ) ); } } @@ -1810,27 +1819,28 @@ bool InputQuery::constructSoftmaxLayer( NLR::NetworkLevelReasoner *nlr, { handledVariableToLayer[newNeuron._variable] = newLayerIndex; - layer->setLb( newNeuron._neuron, _lowerBounds.exists( newNeuron._variable ) ? - _lowerBounds[newNeuron._variable] : FloatUtils::negativeInfinity() ); - layer->setUb( newNeuron._neuron, _upperBounds.exists( newNeuron._variable ) ? - _upperBounds[newNeuron._variable] : FloatUtils::infinity() ); + layer->setLb( newNeuron._neuron, + _lowerBounds.exists( newNeuron._variable ) ? _lowerBounds[newNeuron._variable] + : FloatUtils::negativeInfinity() ); + layer->setUb( newNeuron._neuron, + _upperBounds.exists( newNeuron._variable ) ? _upperBounds[newNeuron._variable] + : FloatUtils::infinity() ); // Add the new neuron - nlr->setNeuronVariable( NLR::NeuronIndex( newLayerIndex, newNeuron._neuron ), newNeuron._variable ); + nlr->setNeuronVariable( NLR::NeuronIndex( newLayerIndex, newNeuron._neuron ), + newNeuron._variable ); for ( const auto &sourceVariable : newNeuron._sourceVariables ) { unsigned sourceLayer = handledVariableToLayer[sourceVariable]; - unsigned sourceNeuron = nlr->getLayer( sourceLayer )->variableToNeuron( sourceVariable ); + unsigned sourceNeuron = + nlr->getLayer( sourceLayer )->variableToNeuron( sourceVariable ); // Mark the layer dependency nlr->addLayerDependency( sourceLayer, newLayerIndex ); // Mark the activation connection - nlr->addActivationSource( sourceLayer, - sourceNeuron, - newLayerIndex, - newNeuron._neuron ); + nlr->addActivationSource( sourceLayer, sourceNeuron, newLayerIndex, newNeuron._neuron ); } } diff --git a/src/engine/InputQuery.h b/src/engine/InputQuery.h index dbc9b60164..f45b74b9f1 100644 --- a/src/engine/InputQuery.h +++ b/src/engine/InputQuery.h @@ -21,8 +21,8 @@ #include "MString.h" #include "Map.h" #include "NetworkLevelReasoner.h" -#include "PiecewiseLinearConstraint.h" #include "NonlinearConstraint.h" +#include "PiecewiseLinearConstraint.h" class InputQuery { @@ -158,8 +158,8 @@ class InputQuery Map _solution; /* - Attempt to ensure that neurons in the same non-linear NLR layer - have the same source layer by spacing neurons with different + Attempt to ensure that neurons in the same non-linear NLR layer + have the same source layer by spacing neurons with different source neurons in separate NLR layers. */ bool _ensureSameSourceLayerInNLR; @@ -197,8 +197,8 @@ class InputQuery Map &handledVariableToLayer, unsigned newLayerIndex ); bool constructBilinearLayer( NLR::NetworkLevelReasoner *nlr, - Map &handledVariableToLayer, - unsigned newLayerIndex ); + Map &handledVariableToLayer, + unsigned newLayerIndex ); bool constructSoftmaxLayer( NLR::NetworkLevelReasoner *nlr, Map &handledVariableToLayer, unsigned newLayerIndex ); diff --git a/src/engine/LargestIntervalDivider.cpp b/src/engine/LargestIntervalDivider.cpp index f90911336e..df7d33aff9 100644 --- a/src/engine/LargestIntervalDivider.cpp +++ b/src/engine/LargestIntervalDivider.cpp @@ -13,14 +13,14 @@ **/ +#include "LargestIntervalDivider.h" + #include "Debug.h" #include "FloatUtils.h" -#include "LargestIntervalDivider.h" #include "MStringf.h" #include "PiecewiseLinearCaseSplit.h" -LargestIntervalDivider::LargestIntervalDivider( const List - &inputVariables ) +LargestIntervalDivider::LargestIntervalDivider( const List &inputVariables ) : _inputVariables( inputVariables ) { } @@ -28,8 +28,7 @@ LargestIntervalDivider::LargestIntervalDivider( const List void LargestIntervalDivider::createSubQueries( unsigned numNewSubqueries, const String queryIdPrefix, const unsigned previousDepth, - const PiecewiseLinearCaseSplit - &previousSplit, + const PiecewiseLinearCaseSplit &previousSplit, const unsigned timeoutInSeconds, SubQueries &subQueries ) { @@ -78,31 +77,27 @@ void LargestIntervalDivider::createSubQueries( unsigned numNewSubqueries, queryId = queryIdPrefix + Stringf( "-%u", queryIdSuffix++ ); // Create a new case split - auto split = std::unique_ptr - ( new PiecewiseLinearCaseSplit() ); + auto split = std::unique_ptr( new PiecewiseLinearCaseSplit() ); // Add bound as equations for each input variable for ( const auto &variable : _inputVariables ) { double lb = inputRegion._lowerBounds[variable]; double ub = inputRegion._upperBounds[variable]; - split->storeBoundTightening( Tightening( variable, lb, - Tightening::LB ) ); - split->storeBoundTightening( Tightening( variable, ub, - Tightening::UB ) ); + split->storeBoundTightening( Tightening( variable, lb, Tightening::LB ) ); + split->storeBoundTightening( Tightening( variable, ub, Tightening::UB ) ); } // Construct the new subquery and add it to subqueries SubQuery *subQuery = new SubQuery; subQuery->_queryId = queryId; - subQuery->_split = std::move(split); + subQuery->_split = std::move( split ); subQuery->_timeoutInSeconds = timeoutInSeconds; subQuery->_depth = previousDepth + 1; subQueries.append( subQuery ); } } -unsigned LargestIntervalDivider::getLargestInterval( const InputRegion - &inputRegion ) +unsigned LargestIntervalDivider::getLargestInterval( const InputRegion &inputRegion ) { ASSERT( inputRegion._lowerBounds.size() == inputRegion._upperBounds.size() ); unsigned dimensionToSplit = 0; @@ -112,8 +107,7 @@ unsigned LargestIntervalDivider::getLargestInterval( const InputRegion for ( const auto &variable : _inputVariables ) { - double interval = inputRegion._upperBounds[variable] - - inputRegion._lowerBounds[variable]; + double interval = inputRegion._upperBounds[variable] - inputRegion._lowerBounds[variable]; DEBUG( haveCandidate = true ); diff --git a/src/engine/LargestIntervalDivider.h b/src/engine/LargestIntervalDivider.h index 59732e60ab..ed77c8dce7 100644 --- a/src/engine/LargestIntervalDivider.h +++ b/src/engine/LargestIntervalDivider.h @@ -29,8 +29,7 @@ class LargestIntervalDivider : public QueryDivider void createSubQueries( unsigned numNewSubQueries, const String queryIdPrefix, const unsigned previousDepth, - const PiecewiseLinearCaseSplit - &previousSplit, + const PiecewiseLinearCaseSplit &previousSplit, const unsigned timeoutInSeconds, SubQueries &subQueries ); @@ -44,7 +43,6 @@ class LargestIntervalDivider : public QueryDivider All input variables of the network */ const List _inputVariables; - }; #endif // __LargestIntervalDivider_h__ diff --git a/src/engine/LeakyReluConstraint.cpp b/src/engine/LeakyReluConstraint.cpp index f901ac7faa..a09bda7cff 100644 --- a/src/engine/LeakyReluConstraint.cpp +++ b/src/engine/LeakyReluConstraint.cpp @@ -14,22 +14,22 @@ #include "LeakyReluConstraint.h" -#include "PiecewiseLinearConstraint.h" #include "Debug.h" #include "DivideStrategy.h" #include "FloatUtils.h" #include "GlobalConfiguration.h" +#include "ITableau.h" #include "InfeasibleQueryException.h" #include "InputQuery.h" -#include "ITableau.h" #include "MStringf.h" #include "MarabouError.h" #include "PiecewiseLinearCaseSplit.h" +#include "PiecewiseLinearConstraint.h" #include "Statistics.h" #include "TableauRow.h" #ifdef _WIN32 -#define __attribute__(x) +#define __attribute__( x ) #endif LeakyReluConstraint::LeakyReluConstraint( unsigned b, unsigned f, double slope ) @@ -52,7 +52,8 @@ LeakyReluConstraint::LeakyReluConstraint( const String &serializedLeakyRelu ) ASSERT( constraintType == String( "leaky_relu" ) ); // Remove the constraint type in serialized form - String serializedValues = serializedLeakyRelu.substring( 11, serializedLeakyRelu.length() - 11 ); + String serializedValues = + serializedLeakyRelu.substring( 11, serializedLeakyRelu.length() - 11 ); List values = serializedValues.tokenize( "," ); ASSERT( values.size() == 3 || values.size() == 5 ); @@ -112,7 +113,8 @@ void LeakyReluConstraint::registerAsWatcher( ITableau *tableau ) tableau->registerToWatchVariable( this, _b ); tableau->registerToWatchVariable( this, _f ); - if ( _auxVarsInUse ) { + if ( _auxVarsInUse ) + { tableau->registerToWatchVariable( this, _activeAux ); tableau->registerToWatchVariable( this, _inactiveAux ); } @@ -123,7 +125,8 @@ void LeakyReluConstraint::unregisterAsWatcher( ITableau *tableau ) tableau->unregisterToWatchVariable( this, _b ); tableau->unregisterToWatchVariable( this, _f ); - if ( _auxVarsInUse ) { + if ( _auxVarsInUse ) + { tableau->unregisterToWatchVariable( this, _activeAux ); tableau->unregisterToWatchVariable( this, _inactiveAux ); } @@ -164,9 +167,9 @@ void LeakyReluConstraint::notifyLowerBound( unsigned variable, double bound ) if ( _statistics ) _statistics->incLongAttribute( Statistics::NUM_BOUND_NOTIFICATIONS_TO_PL_CONSTRAINTS ); - if ( _boundManager == nullptr && existsLowerBound( variable ) - && !FloatUtils::gt( bound, getLowerBound( variable ) ) ) - return; + if ( _boundManager == nullptr && existsLowerBound( variable ) && + !FloatUtils::gt( bound, getLowerBound( variable ) ) ) + return; setLowerBound( variable, bound ); checkIfLowerBoundUpdateFixesPhase( variable, bound ); @@ -221,9 +224,9 @@ void LeakyReluConstraint::notifyUpperBound( unsigned variable, double bound ) if ( _statistics ) _statistics->incLongAttribute( Statistics::NUM_BOUND_NOTIFICATIONS_TO_PL_CONSTRAINTS ); - if ( _boundManager == nullptr && existsUpperBound( - variable ) && !FloatUtils::lt( bound, getUpperBound( variable ) ) ) - return; + if ( _boundManager == nullptr && existsUpperBound( variable ) && + !FloatUtils::lt( bound, getUpperBound( variable ) ) ) + return; setUpperBound( variable, bound ); checkIfUpperBoundUpdateFixesPhase( variable, bound ); @@ -253,14 +256,13 @@ void LeakyReluConstraint::notifyUpperBound( unsigned variable, double bound ) bool LeakyReluConstraint::participatingVariable( unsigned variable ) const { return ( variable == _b ) || ( variable == _f ) || - ( _auxVarsInUse && ( variable == _activeAux || variable == _inactiveAux ) ); + ( _auxVarsInUse && ( variable == _activeAux || variable == _inactiveAux ) ); } List LeakyReluConstraint::getParticipatingVariables() const { - return _auxVarsInUse ? - List( { _b, _f, _activeAux, _inactiveAux } ) : - List( { _b, _f } ); + return _auxVarsInUse ? List( { _b, _f, _activeAux, _inactiveAux } ) + : List( { _b, _f } ); } bool LeakyReluConstraint::satisfied() const @@ -272,9 +274,11 @@ bool LeakyReluConstraint::satisfied() const double fValue = getAssignment( _f ); if ( FloatUtils::isPositive( fValue ) ) - return FloatUtils::areEqual( bValue, fValue, GlobalConfiguration::CONSTRAINT_COMPARISON_TOLERANCE ); + return FloatUtils::areEqual( + bValue, fValue, GlobalConfiguration::CONSTRAINT_COMPARISON_TOLERANCE ); else - return FloatUtils::areEqual( _slope * bValue, fValue, GlobalConfiguration::CONSTRAINT_COMPARISON_TOLERANCE ); + return FloatUtils::areEqual( + _slope * bValue, fValue, GlobalConfiguration::CONSTRAINT_COMPARISON_TOLERANCE ); } List LeakyReluConstraint::getPossibleFixes() const @@ -495,99 +499,109 @@ PiecewiseLinearCaseSplit LeakyReluConstraint::getValidCaseSplit() const void LeakyReluConstraint::dump( String &output ) const { - output = Stringf( "LeakyReluConstraint: x%u = LeakyReLU( x%u ), slope = %lf. Active? %s. PhaseStatus = %u (%s).\n", - _f, _b, _slope, + output = Stringf( "LeakyReluConstraint: x%u = LeakyReLU( x%u ), slope = %lf. Active? %s. " + "PhaseStatus = %u (%s).\n", + _f, + _b, + _slope, _constraintActive ? "Yes" : "No", - _phaseStatus, phaseToString( _phaseStatus ).ascii() - ); + _phaseStatus, + phaseToString( _phaseStatus ).ascii() ); - output += Stringf( "b in [%s, %s], ", - existsLowerBound( _b ) ? Stringf( "%lf", getLowerBound( _b ) ).ascii() : "-inf", - existsUpperBound( _b ) ? Stringf( "%lf", getUpperBound( _b ) ).ascii() : "inf" ); + output += + Stringf( "b in [%s, %s], ", + existsLowerBound( _b ) ? Stringf( "%lf", getLowerBound( _b ) ).ascii() : "-inf", + existsUpperBound( _b ) ? Stringf( "%lf", getUpperBound( _b ) ).ascii() : "inf" ); - output += Stringf( "f in [%s, %s]", - existsLowerBound( _f ) ? Stringf( "%lf", getLowerBound( _f ) ).ascii() : "-inf", - existsUpperBound( _f ) ? Stringf( "%lf", getUpperBound( _f ) ).ascii() : "inf" ); + output += + Stringf( "f in [%s, %s]", + existsLowerBound( _f ) ? Stringf( "%lf", getLowerBound( _f ) ).ascii() : "-inf", + existsUpperBound( _f ) ? Stringf( "%lf", getUpperBound( _f ) ).ascii() : "inf" ); if ( _auxVarsInUse ) { - output += Stringf( ". Active aux var: %u. Range: [%s, %s]\n", - _activeAux, - existsLowerBound( _activeAux ) ? Stringf( "%lf", getLowerBound( _activeAux ) ).ascii() : "-inf", - existsUpperBound( _activeAux ) ? Stringf( "%lf", getUpperBound( _activeAux ) ).ascii() : "inf" ); + output += Stringf( + ". Active aux var: %u. Range: [%s, %s]\n", + _activeAux, + existsLowerBound( _activeAux ) ? Stringf( "%lf", getLowerBound( _activeAux ) ).ascii() + : "-inf", + existsUpperBound( _activeAux ) ? Stringf( "%lf", getUpperBound( _activeAux ) ).ascii() + : "inf" ); output += Stringf( ". Inactive aux var: %u. Range: [%s, %s]\n", _inactiveAux, - existsLowerBound( _inactiveAux ) ? Stringf( "%lf", getLowerBound( _inactiveAux ) ).ascii() : "-inf", - existsUpperBound( _inactiveAux ) ? Stringf( "%lf", getUpperBound( _inactiveAux ) ).ascii() : "inf" ); + existsLowerBound( _inactiveAux ) + ? Stringf( "%lf", getLowerBound( _inactiveAux ) ).ascii() + : "-inf", + existsUpperBound( _inactiveAux ) + ? Stringf( "%lf", getUpperBound( _inactiveAux ) ).ascii() + : "inf" ); } - } void LeakyReluConstraint::updateVariableIndex( unsigned oldIndex, unsigned newIndex ) { - // Variable reindexing can only occur in preprocessing before Gurobi is - // registered. - ASSERT( _gurobi == NULL ); + // Variable reindexing can only occur in preprocessing before Gurobi is + // registered. + ASSERT( _gurobi == NULL ); - ASSERT( participatingVariable( oldIndex ) ); - ASSERT( !_lowerBounds.exists( newIndex ) && - !_upperBounds.exists( newIndex ) && - !participatingVariable( newIndex ) ); + ASSERT( participatingVariable( oldIndex ) ); + ASSERT( !_lowerBounds.exists( newIndex ) && !_upperBounds.exists( newIndex ) && + !participatingVariable( newIndex ) ); - if ( _lowerBounds.exists( oldIndex ) ) - { - _lowerBounds[newIndex] = _lowerBounds.get( oldIndex ); - _lowerBounds.erase( oldIndex ); - } + if ( _lowerBounds.exists( oldIndex ) ) + { + _lowerBounds[newIndex] = _lowerBounds.get( oldIndex ); + _lowerBounds.erase( oldIndex ); + } - if ( _upperBounds.exists( oldIndex ) ) - { - _upperBounds[newIndex] = _upperBounds.get( oldIndex ); - _upperBounds.erase( oldIndex ); - } + if ( _upperBounds.exists( oldIndex ) ) + { + _upperBounds[newIndex] = _upperBounds.get( oldIndex ); + _upperBounds.erase( oldIndex ); + } - if ( oldIndex == _b ) - _b = newIndex; - else if ( oldIndex == _f ) - _f = newIndex; - else if ( oldIndex == _activeAux ) - _activeAux = newIndex; - else - _inactiveAux = newIndex; + if ( oldIndex == _b ) + _b = newIndex; + else if ( oldIndex == _f ) + _f = newIndex; + else if ( oldIndex == _activeAux ) + _activeAux = newIndex; + else + _inactiveAux = newIndex; } -void LeakyReluConstraint::eliminateVariable( __attribute__((unused)) unsigned variable, - __attribute__((unused)) double fixedValue ) +void LeakyReluConstraint::eliminateVariable( __attribute__( ( unused ) ) unsigned variable, + __attribute__( ( unused ) ) double fixedValue ) { ASSERT( participatingVariable( variable ) ); - DEBUG({ - if ( variable == _f || variable == _b ) + DEBUG( { + if ( variable == _f || variable == _b ) + { + if ( FloatUtils::gt( fixedValue, 0 ) ) { - if ( FloatUtils::gt( fixedValue, 0 ) ) - { - ASSERT( _phaseStatus != RELU_PHASE_INACTIVE ); - } - else if ( FloatUtils::lt( fixedValue, 0 ) ) - { - ASSERT( _phaseStatus != RELU_PHASE_ACTIVE ); - } + ASSERT( _phaseStatus != RELU_PHASE_INACTIVE ); } - else if ( variable == _activeAux ) + else if ( FloatUtils::lt( fixedValue, 0 ) ) { - if ( FloatUtils::isPositive( fixedValue ) ) - { - ASSERT( _phaseStatus != RELU_PHASE_ACTIVE ); - } + ASSERT( _phaseStatus != RELU_PHASE_ACTIVE ); } - else + } + else if ( variable == _activeAux ) + { + if ( FloatUtils::isPositive( fixedValue ) ) + { + ASSERT( _phaseStatus != RELU_PHASE_ACTIVE ); + } + } + else + { + // This is the inactive aux variable + if ( FloatUtils::isPositive( fixedValue ) ) { - // This is the inactive aux variable - if ( FloatUtils::isPositive( fixedValue ) ) - { - ASSERT( _phaseStatus != RELU_PHASE_INACTIVE ); - } + ASSERT( _phaseStatus != RELU_PHASE_INACTIVE ); } - }); + } + } ); // In a Leaky ReLU constraint, if a variable is removed the entire constraint can be discarded. _haveEliminatedVariables = true; @@ -600,8 +614,8 @@ bool LeakyReluConstraint::constraintObsolete() const void LeakyReluConstraint::getEntailedTightenings( List &tightenings ) const { - ASSERT( existsLowerBound( _b ) && existsLowerBound( _f ) && - existsUpperBound( _b ) && existsUpperBound( _f ) ); + ASSERT( existsLowerBound( _b ) && existsLowerBound( _f ) && existsUpperBound( _b ) && + existsUpperBound( _f ) ); ASSERT( !_auxVarsInUse || ( existsLowerBound( _activeAux ) && existsUpperBound( _activeAux ) && @@ -627,11 +641,9 @@ void LeakyReluConstraint::getEntailedTightenings( List &tightenings } // Determine if we are in the active phase, inactive phase or unknown phase - if ( FloatUtils::isPositive( bLowerBound ) || - FloatUtils::isPositive( fLowerBound ) || - ( _auxVarsInUse && - ( FloatUtils::isZero( activeAuxUpperBound ) || - FloatUtils::isPositive( inactiveAuxLowerBound ) ) ) ) + if ( FloatUtils::isPositive( bLowerBound ) || FloatUtils::isPositive( fLowerBound ) || + ( _auxVarsInUse && ( FloatUtils::isZero( activeAuxUpperBound ) || + FloatUtils::isPositive( inactiveAuxLowerBound ) ) ) ) { // Active case; if ( FloatUtils::isPositive( fLowerBound ) ) @@ -652,17 +664,15 @@ void LeakyReluConstraint::getEntailedTightenings( List &tightenings tightenings.append( Tightening( _b, 0, Tightening::LB ) ); tightenings.append( Tightening( _f, 0, Tightening::LB ) ); } - else if ( !FloatUtils::isPositive( bUpperBound ) || - !FloatUtils::isPositive( fUpperBound ) || - ( _auxVarsInUse && - ( FloatUtils::isZero( inactiveAuxUpperBound ) || - FloatUtils::isPositive( activeAuxLowerBound ) ) ) ) + else if ( !FloatUtils::isPositive( bUpperBound ) || !FloatUtils::isPositive( fUpperBound ) || + ( _auxVarsInUse && ( FloatUtils::isZero( inactiveAuxUpperBound ) || + FloatUtils::isPositive( activeAuxLowerBound ) ) ) ) { // Inactive case if ( FloatUtils::isFinite( fLowerBound ) ) - tightenings.append( Tightening( _b, fLowerBound / _slope, Tightening::LB ) ); + tightenings.append( Tightening( _b, fLowerBound / _slope, Tightening::LB ) ); if ( FloatUtils::isFinite( bLowerBound ) ) - tightenings.append( Tightening( _f, _slope * bLowerBound, Tightening::LB ) ); + tightenings.append( Tightening( _f, _slope * bLowerBound, Tightening::LB ) ); if ( FloatUtils::isFinite( fUpperBound ) && !FloatUtils::isPositive( fUpperBound ) ) tightenings.append( Tightening( _b, fUpperBound / _slope, Tightening::UB ) ); @@ -761,8 +771,8 @@ void LeakyReluConstraint::transformToUseAuxVariables( InputQuery &inputQuery ) void LeakyReluConstraint::getCostFunctionComponent( LinearExpression &cost, PhaseStatus phase ) const { - // If the constraint is not active or is fixed, it contributes nothing - if( !isActive() || phaseFixed() ) + // If the constraint is not active or is fixed, it contributes nothing + if ( !isActive() || phaseFixed() ) return; // This should not be called when the linear constraints have @@ -797,37 +807,40 @@ void LeakyReluConstraint::getCostFunctionComponent( LinearExpression &cost, } } -PhaseStatus LeakyReluConstraint::getPhaseStatusInAssignment( const Map - &assignment ) const +PhaseStatus +LeakyReluConstraint::getPhaseStatusInAssignment( const Map &assignment ) const { ASSERT( assignment.exists( _b ) ); - return FloatUtils::isNegative( assignment[_b] ) ? - RELU_PHASE_INACTIVE : RELU_PHASE_ACTIVE; + return FloatUtils::isNegative( assignment[_b] ) ? RELU_PHASE_INACTIVE : RELU_PHASE_ACTIVE; } bool LeakyReluConstraint::haveOutOfBoundVariables() const { - double bValue = getAssignment( _b ); - double fValue = getAssignment( _f ); + double bValue = getAssignment( _b ); + double fValue = getAssignment( _f ); - if ( FloatUtils::gt( getLowerBound( _b ), bValue, GlobalConfiguration::CONSTRAINT_COMPARISON_TOLERANCE ) - || FloatUtils::lt( getUpperBound( _b ), bValue, GlobalConfiguration::CONSTRAINT_COMPARISON_TOLERANCE ) ) - return true; + if ( FloatUtils::gt( + getLowerBound( _b ), bValue, GlobalConfiguration::CONSTRAINT_COMPARISON_TOLERANCE ) || + FloatUtils::lt( + getUpperBound( _b ), bValue, GlobalConfiguration::CONSTRAINT_COMPARISON_TOLERANCE ) ) + return true; - if ( FloatUtils::gt( getLowerBound( _f ), fValue, GlobalConfiguration::CONSTRAINT_COMPARISON_TOLERANCE ) - || FloatUtils::lt( getUpperBound( _f ), fValue, GlobalConfiguration::CONSTRAINT_COMPARISON_TOLERANCE ) ) - return true; + if ( FloatUtils::gt( + getLowerBound( _f ), fValue, GlobalConfiguration::CONSTRAINT_COMPARISON_TOLERANCE ) || + FloatUtils::lt( + getUpperBound( _f ), fValue, GlobalConfiguration::CONSTRAINT_COMPARISON_TOLERANCE ) ) + return true; - return false; + return false; } String LeakyReluConstraint::serializeToString() const { - // Output format is: relu,f,b,slope,activeAux,inactiveAux - if ( _auxVarsInUse ) - return Stringf( "leaky_relu,%u,%u,%f,%u,%u", _f, _b, _slope, _activeAux, _inactiveAux ); - else - return Stringf( "leaky_relu,%u,%u,%f", _f, _b, _slope ); + // Output format is: relu,f,b,slope,activeAux,inactiveAux + if ( _auxVarsInUse ) + return Stringf( "leaky_relu,%u,%u,%f,%u,%u", _f, _b, _slope, _activeAux, _inactiveAux ); + else + return Stringf( "leaky_relu,%u,%u,%f", _f, _b, _slope ); } unsigned LeakyReluConstraint::getB() const @@ -867,8 +880,10 @@ double LeakyReluConstraint::computePolarity() const { double currentLb = _lowerBounds[_b]; double currentUb = _upperBounds[_b]; - if ( currentLb >= 0 ) return 1; - if ( currentUb <= 0 ) return -1; + if ( currentLb >= 0 ) + return 1; + if ( currentUb <= 0 ) + return -1; double width = currentUb - currentLb; double sum = currentUb + currentLb; return sum / width; @@ -890,6 +905,7 @@ void LeakyReluConstraint::updateScoreBasedOnPolarity() } // Not supporting proof production yet -void LeakyReluConstraint::addTableauAuxVar( unsigned /* tableauAuxVar */, unsigned /* constraintAuxVar */ ) +void LeakyReluConstraint::addTableauAuxVar( unsigned /* tableauAuxVar */, + unsigned /* constraintAuxVar */ ) { } diff --git a/src/engine/LeakyReluConstraint.h b/src/engine/LeakyReluConstraint.h index 959299fbff..11737510a4 100644 --- a/src/engine/LeakyReluConstraint.h +++ b/src/engine/LeakyReluConstraint.h @@ -192,8 +192,8 @@ class LeakyReluConstraint : public PiecewiseLinearConstraint Return the phase status corresponding to the values of the *input* variables in the given assignment. */ - virtual PhaseStatus getPhaseStatusInAssignment( const Map - &assignment ) const override; + virtual PhaseStatus + getPhaseStatusInAssignment( const Map &assignment ) const override; /* Returns string with shape: relu, _f, _b diff --git a/src/engine/MILPEncoder.cpp b/src/engine/MILPEncoder.cpp index ddcb8e51ab..7433611c10 100644 --- a/src/engine/MILPEncoder.cpp +++ b/src/engine/MILPEncoder.cpp @@ -14,16 +14,18 @@ ** [[ Add lengthier description here ]] **/ +#include "MILPEncoder.h" + #include "DeepPolySoftmaxElement.h" #include "FloatUtils.h" #include "GurobiWrapper.h" -#include "MILPEncoder.h" #include "TimeUtils.h" MILPEncoder::MILPEncoder( const ITableau &tableau ) : _tableau( tableau ) , _statistics( NULL ) -{} +{ +} void MILPEncoder::encodeInputQuery( GurobiWrapper &gurobi, const InputQuery &inputQuery, @@ -58,30 +60,22 @@ void MILPEncoder::encodeInputQuery( GurobiWrapper &gurobi, switch ( plConstraint->getType() ) { case PiecewiseLinearFunctionType::RELU: - encodeReLUConstraint( gurobi, (ReluConstraint *)plConstraint, - relax ); + encodeReLUConstraint( gurobi, (ReluConstraint *)plConstraint, relax ); break; case PiecewiseLinearFunctionType::LEAKY_RELU: - encodeLeakyReLUConstraint( gurobi, (LeakyReluConstraint *)plConstraint, - relax ); + encodeLeakyReLUConstraint( gurobi, (LeakyReluConstraint *)plConstraint, relax ); break; case PiecewiseLinearFunctionType::MAX: - encodeMaxConstraint( gurobi, (MaxConstraint *)plConstraint, - relax ); + encodeMaxConstraint( gurobi, (MaxConstraint *)plConstraint, relax ); break; case PiecewiseLinearFunctionType::SIGN: - encodeSignConstraint( gurobi, (SignConstraint *)plConstraint, - relax ); + encodeSignConstraint( gurobi, (SignConstraint *)plConstraint, relax ); break; case PiecewiseLinearFunctionType::ABSOLUTE_VALUE: - encodeAbsoluteValueConstraint( gurobi, - (AbsoluteValueConstraint *)plConstraint, - relax ); + encodeAbsoluteValueConstraint( gurobi, (AbsoluteValueConstraint *)plConstraint, relax ); break; case PiecewiseLinearFunctionType::DISJUNCTION: - encodeDisjunctionConstraint( gurobi, - (DisjunctionConstraint *)plConstraint, - relax ); + encodeDisjunctionConstraint( gurobi, (DisjunctionConstraint *)plConstraint, relax ); break; default: throw MarabouError( MarabouError::UNSUPPORTED_PIECEWISE_LINEAR_CONSTRAINT, @@ -119,9 +113,8 @@ void MILPEncoder::encodeInputQuery( GurobiWrapper &gurobi, if ( _statistics ) { struct timespec end = TimeUtils::sampleMicro(); - _statistics->incLongAttribute - ( Statistics::TIME_ADDING_CONSTRAINTS_TO_MILP_SOLVER_MICRO, - TimeUtils::timePassed( start, end ) ); + _statistics->incLongAttribute( Statistics::TIME_ADDING_CONSTRAINTS_TO_MILP_SOLVER_MICRO, + TimeUtils::timePassed( start, end ) ); } } @@ -137,9 +130,7 @@ void MILPEncoder::encodeEquation( GurobiWrapper &gurobi, const Equation &equatio List terms; double scalar = equation._scalar; for ( const auto &term : equation._addends ) - terms.append( GurobiWrapper::Term - ( term._coefficient, - Stringf( "x%u", term._variable ) ) ); + terms.append( GurobiWrapper::Term( term._coefficient, Stringf( "x%u", term._variable ) ) ); switch ( equation._type ) { case Equation::EQ: @@ -156,16 +147,13 @@ void MILPEncoder::encodeEquation( GurobiWrapper &gurobi, const Equation &equatio } } -void MILPEncoder::encodeReLUConstraint( GurobiWrapper &gurobi, - ReluConstraint *relu, bool relax ) +void MILPEncoder::encodeReLUConstraint( GurobiWrapper &gurobi, ReluConstraint *relu, bool relax ) { - if ( !relu->isActive() || relu->phaseFixed() ) { ASSERT( relu->auxVariableInUse() ); - ASSERT( ( FloatUtils::gte( _tableau.getLowerBound( relu->getB() ), 0 ) && - FloatUtils::lte( _tableau.getLowerBound( relu->getAux() ), 0 ) ) - || + ASSERT( ( FloatUtils::gte( _tableau.getLowerBound( relu->getB() ), 0 ) && + FloatUtils::lte( _tableau.getLowerBound( relu->getAux() ), 0 ) ) || ( FloatUtils::lte( _tableau.getUpperBound( relu->getB() ), 0 ) && FloatUtils::lte( _tableau.getUpperBound( relu->getF() ), 0 ) ) ); return; @@ -183,8 +171,7 @@ void MILPEncoder::encodeReLUConstraint( GurobiWrapper &gurobi, gurobi.addVariable( Stringf( "a%u", _binVarIndex ), 0, 1, - relax ? - GurobiWrapper::CONTINUOUS : GurobiWrapper::BINARY ); + relax ? GurobiWrapper::CONTINUOUS : GurobiWrapper::BINARY ); unsigned sourceVariable = relu->getB(); unsigned targetVariable = relu->getF(); @@ -203,10 +190,10 @@ void MILPEncoder::encodeReLUConstraint( GurobiWrapper &gurobi, gurobi.addLeqConstraint( terms, 0 ); } -void MILPEncoder::encodeLeakyReLUConstraint( GurobiWrapper &gurobi, LeakyReluConstraint *lRelu, +void MILPEncoder::encodeLeakyReLUConstraint( GurobiWrapper &gurobi, + LeakyReluConstraint *lRelu, bool relax ) { - if ( !lRelu->isActive() || lRelu->phaseFixed() ) { return; @@ -241,12 +228,13 @@ void MILPEncoder::encodeLeakyReLUConstraint( GurobiWrapper &gurobi, LeakyReluCon which is the upper bound in the triangular relaxation */ - double lambda = ( sourceUb - slope * sourceLb ) / (sourceUb - sourceLb ); + double lambda = ( sourceUb - slope * sourceLb ) / ( sourceUb - sourceLb ); List terms; terms.append( GurobiWrapper::Term( lambda, Stringf( "x%u", sourceVariable ) ) ); terms.append( GurobiWrapper::Term( -1, Stringf( "x%u", targetVariable ) ) ); - gurobi.addGeqConstraint( terms, ( lambda - 1 ) * sourceUb ); - } else + gurobi.addGeqConstraint( terms, ( lambda - 1 ) * sourceUb ); + } + else { double xPoints[3]; double yPoints[3]; @@ -258,13 +246,14 @@ void MILPEncoder::encodeLeakyReLUConstraint( GurobiWrapper &gurobi, LeakyReluCon yPoints[2] = sourceUb; gurobi.addPiecewiseLinearConstraint( Stringf( "x%u", sourceVariable ), Stringf( "x%u", targetVariable ), - 3, xPoints, yPoints ); + 3, + xPoints, + yPoints ); } } } -void MILPEncoder::encodeMaxConstraint( GurobiWrapper &gurobi, MaxConstraint *max, - bool relax ) +void MILPEncoder::encodeMaxConstraint( GurobiWrapper &gurobi, MaxConstraint *max, bool relax ) { if ( !max->isActive() ) return; @@ -277,8 +266,7 @@ void MILPEncoder::encodeMaxConstraint( GurobiWrapper &gurobi, MaxConstraint *max gurobi.addVariable( Stringf( "a%u_%u", _binVarIndex, i ), 0, 1, - relax ? - GurobiWrapper::CONTINUOUS : GurobiWrapper::BINARY ); + relax ? GurobiWrapper::CONTINUOUS : GurobiWrapper::BINARY ); terms.append( GurobiWrapper::Term( 1, Stringf( "a%u_%u", _binVarIndex, i ) ) ); } @@ -313,10 +301,10 @@ void MILPEncoder::encodeMaxConstraint( GurobiWrapper &gurobi, MaxConstraint *max We added aux_i >= 0, for each x. We now add, aux_i <= (1 - a) * (ub_aux) */ - DEBUG({ - ASSERT( split.getBoundTightenings().size() == 1 ); - ASSERT( split.getEquations().size() == 0 ); - }); + DEBUG( { + ASSERT( split.getBoundTightenings().size() == 1 ); + ASSERT( split.getEquations().size() == 0 ); + } ); unsigned aux = split.getBoundTightenings().begin()->_variable; double auxUb = _tableau.getUpperBound( aux ); terms.append( GurobiWrapper::Term( 1, Stringf( "x%u", aux ) ) ); @@ -338,9 +326,8 @@ void MILPEncoder::encodeAbsoluteValueConstraint( GurobiWrapper &gurobi, if ( !abs->isActive() || abs->phaseFixed() ) { - ASSERT( ( FloatUtils::gte( _tableau.getLowerBound( abs->getB() ), 0 ) && - FloatUtils::lte( _tableau.getUpperBound( abs->getPosAux() ), 0 ) ) - || + ASSERT( ( FloatUtils::gte( _tableau.getLowerBound( abs->getB() ), 0 ) && + FloatUtils::lte( _tableau.getUpperBound( abs->getPosAux() ), 0 ) ) || ( FloatUtils::lte( _tableau.getUpperBound( abs->getB() ), 0 ) && FloatUtils::lte( _tableau.getUpperBound( abs->getNegAux() ), 0 ) ) ); return; @@ -352,8 +339,7 @@ void MILPEncoder::encodeAbsoluteValueConstraint( GurobiWrapper &gurobi, double sourceUb = _tableau.getUpperBound( sourceVariable ); double targetUb = _tableau.getUpperBound( targetVariable ); - ASSERT( FloatUtils::isPositive( sourceUb ) && - FloatUtils::isNegative( sourceLb ) ); + ASSERT( FloatUtils::isPositive( sourceUb ) && FloatUtils::isNegative( sourceLb ) ); /* We have added f - b >= 0 and f + b >= 0. We add @@ -367,8 +353,7 @@ void MILPEncoder::encodeAbsoluteValueConstraint( GurobiWrapper &gurobi, gurobi.addVariable( Stringf( "a%u", _binVarIndex ), 0, 1, - relax ? - GurobiWrapper::CONTINUOUS : GurobiWrapper::BINARY ); + relax ? GurobiWrapper::CONTINUOUS : GurobiWrapper::BINARY ); List terms; terms.append( GurobiWrapper::Term( 1, Stringf( "x%u", targetVariable ) ) ); @@ -379,8 +364,7 @@ void MILPEncoder::encodeAbsoluteValueConstraint( GurobiWrapper &gurobi, terms.clear(); terms.append( GurobiWrapper::Term( 1, Stringf( "x%u", targetVariable ) ) ); terms.append( GurobiWrapper::Term( 1, Stringf( "x%u", sourceVariable ) ) ); - terms.append( GurobiWrapper::Term( -( targetUb + sourceUb ), - Stringf( "a%u", _binVarIndex ) ) ); + terms.append( GurobiWrapper::Term( -( targetUb + sourceUb ), Stringf( "a%u", _binVarIndex ) ) ); gurobi.addLeqConstraint( terms, 0 ); ++_binVarIndex; } @@ -401,8 +385,7 @@ void MILPEncoder::encodeDisjunctionConstraint( GurobiWrapper &gurobi, gurobi.addVariable( Stringf( "a%u_%u", _binVarIndex, i ), 0, 1, - relax ? - GurobiWrapper::CONTINUOUS : GurobiWrapper::BINARY ); + relax ? GurobiWrapper::CONTINUOUS : GurobiWrapper::BINARY ); terms.append( GurobiWrapper::Term( 1, Stringf( "a%u_%u", _binVarIndex, i ) ) ); } @@ -419,9 +402,8 @@ void MILPEncoder::encodeDisjunctionConstraint( GurobiWrapper &gurobi, for ( const auto &tightening : disjunct.getBoundTightenings() ) { // add indicator constraint: a_1 => disjunct1, etc. - terms.append( GurobiWrapper::Term - ( 1, getVariableNameFromVariable - ( tightening._variable ) ) ); + terms.append( + GurobiWrapper::Term( 1, getVariableNameFromVariable( tightening._variable ) ) ); if ( tightening._type == Tightening::UB ) gurobi.addLeqIndicatorConstraint( binVarName, 1, terms, tightening._value ); else @@ -434,31 +416,27 @@ void MILPEncoder::encodeDisjunctionConstraint( GurobiWrapper &gurobi, _binVarIndex++; } -void MILPEncoder::encodeSignConstraint( GurobiWrapper &gurobi, - SignConstraint *sign, - bool relax ) +void MILPEncoder::encodeSignConstraint( GurobiWrapper &gurobi, SignConstraint *sign, bool relax ) { ASSERT( GlobalConfiguration::PL_CONSTRAINTS_ADD_AUX_EQUATIONS_AFTER_PREPROCESSING ); if ( !sign->isActive() || sign->phaseFixed() ) { - ASSERT( ( FloatUtils::gte( _tableau.getLowerBound( sign->getB() ), 0 ) && - FloatUtils::areEqual( _tableau.getLowerBound( sign->getF() ), 1 ) ) - || + ASSERT( ( FloatUtils::gte( _tableau.getLowerBound( sign->getB() ), 0 ) && + FloatUtils::areEqual( _tableau.getLowerBound( sign->getF() ), 1 ) ) || ( FloatUtils::lte( _tableau.getUpperBound( sign->getB() ), 0 ) && FloatUtils::areEqual( _tableau.getUpperBound( sign->getF() ), -1 ) ) ); return; } unsigned targetVariable = sign->getF(); - DEBUG({ - unsigned sourceVariable = sign->getB(); + DEBUG( { + unsigned sourceVariable = sign->getB(); - double sourceLb = _tableau.getLowerBound( sourceVariable ); - double sourceUb = _tableau.getUpperBound( sourceVariable ); - ASSERT( !FloatUtils::isNegative( sourceUb ) && - FloatUtils::isNegative( sourceLb ) ); - }); + double sourceLb = _tableau.getLowerBound( sourceVariable ); + double sourceUb = _tableau.getUpperBound( sourceVariable ); + ASSERT( !FloatUtils::isNegative( sourceUb ) && FloatUtils::isNegative( sourceLb ) ); + } ); /* We have added f <= -2/lb b + 1 and f >= 2/ub * b - 1. We just need to specify @@ -471,8 +449,7 @@ void MILPEncoder::encodeSignConstraint( GurobiWrapper &gurobi, gurobi.addVariable( Stringf( "a%u", _binVarIndex ), 0, 1, - relax ? - GurobiWrapper::CONTINUOUS : GurobiWrapper::BINARY ); + relax ? GurobiWrapper::CONTINUOUS : GurobiWrapper::BINARY ); List terms; terms.append( GurobiWrapper::Term( 1, Stringf( "x%u", targetVariable ) ) ); @@ -484,8 +461,8 @@ void MILPEncoder::encodeSignConstraint( GurobiWrapper &gurobi, void MILPEncoder::encodeSigmoidConstraint( GurobiWrapper &gurobi, SigmoidConstraint *sigmoid ) { - unsigned sourceVariable = sigmoid->getB(); // x_b - unsigned targetVariable = sigmoid->getF(); // x_f + unsigned sourceVariable = sigmoid->getB(); // x_b + unsigned targetVariable = sigmoid->getF(); // x_f double sourceLb = _tableau.getLowerBound( sourceVariable ); double sourceUb = _tableau.getUpperBound( sourceVariable ); @@ -504,14 +481,13 @@ void MILPEncoder::encodeSigmoidConstraint( GurobiWrapper &gurobi, SigmoidConstra else if ( FloatUtils::lt( sourceLb, 0 ) && FloatUtils::gt( sourceUb, 0 ) ) { List terms; - String binVarName = Stringf( "a%u", _binVarIndex ); // a = 1 -> the case where x_b >= 0, otherwise where x_b <= 0 - gurobi.addVariable( binVarName, - 0, - 1, - GurobiWrapper::BINARY ); + String binVarName = Stringf( "a%u", _binVarIndex ); // a = 1 -> the case where x_b >= 0, + // otherwise where x_b <= 0 + gurobi.addVariable( binVarName, 0, 1, GurobiWrapper::BINARY ); // Constraint where x_b >= 0 - // Upper line is tangent and lower line is secant for an overapproximation with a linearization. + // Upper line is tangent and lower line is secant for an overapproximation with a + // linearization. int binVal = 1; @@ -521,7 +497,8 @@ void MILPEncoder::encodeSigmoidConstraint( GurobiWrapper &gurobi, SigmoidConstra double tangentSlope = sigmoid->sigmoidDerivative( tangentPoint ); terms.append( GurobiWrapper::Term( 1, Stringf( "x%u", targetVariable ) ) ); terms.append( GurobiWrapper::Term( -tangentSlope, Stringf( "x%u", sourceVariable ) ) ); - gurobi.addLeqIndicatorConstraint( binVarName, binVal, terms, -tangentSlope * tangentPoint + yAtTangentPoint ); + gurobi.addLeqIndicatorConstraint( + binVarName, binVal, terms, -tangentSlope * tangentPoint + yAtTangentPoint ); terms.clear(); // secant line: x_f = secantSlope * (x_b - 0) + y_l @@ -535,16 +512,17 @@ void MILPEncoder::encodeSigmoidConstraint( GurobiWrapper &gurobi, SigmoidConstra // lower bound of x_b terms.append( GurobiWrapper::Term( 1, Stringf( "x%u", sourceVariable ) ) ); - gurobi.addGeqIndicatorConstraint( binVarName, binVal, terms, 0 ); + gurobi.addGeqIndicatorConstraint( binVarName, binVal, terms, 0 ); terms.clear(); // lower bound of x_f terms.append( GurobiWrapper::Term( 1, Stringf( "x%u", targetVariable ) ) ); - gurobi.addGeqIndicatorConstraint( binVarName, binVal, terms, y_l ); - terms.clear(); + gurobi.addGeqIndicatorConstraint( binVarName, binVal, terms, y_l ); + terms.clear(); // Constraints where x_b <= 0 - // Upper line is secant and lower line is tangent for an overapproximation with a linearization. + // Upper line is secant and lower line is tangent for an overapproximation with a + // linearization. binVal = 0; @@ -554,7 +532,8 @@ void MILPEncoder::encodeSigmoidConstraint( GurobiWrapper &gurobi, SigmoidConstra tangentSlope = sigmoid->sigmoidDerivative( tangentPoint ); terms.append( GurobiWrapper::Term( 1, Stringf( "x%u", targetVariable ) ) ); terms.append( GurobiWrapper::Term( -tangentSlope, Stringf( "x%u", sourceVariable ) ) ); - gurobi.addGeqIndicatorConstraint( binVarName, binVal, terms, -tangentSlope * tangentPoint + yAtTangentPoint ); + gurobi.addGeqIndicatorConstraint( + binVarName, binVal, terms, -tangentSlope * tangentPoint + yAtTangentPoint ); terms.clear(); // secant line: x_f = secantSlope * (x_b - sourceLb) + y_l @@ -563,7 +542,8 @@ void MILPEncoder::encodeSigmoidConstraint( GurobiWrapper &gurobi, SigmoidConstra secantSlope = ( y_u - y_l ) / ( 0 - sourceLb ); terms.append( GurobiWrapper::Term( 1, Stringf( "x%u", targetVariable ) ) ); terms.append( GurobiWrapper::Term( -secantSlope, Stringf( "x%u", sourceVariable ) ) ); - gurobi.addLeqIndicatorConstraint( binVarName, binVal, terms, -secantSlope * sourceLb + y_l ); + gurobi.addLeqIndicatorConstraint( + binVarName, binVal, terms, -secantSlope * sourceLb + y_l ); terms.clear(); // upper bound of x_b @@ -659,35 +639,35 @@ void MILPEncoder::encodeSoftmaxConstraint( GurobiWrapper &gurobi, SoftmaxConstra } if ( !useLSE2 ) { - symbolicLowerBias = - NLR::DeepPolySoftmaxElement::LSELowerBound( sourceMids, sourceLbs, sourceUbs, i ); + symbolicLowerBias = NLR::DeepPolySoftmaxElement::LSELowerBound( + sourceMids, sourceLbs, sourceUbs, i ); if ( !FloatUtils::wellFormed( symbolicLowerBias ) ) wellFormed = false; for ( unsigned j = 0; j < size; ++j ) { - double dldj = - NLR::DeepPolySoftmaxElement::dLSELowerBound( sourceMids, sourceLbs, - sourceUbs, i, j ); + double dldj = NLR::DeepPolySoftmaxElement::dLSELowerBound( + sourceMids, sourceLbs, sourceUbs, i, j ); if ( !FloatUtils::wellFormed( dldj ) ) wellFormed = false; - terms.append( GurobiWrapper::Term( -dldj, Stringf( "x%u", sourceVariables[j] ) ) ); + terms.append( + GurobiWrapper::Term( -dldj, Stringf( "x%u", sourceVariables[j] ) ) ); symbolicLowerBias -= dldj * sourceMids[j]; } } else { - symbolicLowerBias = - NLR::DeepPolySoftmaxElement::LSELowerBound2( sourceMids, sourceLbs, sourceUbs, i ); + symbolicLowerBias = NLR::DeepPolySoftmaxElement::LSELowerBound2( + sourceMids, sourceLbs, sourceUbs, i ); if ( !FloatUtils::wellFormed( symbolicLowerBias ) ) wellFormed = false; for ( unsigned j = 0; j < size; ++j ) { - double dldj = - NLR::DeepPolySoftmaxElement::dLSELowerBound2( sourceMids, sourceLbs, - sourceUbs, i, j ); + double dldj = NLR::DeepPolySoftmaxElement::dLSELowerBound2( + sourceMids, sourceLbs, sourceUbs, i, j ); if ( !FloatUtils::wellFormed( dldj ) ) wellFormed = false; - terms.append( GurobiWrapper::Term( -dldj, Stringf( "x%u", sourceVariables[j] ) ) ); + terms.append( + GurobiWrapper::Term( -dldj, Stringf( "x%u", sourceVariables[j] ) ) ); symbolicLowerBias -= dldj * sourceMids[j]; } } @@ -704,9 +684,8 @@ void MILPEncoder::encodeSoftmaxConstraint( GurobiWrapper &gurobi, SoftmaxConstra terms.append( GurobiWrapper::Term( 1, Stringf( "x%u", targetVariables[i] ) ) ); for ( unsigned j = 0; j < size; ++j ) { - double dudj = - NLR::DeepPolySoftmaxElement::dLSEUpperbound( sourceMids, targetLbs, - targetUbs, i, j ); + double dudj = NLR::DeepPolySoftmaxElement::dLSEUpperbound( + sourceMids, targetLbs, targetUbs, i, j ); if ( !FloatUtils::wellFormed( dudj ) ) wellFormed = false; terms.append( GurobiWrapper::Term( -dudj, Stringf( "x%u", sourceVariables[j] ) ) ); @@ -751,14 +730,13 @@ void MILPEncoder::encodeBilinearConstraint( GurobiWrapper &gurobi, auto bs = bilinear->getBs(); ASSERT( bs.size() == 2 ); auto f = bilinear->getF(); - gurobi.addBilinearConstraint( Stringf( "x%u", bs[0] ), Stringf( "x%u", bs[1] ), Stringf( "x%u", f ) ); + gurobi.addBilinearConstraint( + Stringf( "x%u", bs[0] ), Stringf( "x%u", bs[1] ), Stringf( "x%u", f ) ); return; } } -void MILPEncoder::encodeRoundConstraint( GurobiWrapper &gurobi, - RoundConstraint *round, - bool relax ) +void MILPEncoder::encodeRoundConstraint( GurobiWrapper &gurobi, RoundConstraint *round, bool relax ) { /* We have already introduced during preprocessing @@ -785,15 +763,12 @@ void MILPEncoder::encodeRoundConstraint( GurobiWrapper &gurobi, } } -void MILPEncoder::encodeCostFunction( GurobiWrapper &gurobi, - const LinearExpression &cost ) +void MILPEncoder::encodeCostFunction( GurobiWrapper &gurobi, const LinearExpression &cost ) { List terms; for ( const auto &pair : cost._addends ) { - terms.append( GurobiWrapper::Term - ( pair.second, - Stringf( "x%u", pair.first ) ) ); + terms.append( GurobiWrapper::Term( pair.second, Stringf( "x%u", pair.first ) ) ); } gurobi.setCost( terms, cost._constant ); } diff --git a/src/engine/MILPEncoder.h b/src/engine/MILPEncoder.h index fa5c5c2b28..10c4fb703d 100644 --- a/src/engine/MILPEncoder.h +++ b/src/engine/MILPEncoder.h @@ -19,17 +19,16 @@ #include "BilinearConstraint.h" #include "DisjunctionConstraint.h" #include "GurobiWrapper.h" -#include "InputQuery.h" #include "ITableau.h" +#include "InputQuery.h" #include "LeakyReluConstraint.h" #include "LinearExpression.h" #include "MStringf.h" +#include "Map.h" #include "RoundConstraint.h" #include "SoftmaxConstraint.h" #include "Statistics.h" -#include "Map.h" - class MILPEncoder { public: @@ -39,8 +38,8 @@ class MILPEncoder Encode the input query as a Gurobi query, variables and inequalities are from inputQuery, and latest variable bounds are from tableau */ - void encodeInputQuery( GurobiWrapper &gurobi, const InputQuery &inputQuery, - bool relax = false ); + void + encodeInputQuery( GurobiWrapper &gurobi, const InputQuery &inputQuery, bool relax = false ); /* get variable name from a variable in the encoded inputquery @@ -55,11 +54,9 @@ class MILPEncoder /* Encode the cost function into Gurobi */ - void encodeCostFunction( GurobiWrapper &gurobi, - const LinearExpression &cost ); + void encodeCostFunction( GurobiWrapper &gurobi, const LinearExpression &cost ); private: - /* Tableau has the latest bound */ @@ -103,14 +100,12 @@ class MILPEncoder The other two constraints f >= b and f >= 0 are encoded already when preprocessing */ - void encodeReLUConstraint( GurobiWrapper &gurobi, ReluConstraint *relu, - bool relax ); + void encodeReLUConstraint( GurobiWrapper &gurobi, ReluConstraint *relu, bool relax ); /* Encode a LeakyReLU constraint f = LeakyReLU(b) into Gurobi as a Piecewise Linear Constraint */ - void encodeLeakyReLUConstraint( GurobiWrapper &gurobi, LeakyReluConstraint *lRelu, - bool relax ); + void encodeLeakyReLUConstraint( GurobiWrapper &gurobi, LeakyReluConstraint *lRelu, bool relax ); /* Encode a MAX constraint y = max(x_1, x_2, ... ,x_m) into Gurobi using the same encoding in @@ -122,8 +117,7 @@ class MILPEncoder a_1 + a_2 + ... + a_m = 1 a_i \in {0, 1} (i = 1 ~ m) */ - void encodeMaxConstraint( GurobiWrapper &gurobi, MaxConstraint *max, - bool relax ); + void encodeMaxConstraint( GurobiWrapper &gurobi, MaxConstraint *max, bool relax ); /* Encode an abs constraint f = Abs(b) into Gurobi @@ -135,15 +129,13 @@ class MILPEncoder /* Encode a sign constraint f = Sign(b) into Gurobi */ - void encodeSignConstraint( GurobiWrapper &gurobi, SignConstraint *sign, - bool relax ); + void encodeSignConstraint( GurobiWrapper &gurobi, SignConstraint *sign, bool relax ); /* Encode a disjunction constraint into Gurobi */ - void encodeDisjunctionConstraint( GurobiWrapper &gurobi, - DisjunctionConstraint *disj, - bool relax ); + void + encodeDisjunctionConstraint( GurobiWrapper &gurobi, DisjunctionConstraint *disj, bool relax ); /* Encode a Sigmoid constraint @@ -158,16 +150,13 @@ class MILPEncoder /* Encode a Bilinear constraint */ - void encodeBilinearConstraint( GurobiWrapper &gurobi, - BilinearConstraint *bilinear, - bool relax ); + void + encodeBilinearConstraint( GurobiWrapper &gurobi, BilinearConstraint *bilinear, bool relax ); /* Encode a Round constraint */ - void encodeRoundConstraint( GurobiWrapper &gurobi, - RoundConstraint *round, - bool relax ); + void encodeRoundConstraint( GurobiWrapper &gurobi, RoundConstraint *round, bool relax ); }; #endif // __MILPEncoder_h__ diff --git a/src/engine/MILPSolverBoundTighteningType.h b/src/engine/MILPSolverBoundTighteningType.h index 0e571071d7..e412e6a04d 100644 --- a/src/engine/MILPSolverBoundTighteningType.h +++ b/src/engine/MILPSolverBoundTighteningType.h @@ -19,21 +19,20 @@ /* MILP solver bound tightening options */ -enum class MILPSolverBoundTighteningType -{ - // Only encode pure linear constraints in the underlying - // solver, in a way that over-approximates the query - LP_RELAXATION = 0, - LP_RELAXATION_INCREMENTAL = 1, - // Encode linear and integer constraints in the underlying - // solver, in a way that completely captures the query but is - // more expensive to solve - MILP_ENCODING = 2, - MILP_ENCODING_INCREMENTAL = 3, - // Encode full queries and tries to fix relus until fix point - ITERATIVE_PROPAGATION = 4, - // Option to have no MILP bound tightening performed - NONE = 5, +enum class MILPSolverBoundTighteningType { + // Only encode pure linear constraints in the underlying + // solver, in a way that over-approximates the query + LP_RELAXATION = 0, + LP_RELAXATION_INCREMENTAL = 1, + // Encode linear and integer constraints in the underlying + // solver, in a way that completely captures the query but is + // more expensive to solve + MILP_ENCODING = 2, + MILP_ENCODING_INCREMENTAL = 3, + // Encode full queries and tries to fix relus until fix point + ITERATIVE_PROPAGATION = 4, + // Option to have no MILP bound tightening performed + NONE = 5, }; #endif // __MILPSolverBoundTighteningType_h__ diff --git a/src/engine/Marabou.cpp b/src/engine/Marabou.cpp index ad114dbfa5..36fa1d09e5 100644 --- a/src/engine/Marabou.cpp +++ b/src/engine/Marabou.cpp @@ -14,18 +14,19 @@ ** [[ Add lengthier description here ]] **/ +#include "Marabou.h" + #include "AcasParser.h" #include "AutoFile.h" -#include "GlobalConfiguration.h" #include "File.h" +#include "GlobalConfiguration.h" #include "MStringf.h" -#include "Marabou.h" +#include "MarabouError.h" #include "OnnxParser.h" #include "Options.h" #include "PropertyParser.h" -#include "VnnLibParser.h" -#include "MarabouError.h" #include "QueryLoader.h" +#include "VnnLibParser.h" #ifdef _WIN32 #undef ERROR @@ -65,7 +66,7 @@ void Marabou::run() unsigned long long totalElapsed = TimeUtils::timePassed( start, end ); displayResults( totalElapsed ); - if( Options::get()->getBool( Options::EXPORT_ASSIGNMENT ) ) + if ( Options::get()->getBool( Options::EXPORT_ASSIGNMENT ) ) exportAssignment(); } @@ -79,7 +80,8 @@ void Marabou::prepareInputQuery() */ if ( !File::exists( inputQueryFilePath ) ) { - printf( "Error: the specified inputQuery file (%s) doesn't exist!\n", inputQueryFilePath.ascii() ); + printf( "Error: the specified inputQuery file (%s) doesn't exist!\n", + inputQueryFilePath.ascii() ); throw MarabouError( MarabouError::FILE_DOESNT_EXIST, inputQueryFilePath.ascii() ); } @@ -102,12 +104,13 @@ void Marabou::prepareInputQuery() if ( !File::exists( networkFilePath ) ) { - printf( "Error: the specified network file (%s) doesn't exist!\n", networkFilePath.ascii() ); + printf( "Error: the specified network file (%s) doesn't exist!\n", + networkFilePath.ascii() ); throw MarabouError( MarabouError::FILE_DOESNT_EXIST, networkFilePath.ascii() ); } printf( "Network: %s\n", networkFilePath.ascii() ); - if ( ((String) networkFilePath).endsWith( ".onnx" ) ) + if ( ( (String)networkFilePath ).endsWith( ".onnx" ) ) { _onnxParser = new OnnxParser( networkFilePath ); _onnxParser->generateQuery( _inputQuery ); @@ -156,12 +159,13 @@ void Marabou::prepareInputQuery() void Marabou::importDebuggingSolution() { - String fileName= Options::get()->getString( Options::IMPORT_ASSIGNMENT_FILE_PATH ); + String fileName = Options::get()->getString( Options::IMPORT_ASSIGNMENT_FILE_PATH ); AutoFile input( fileName ); if ( !IFile::exists( fileName ) ) { - throw MarabouError( MarabouError::FILE_DOES_NOT_EXIST, Stringf( "File %s not found.\n", fileName.ascii() ).ascii() ); + throw MarabouError( MarabouError::FILE_DOES_NOT_EXIST, + Stringf( "File %s not found.\n", fileName.ascii() ).ascii() ); } input->open( IFile::MODE_READ ); @@ -174,7 +178,7 @@ void Marabou::importDebuggingSolution() String line; // Import each assignment - for ( unsigned i = 0; i < numVars; ++i ) + for ( unsigned i = 0; i < numVars; ++i ) { line = input->readLine(); List tokens = line.tokenize( "," ); @@ -185,7 +189,7 @@ void Marabou::importDebuggingSolution() value = atof( it->ascii() ); it++; ASSERT( it == tokens.end() ); - _inputQuery.storeDebuggingSolution( var, value); + _inputQuery.storeDebuggingSolution( var, value ); } input->close(); @@ -202,7 +206,7 @@ void Marabou::exportAssignment() const exportFile->write( Stringf( "%u\n", numberOfVariables ) ); // Export each assignment - for ( unsigned var = 0; var < numberOfVariables; ++var ) + for ( unsigned var = 0; var < numberOfVariables; ++var ) exportFile->write( Stringf( "%u, %f\n", var, _inputQuery.getSolutionValue( var ) ) ); exportFile->close(); @@ -238,7 +242,9 @@ void Marabou::displayResults( unsigned long long microSecondsElapsed ) const printf( "Input assignment:\n" ); for ( unsigned i = 0; i < _inputQuery.getNumInputVariables(); ++i ) - printf( "\tx%u = %lf\n", i, _inputQuery.getSolutionValue( _inputQuery.inputVariableByIndex( i ) ) ); + printf( "\tx%u = %lf\n", + i, + _inputQuery.getSolutionValue( _inputQuery.inputVariableByIndex( i ) ) ); if ( _inputQuery._networkLevelReasoner ) { @@ -265,7 +271,9 @@ void Marabou::displayResults( unsigned long long microSecondsElapsed ) const printf( "\n" ); printf( "Output:\n" ); for ( unsigned i = 0; i < _inputQuery.getNumOutputVariables(); ++i ) - printf( "\ty%u = %lf\n", i, _inputQuery.getSolutionValue( _inputQuery.outputVariableByIndex( i ) ) ); + printf( "\ty%u = %lf\n", + i, + _inputQuery.getSolutionValue( _inputQuery.outputVariableByIndex( i ) ) ); printf( "\n" ); } } @@ -300,13 +308,11 @@ void Marabou::displayResults( unsigned long long microSecondsElapsed ) const // Field #3: number of visited tree states summaryFile.write( Stringf( "%u ", - _engine.getStatistics()-> - getUnsignedAttribute - ( Statistics::NUM_VISITED_TREE_STATES ) ) ); + _engine.getStatistics()->getUnsignedAttribute( + Statistics::NUM_VISITED_TREE_STATES ) ) ); // Field #4: average pivot time in micro seconds - summaryFile.write( Stringf( "%u", - _engine.getStatistics()->getAveragePivotTimeInMicro() ) ); + summaryFile.write( Stringf( "%u", _engine.getStatistics()->getAveragePivotTimeInMicro() ) ); summaryFile.write( "\n" ); } diff --git a/src/engine/Marabou.h b/src/engine/Marabou.h index a926707969..648a2b8978 100644 --- a/src/engine/Marabou.h +++ b/src/engine/Marabou.h @@ -17,9 +17,9 @@ #define __Marabou_h__ #include "AcasParser.h" -#include "OnnxParser.h" #include "Engine.h" #include "InputQuery.h" +#include "OnnxParser.h" class Marabou { diff --git a/src/engine/MarabouError.h b/src/engine/MarabouError.h index 126d2d8b15..8b2079c6b9 100644 --- a/src/engine/MarabouError.h +++ b/src/engine/MarabouError.h @@ -21,7 +21,7 @@ class MarabouError : public Error { public: - enum Code { + enum Code { ALLOCATION_FAILED = 0, VARIABLE_INDEX_OUT_OF_RANGE = 1, VARIABLE_DOESNT_EXIST_IN_SOLUTION = 2, @@ -51,7 +51,7 @@ class MarabouError : public Error REQUESTED_NONEXISTENT_CASE_SPLIT = 26, UNABLE_TO_INITIALIZATION_PHASE_PATTERN = 27, BOUNDS_NOT_UP_TO_DATE_IN_LP_SOLVER = 28, - INVALID_LEAKY_RELU_SLOPE= 29, + INVALID_LEAKY_RELU_SLOPE = 29, // Error codes for Query Loader FILE_DOES_NOT_EXIST = 100, @@ -66,12 +66,13 @@ class MarabouError : public Error DEBUGGING_ERROR = 999, }; - MarabouError( MarabouError::Code code ) : Error( "MarabouError", (int)code ) - { - } + MarabouError( MarabouError::Code code ) + : Error( "MarabouError", (int)code ) + { + } - MarabouError( MarabouError::Code code, const char *userMessage ) : - Error( "MarabouError", (int)code, userMessage ) + MarabouError( MarabouError::Code code, const char *userMessage ) + : Error( "MarabouError", (int)code, userMessage ) { } }; diff --git a/src/engine/MarabouMain.cpp b/src/engine/MarabouMain.cpp index 6ba9551dc7..7ffbaafdc5 100644 --- a/src/engine/MarabouMain.cpp +++ b/src/engine/MarabouMain.cpp @@ -13,8 +13,8 @@ **/ -#include "DnCMarabou.h" #include "ConfigurationError.h" +#include "DnCMarabou.h" #include "Error.h" #include "LPSolverType.h" #include "Marabou.h" @@ -24,33 +24,33 @@ #include "cblas.h" #endif -static std::string getCompiler() { +static std::string getCompiler() +{ std::stringstream ss; #ifdef __GNUC__ ss << "GCC"; -#else /* __GNUC__ */ +#else /* __GNUC__ */ ss << "unknown compiler"; #endif /* __GNUC__ */ #ifdef __VERSION__ ss << " version " << __VERSION__; -#else /* __VERSION__ */ +#else /* __VERSION__ */ ss << ", unknown version"; #endif /* __VERSION__ */ return ss.str(); } -static std::string getCompiledDateTime() { +static std::string getCompiledDateTime() +{ return __DATE__ " " __TIME__; } void printVersion() { - std::cout << - "Marabou version " << MARABOU_VERSION << - " [" << GIT_BRANCH << " " << GIT_COMMIT_HASH << "]" - << "\ncompiled with " << getCompiler() - << "\non " << getCompiledDateTime() - << std::endl; + std::cout << "Marabou version " << MARABOU_VERSION << " [" << GIT_BRANCH << " " + << GIT_COMMIT_HASH << "]" + << "\ncompiled with " << getCompiler() << "\non " << getCompiledDateTime() + << std::endl; } void printHelpMessage() @@ -81,25 +81,31 @@ int marabouMain( int argc, char **argv ) if ( options->getBool( Options::PRODUCE_PROOFS ) ) { GlobalConfiguration::USE_DEEPSOI_LOCAL_SEARCH = false; - printf( "Proof production is not yet supported with DEEPSOI search, turning search off.\n" ); + printf( "Proof production is not yet supported with DEEPSOI search, turning search " + "off.\n" ); } - if ( options->getBool( Options::PRODUCE_PROOFS ) && ( options->getBool( Options::DNC_MODE ) ) ) + if ( options->getBool( Options::PRODUCE_PROOFS ) && + ( options->getBool( Options::DNC_MODE ) ) ) { options->setBool( Options::DNC_MODE, false ); printf( "Proof production is not yet supported with snc mode, turning --snc off.\n" ); } - if ( options->getBool( Options::PRODUCE_PROOFS ) && ( options->getBool( Options::SOLVE_WITH_MILP ) ) ) + if ( options->getBool( Options::PRODUCE_PROOFS ) && + ( options->getBool( Options::SOLVE_WITH_MILP ) ) ) { options->setBool( Options::SOLVE_WITH_MILP, false ); - printf( "Proof production is not yet supported with MILP solvers, turning --milp off.\n" ); + printf( + "Proof production is not yet supported with MILP solvers, turning --milp off.\n" ); } - if ( options->getBool( Options::PRODUCE_PROOFS ) && ( options->getLPSolverType() == LPSolverType::GUROBI ) ) + if ( options->getBool( Options::PRODUCE_PROOFS ) && + ( options->getLPSolverType() == LPSolverType::GUROBI ) ) { options->setString( Options::LP_SOLVER, "native" ); - printf( "Proof production is not yet supported with MILP solvers, using native simplex engine.\n" ); + printf( "Proof production is not yet supported with MILP solvers, using native simplex " + "engine.\n" ); } if ( options->getBool( Options::DNC_MODE ) && @@ -109,30 +115,33 @@ int marabouMain( int argc, char **argv ) "Cannot set both --snc and --poi to true..." ); } - if ( options->getBool( Options::PARALLEL_DEEPSOI ) && ( options->getBool( Options::SOLVE_WITH_MILP ) ) ) + if ( options->getBool( Options::PARALLEL_DEEPSOI ) && + ( options->getBool( Options::SOLVE_WITH_MILP ) ) ) { options->setBool( Options::SOLVE_WITH_MILP, false ); printf( "Cannot set both --poi and --milp to true, turning --milp off.\n" ); } if ( options->getBool( Options::DNC_MODE ) || - ( options->getBool( Options::PARALLEL_DEEPSOI ) && options->getInt( Options::NUM_WORKERS ) > 1 ) ) + ( options->getBool( Options::PARALLEL_DEEPSOI ) && + options->getInt( Options::NUM_WORKERS ) > 1 ) ) DnCMarabou().run(); else - { + { #ifdef ENABLE_OPENBLAS - openblas_set_num_threads( options->getInt( Options::NUM_BLAS_THREADS ) ); + openblas_set_num_threads( options->getInt( Options::NUM_BLAS_THREADS ) ); #endif Marabou().run(); - } + } } catch ( const Error &e ) { - fprintf( stderr, "Caught a %s error. Code: %u, Errno: %i, Message: %s.\n", - e.getErrorClass(), - e.getCode(), - e.getErrno(), - e.getUserMessage() ); + fprintf( stderr, + "Caught a %s error. Code: %u, Errno: %i, Message: %s.\n", + e.getErrorClass(), + e.getCode(), + e.getErrno(), + e.getUserMessage() ); return 1; } diff --git a/src/engine/MaxConstraint.cpp b/src/engine/MaxConstraint.cpp index 3899400492..232e2790d5 100644 --- a/src/engine/MaxConstraint.cpp +++ b/src/engine/MaxConstraint.cpp @@ -70,7 +70,7 @@ MaxConstraint::MaxConstraint( const String &serializedMax ) if ( eliminatedVariableFromString ) maxValueOfEliminatedFromString = std::stod( valuesIter->ascii() ); - *(this) = MaxConstraint( f, elements ); + *( this ) = MaxConstraint( f, elements ); _haveFeasibleEliminatedPhases = eliminatedVariableFromString; _maxValueOfEliminatedPhases = maxValueOfEliminatedFromString; } @@ -137,13 +137,11 @@ void MaxConstraint::unregisterAsWatcher( ITableau *tableau ) void MaxConstraint::notifyLowerBound( unsigned variable, double value ) { if ( _statistics ) - _statistics->incLongAttribute( - Statistics::NUM_BOUND_NOTIFICATIONS_TO_PL_CONSTRAINTS ); + _statistics->incLongAttribute( Statistics::NUM_BOUND_NOTIFICATIONS_TO_PL_CONSTRAINTS ); if ( _boundManager == nullptr ) { - if ( existsLowerBound( variable ) && - !FloatUtils::gt( value, getLowerBound( variable ) ) ) + if ( existsLowerBound( variable ) && !FloatUtils::gt( value, getLowerBound( variable ) ) ) return; setLowerBound( variable, value ); @@ -188,9 +186,8 @@ void MaxConstraint::notifyLowerBound( unsigned variable, double value ) } if ( phaseFixed() ) - _phaseStatus = ( _haveFeasibleEliminatedPhases - ? MAX_PHASE_ELIMINATED - : variableToPhase( *_elements.begin() ) ); + _phaseStatus = ( _haveFeasibleEliminatedPhases ? MAX_PHASE_ELIMINATED + : variableToPhase( *_elements.begin() ) ); if ( isActive() && _boundManager ) { @@ -209,13 +206,11 @@ void MaxConstraint::notifyLowerBound( unsigned variable, double value ) void MaxConstraint::notifyUpperBound( unsigned variable, double value ) { if ( _statistics ) - _statistics->incLongAttribute( - Statistics::NUM_BOUND_NOTIFICATIONS_TO_PL_CONSTRAINTS ); + _statistics->incLongAttribute( Statistics::NUM_BOUND_NOTIFICATIONS_TO_PL_CONSTRAINTS ); if ( _boundManager == nullptr ) { - if ( existsUpperBound( variable ) && - !FloatUtils::lt( value, getUpperBound( variable ) ) ) + if ( existsUpperBound( variable ) && !FloatUtils::lt( value, getUpperBound( variable ) ) ) return; setUpperBound( variable, value ); @@ -252,9 +247,8 @@ void MaxConstraint::notifyUpperBound( unsigned variable, double value ) } if ( phaseFixed() ) - _phaseStatus = ( _haveFeasibleEliminatedPhases - ? MAX_PHASE_ELIMINATED - : variableToPhase( *_elements.begin() ) ); + _phaseStatus = ( _haveFeasibleEliminatedPhases ? MAX_PHASE_ELIMINATED + : variableToPhase( *_elements.begin() ) ); // There is no need to recompute the max lower bound and max index here. @@ -311,15 +305,14 @@ void MaxConstraint::getEntailedTightenings( List &tightenings ) cons // fLB cannot be smaller than maxElementLB if ( FloatUtils::lt( fLB, maxElementLB ) ) - tightenings.append( Tightening( _f, maxElementLB, Tightening::LB ) ); + tightenings.append( Tightening( _f, maxElementLB, Tightening::LB ) ); // TODO: bound tightening for aux vars. } bool MaxConstraint::participatingVariable( unsigned variable ) const { - return ( variable == _f ) || _elements.exists( variable ) || - _auxToElement.exists( variable ); + return ( variable == _f ) || _elements.exists( variable ) || _auxToElement.exists( variable ); } List MaxConstraint::getParticipatingVariables() const @@ -353,18 +346,15 @@ unsigned MaxConstraint::getF() const bool MaxConstraint::satisfied() const { - DEBUG({ - if ( !( existsAssignment( _f ) ) ) - throw MarabouError - ( MarabouError::PARTICIPATING_VARIABLE_MISSING_ASSIGNMENT, - Stringf( "f(x%u) assignment missing.", _f ).ascii() ); - for ( const auto &element : _elements ) - if ( !( existsAssignment( element ) ) ) - throw MarabouError - ( MarabouError::PARTICIPATING_VARIABLE_MISSING_ASSIGNMENT, - Stringf( "input(x%u) assignment missing.", - element ).ascii() ); - }); + DEBUG( { + if ( !( existsAssignment( _f ) ) ) + throw MarabouError( MarabouError::PARTICIPATING_VARIABLE_MISSING_ASSIGNMENT, + Stringf( "f(x%u) assignment missing.", _f ).ascii() ); + for ( const auto &element : _elements ) + if ( !( existsAssignment( element ) ) ) + throw MarabouError( MarabouError::PARTICIPATING_VARIABLE_MISSING_ASSIGNMENT, + Stringf( "input(x%u) assignment missing.", element ).ascii() ); + } ); double fValue = getAssignment( _f ); double maxValue = _maxValueOfEliminatedPhases; @@ -450,12 +440,10 @@ PiecewiseLinearCaseSplit MaxConstraint::getCaseSplit( PhaseStatus phase ) const if ( phase == MAX_PHASE_ELIMINATED ) { PiecewiseLinearCaseSplit eliminatedPhase; - eliminatedPhase.storeBoundTightening - ( Tightening( _f, _maxValueOfEliminatedPhases, - Tightening::LB ) ); - eliminatedPhase.storeBoundTightening - ( Tightening( _f, _maxValueOfEliminatedPhases, - Tightening::UB ) ); + eliminatedPhase.storeBoundTightening( + Tightening( _f, _maxValueOfEliminatedPhases, Tightening::LB ) ); + eliminatedPhase.storeBoundTightening( + Tightening( _f, _maxValueOfEliminatedPhases, Tightening::UB ) ); return eliminatedPhase; } else @@ -466,8 +454,7 @@ PiecewiseLinearCaseSplit MaxConstraint::getCaseSplit( PhaseStatus phase ) const if ( argMax != _f ) { // We had f - argMax = aux and - maxPhase.storeBoundTightening( Tightening( _elementToAux[argMax], 0, - Tightening::UB ) ); + maxPhase.storeBoundTightening( Tightening( _elementToAux[argMax], 0, Tightening::UB ) ); } return maxPhase; } @@ -495,7 +482,7 @@ void MaxConstraint::updateVariableIndex( unsigned oldIndex, unsigned newIndex ) _auxToElement[auxVar] = newIndex; if ( _phaseStatus == variableToPhase( oldIndex ) ) - _phaseStatus = variableToPhase( newIndex ) ; + _phaseStatus = variableToPhase( newIndex ); } else { @@ -525,8 +512,7 @@ void MaxConstraint::eliminateVariable( unsigned var, double value ) _maxLowerBound = FloatUtils::max( value, _maxLowerBound ); - _maxValueOfEliminatedPhases = FloatUtils::max - ( value, _maxValueOfEliminatedPhases ); + _maxValueOfEliminatedPhases = FloatUtils::max( value, _maxValueOfEliminatedPhases ); _haveFeasibleEliminatedPhases = FloatUtils::gte( _maxValueOfEliminatedPhases, _maxLowerBound ); @@ -547,9 +533,8 @@ void MaxConstraint::eliminateVariable( unsigned var, double value ) } if ( phaseFixed() ) - _phaseStatus = ( _haveFeasibleEliminatedPhases ? - MAX_PHASE_ELIMINATED : - variableToPhase( *_elements.begin() ) ); + _phaseStatus = ( _haveFeasibleEliminatedPhases ? MAX_PHASE_ELIMINATED + : variableToPhase( *_elements.begin() ) ); if ( _elements.size() == 0 ) _obsolete = true; @@ -603,11 +588,10 @@ void MaxConstraint::transformToUseAuxVariables( InputQuery &inputQuery ) } } -void MaxConstraint::getCostFunctionComponent( LinearExpression &cost, - PhaseStatus phase ) const +void MaxConstraint::getCostFunctionComponent( LinearExpression &cost, PhaseStatus phase ) const { // If the constraint is not active or is fixed, it contributes nothing - if( !isActive() || phaseFixed() ) + if ( !isActive() || phaseFixed() ) return; if ( phase == MAX_PHASE_ELIMINATED ) @@ -628,18 +612,16 @@ void MaxConstraint::getCostFunctionComponent( LinearExpression &cost, } } -PhaseStatus MaxConstraint::getPhaseStatusInAssignment( const Map - &assignment ) const +PhaseStatus +MaxConstraint::getPhaseStatusInAssignment( const Map &assignment ) const { - auto byAssignment = [&](const unsigned& a, const unsigned& b) { - return assignment[a] < assignment[b]; - }; - unsigned largestVariable = *std::max_element( _elements.begin(), - _elements.end(), - byAssignment ); + auto byAssignment = [&]( const unsigned &a, const unsigned &b ) { + return assignment[a] < assignment[b]; + }; + unsigned largestVariable = + *std::max_element( _elements.begin(), _elements.end(), byAssignment ); double value = assignment[largestVariable]; - if ( _haveFeasibleEliminatedPhases && - FloatUtils::lt( value, _maxValueOfEliminatedPhases ) ) + if ( _haveFeasibleEliminatedPhases && FloatUtils::lt( value, _maxValueOfEliminatedPhases ) ) return MAX_PHASE_ELIMINATED; else return variableToPhase( largestVariable ); @@ -689,7 +671,8 @@ void MaxConstraint::eliminateCase( unsigned variable ) } if ( proofs ) { - if ( _elementToTighteningRow.exists( variable ) && _elementToTighteningRow[variable] != NULL ) + if ( _elementToTighteningRow.exists( variable ) && + _elementToTighteningRow[variable] != NULL ) { _elementToTighteningRow[variable] = NULL; _elementToTighteningRow.erase( variable ); @@ -713,13 +696,12 @@ bool MaxConstraint::haveOutOfBoundVariables() const double value = getAssignment( element ); if ( FloatUtils::gt( getLowerBound( element ), value ) || FloatUtils::lt( getUpperBound( element ), value ) ) - return true; + return true; unsigned aux = _elementToAux[element]; double auxValue = getAssignment( aux ); if ( FloatUtils::gt( getLowerBound( aux ), auxValue ) || FloatUtils::lt( getUpperBound( aux ), auxValue ) ) return true; - } return false; } @@ -733,17 +715,18 @@ void MaxConstraint::createElementTighteningRow( unsigned element ) _elementToTighteningRow[element] = std::make_shared( 3 ); // f = element + aux + counterpart (an additional aux variable of tableau) - _elementToTighteningRow[element]->_lhs = _f; + _elementToTighteningRow[element]->_lhs = _f; _elementToTighteningRow[element]->_row[0] = TableauRow::Entry( element, 1 ); _elementToTighteningRow[element]->_row[1] = TableauRow::Entry( _elementToAux[element], 1 ); - _elementToTighteningRow[element]->_row[2] = TableauRow::Entry( _elementToTableauAux[element], 1 ); + _elementToTighteningRow[element]->_row[2] = + TableauRow::Entry( _elementToTableauAux[element], 1 ); } const List MaxConstraint::getNativeAuxVars() const { List auxVars = {}; for ( const auto &element : _elements ) - auxVars.append( _elementToAux[element]); + auxVars.append( _elementToAux[element] ); return auxVars; } @@ -778,9 +761,11 @@ void MaxConstraint::applyTightenings( const List &tightenings ) cons } } - ASSERT( _elements.exists( maxElementForLB ) && _elementToTighteningRow[maxElementForLB] != NULL ); - ASSERT ( tightening._variable == _f ); - _boundManager->tightenLowerBound( _f, maxElementLB, *_elementToTighteningRow[maxElementForLB] ); + ASSERT( _elements.exists( maxElementForLB ) && + _elementToTighteningRow[maxElementForLB] != NULL ); + ASSERT( tightening._variable == _f ); + _boundManager->tightenLowerBound( + _f, maxElementLB, *_elementToTighteningRow[maxElementForLB] ); } else _boundManager->tightenLowerBound( tightening._variable, tightening._value ); @@ -790,13 +775,20 @@ void MaxConstraint::applyTightenings( const List &tightenings ) cons if ( proofs ) { if ( tightening._variable == _f ) - _boundManager->addLemmaExplanationAndTightenBound( _f, tightening._value, BoundType::UPPER, getElements(), - BoundType::UPPER, getType() ); + _boundManager->addLemmaExplanationAndTightenBound( _f, + tightening._value, + BoundType::UPPER, + getElements(), + BoundType::UPPER, + getType() ); else { - ASSERT (_elements.exists( tightening._variable ) ); + ASSERT( _elements.exists( tightening._variable ) ); ASSERT( _elementToTighteningRow[tightening._variable] != NULL ); - _boundManager->tightenUpperBound( tightening._variable, tightening._value, *_elementToTighteningRow[tightening._variable] ); + _boundManager->tightenUpperBound( + tightening._variable, + tightening._value, + *_elementToTighteningRow[tightening._variable] ); } } else diff --git a/src/engine/MaxConstraint.h b/src/engine/MaxConstraint.h index 9f5b9f1d37..2fd6dca5b6 100644 --- a/src/engine/MaxConstraint.h +++ b/src/engine/MaxConstraint.h @@ -46,9 +46,9 @@ #ifndef __MaxConstraint_h__ #define __MaxConstraint_h__ -#include "PiecewiseLinearConstraint.h" #include "LinearExpression.h" #include "Map.h" +#include "PiecewiseLinearConstraint.h" #define MAX_VARIABLE_TO_PHASE_OFFSET 1 @@ -194,8 +194,8 @@ class MaxConstraint : public PiecewiseLinearConstraint virtual void getCostFunctionComponent( LinearExpression &cost, PhaseStatus phase ) const override; - virtual PhaseStatus getPhaseStatusInAssignment( const Map - &assignment ) const override; + virtual PhaseStatus + getPhaseStatusInAssignment( const Map &assignment ) const override; /* Returns string with shape: @@ -238,18 +238,18 @@ class MaxConstraint : public PiecewiseLinearConstraint inline PhaseStatus variableToPhase( unsigned variable ) const { return ( variable == MAX_PHASE_ELIMINATED ) - ? MAX_PHASE_ELIMINATED - : static_cast( variable + MAX_VARIABLE_TO_PHASE_OFFSET ); + ? MAX_PHASE_ELIMINATED + : static_cast( variable + MAX_VARIABLE_TO_PHASE_OFFSET ); } inline unsigned phaseToVariable( PhaseStatus phase ) const { return ( phase == MAX_PHASE_ELIMINATED ) - ? MAX_PHASE_ELIMINATED - : static_cast( phase ) - MAX_VARIABLE_TO_PHASE_OFFSET; + ? MAX_PHASE_ELIMINATED + : static_cast( phase ) - MAX_VARIABLE_TO_PHASE_OFFSET; } - private: +private: unsigned _f; Set _elements; Set _initialElements; diff --git a/src/engine/NonlinearConstraint.cpp b/src/engine/NonlinearConstraint.cpp index 8f3d5c496a..8528928494 100644 --- a/src/engine/NonlinearConstraint.cpp +++ b/src/engine/NonlinearConstraint.cpp @@ -10,9 +10,10 @@ ** directory for licensing information.\endverbatim ** ** See the description of the class in NonlinearConstraint.h. -**/ + **/ #include "NonlinearConstraint.h" + #include "Statistics.h" NonlinearConstraint::NonlinearConstraint() @@ -22,8 +23,7 @@ NonlinearConstraint::NonlinearConstraint() { } -void NonlinearConstraint::registerBoundManager( - BoundManager *boundManager ) +void NonlinearConstraint::registerBoundManager( BoundManager *boundManager ) { ASSERT( _boundManager == nullptr ); _boundManager = boundManager; diff --git a/src/engine/NonlinearConstraint.h b/src/engine/NonlinearConstraint.h index b244c74799..e53fd66b76 100644 --- a/src/engine/NonlinearConstraint.h +++ b/src/engine/NonlinearConstraint.h @@ -16,8 +16,8 @@ #ifndef __NonlinearConstraint_h__ #define __NonlinearConstraint_h__ -#include "FloatUtils.h" #include "BoundManager.h" +#include "FloatUtils.h" #include "ITableau.h" #include "List.h" #include "Map.h" @@ -64,8 +64,12 @@ class NonlinearConstraint : public ITableau::VariableWatcher /* The variable watcher notifcation callbacks, about a change in a variable's value or bounds. */ - virtual void notifyLowerBound( unsigned /* variable */, double /* bound */ ) {} - virtual void notifyUpperBound( unsigned /* variable */, double /* bound */ ) {} + virtual void notifyLowerBound( unsigned /* variable */, double /* bound */ ) + { + } + virtual void notifyUpperBound( unsigned /* variable */, double /* bound */ ) + { + } /* Returns true iff the variable participates in this nonlinear constraint. @@ -81,8 +85,7 @@ class NonlinearConstraint : public ITableau::VariableWatcher Before solving: get additional auxiliary euqations (typically bound-dependent) that this constraint would like to add to the equation pool. */ - virtual void addAuxiliaryEquationsAfterPreprocessing( InputQuery - &/* inputQuery */ ) {}; + virtual void addAuxiliaryEquationsAfterPreprocessing( InputQuery & /* inputQuery */ ){}; /* Returns true iff the assignment satisfies the constraint. @@ -92,7 +95,9 @@ class NonlinearConstraint : public ITableau::VariableWatcher /* Dump the current state of the constraint. */ - virtual void dump( String & ) const {} + virtual void dump( String & ) const + { + } /* Preprocessing related functions, to inform that a variable has been eliminated completely @@ -104,7 +109,10 @@ class NonlinearConstraint : public ITableau::VariableWatcher virtual void updateVariableIndex( unsigned oldIndex, unsigned newIndex ) = 0; virtual bool constraintObsolete() const = 0; - virtual bool supportVariableElimination() const { return false; }; + virtual bool supportVariableElimination() const + { + return false; + }; /* Get the tightenings entailed by the constraint. @@ -216,17 +224,17 @@ class NonlinearConstraint : public ITableau::VariableWatcher */ bool tightenLowerBound( unsigned var, double value ) { - if ( _boundManager != nullptr ) - { - _boundManager->setLowerBound( var, value ); - return true; - } - else if ( !existsLowerBound( var ) || _lowerBounds[var] < value ) - { - _lowerBounds[var] = value; - return true; - } - return false; + if ( _boundManager != nullptr ) + { + _boundManager->setLowerBound( var, value ); + return true; + } + else if ( !existsLowerBound( var ) || _lowerBounds[var] < value ) + { + _lowerBounds[var] = value; + return true; + } + return false; } /* @@ -234,17 +242,17 @@ class NonlinearConstraint : public ITableau::VariableWatcher */ bool tightenUpperBound( unsigned var, double value ) { - if ( _boundManager != nullptr ) - { - _boundManager->setUpperBound( var, value ); - return true; - } - else if ( !existsUpperBound( var ) || _upperBounds[var] > value ) - { - _upperBounds[var] = value; - return true; - } - return false; + if ( _boundManager != nullptr ) + { + _boundManager->setUpperBound( var, value ); + return true; + } + else if ( !existsUpperBound( var ) || _upperBounds[var] > value ) + { + _upperBounds[var] = value; + return true; + } + return false; } /**********************************************************************/ diff --git a/src/engine/PLConstraintScoreTracker.cpp b/src/engine/PLConstraintScoreTracker.cpp index 87e088e7d1..2e4607998f 100644 --- a/src/engine/PLConstraintScoreTracker.cpp +++ b/src/engine/PLConstraintScoreTracker.cpp @@ -21,8 +21,7 @@ void PLConstraintScoreTracker::reset() _plConstraintToScore.clear(); } -void PLConstraintScoreTracker::initialize( const List - &plConstraints ) +void PLConstraintScoreTracker::initialize( const List &plConstraints ) { reset(); for ( const auto &constraint : plConstraints ) @@ -32,8 +31,7 @@ void PLConstraintScoreTracker::initialize( const ListisActive() && !entry._constraint->phaseFixed() ) { - SCORE_TRACKER_LOG( Stringf( "Score of top unfixed plConstraint: %.2f", - entry._score ).ascii() ); + SCORE_TRACKER_LOG( + Stringf( "Score of top unfixed plConstraint: %.2f", entry._score ).ascii() ); return entry._constraint; } } diff --git a/src/engine/PLConstraintScoreTracker.h b/src/engine/PLConstraintScoreTracker.h index 547e0e953a..46ccf3586b 100644 --- a/src/engine/PLConstraintScoreTracker.h +++ b/src/engine/PLConstraintScoreTracker.h @@ -23,14 +23,14 @@ #include -#define SCORE_TRACKER_LOG(x, ...) LOG(GlobalConfiguration::SCORE_TRACKER_LOGGING, "PLConstraintScoreTracker: %s\n", x) +#define SCORE_TRACKER_LOG( x, ... ) \ + LOG( GlobalConfiguration::SCORE_TRACKER_LOGGING, "PLConstraintScoreTracker: %s\n", x ) struct ScoreEntry { ScoreEntry( PiecewiseLinearConstraint *constraint, double score ) : _constraint( constraint ) - , _score( score ) - {}; + , _score( score ){}; bool operator<( const ScoreEntry &other ) const { @@ -64,8 +64,7 @@ class PLConstraintScoreTracker /* Update the score of a constraint. */ - virtual void updateScore( PiecewiseLinearConstraint *constraint, - double score ) = 0; + virtual void updateScore( PiecewiseLinearConstraint *constraint, double score ) = 0; /* Set the score of a constraint. @@ -91,13 +90,11 @@ class PLConstraintScoreTracker */ inline double getScore( PiecewiseLinearConstraint *constraint ) { - DEBUG({ - ASSERT( _plConstraintToScore.exists( constraint ) ); - ASSERT( _scores.find - ( ScoreEntry( constraint, - _plConstraintToScore[constraint] ) ) != - _scores.end() ); - }); + DEBUG( { + ASSERT( _plConstraintToScore.exists( constraint ) ); + ASSERT( _scores.find( ScoreEntry( constraint, _plConstraintToScore[constraint] ) ) != + _scores.end() ); + } ); return _plConstraintToScore[constraint]; } diff --git a/src/engine/PiecewiseLinearCaseSplit.cpp b/src/engine/PiecewiseLinearCaseSplit.cpp index 6a903962a0..b02bec7d78 100644 --- a/src/engine/PiecewiseLinearCaseSplit.cpp +++ b/src/engine/PiecewiseLinearCaseSplit.cpp @@ -13,8 +13,10 @@ **/ -#include "MStringf.h" #include "PiecewiseLinearCaseSplit.h" + +#include "MStringf.h" + #include void PiecewiseLinearCaseSplit::storeBoundTightening( const Tightening &tightening ) @@ -22,19 +24,19 @@ void PiecewiseLinearCaseSplit::storeBoundTightening( const Tightening &tightenin _bounds.append( tightening ); } -const List & PiecewiseLinearCaseSplit::getBoundTightenings() const +const List &PiecewiseLinearCaseSplit::getBoundTightenings() const { return _bounds; } void PiecewiseLinearCaseSplit::addEquation( const Equation &equation ) { - _equations.append( equation ); + _equations.append( equation ); } -const List & PiecewiseLinearCaseSplit::getEquations() const +const List &PiecewiseLinearCaseSplit::getEquations() const { - return _equations; + return _equations; } void PiecewiseLinearCaseSplit::dump( String &output ) const @@ -44,7 +46,9 @@ void PiecewiseLinearCaseSplit::dump( String &output ) const for ( const auto &bound : _bounds ) { output += Stringf( "\t\tVariable: %u. New bound: %.2lf. Bound type: %s\n", - bound._variable, bound._value, bound._type == Tightening::LB ? "lower" : "upper" ); + bound._variable, + bound._value, + bound._type == Tightening::LB ? "lower" : "upper" ); } output += String( "\n\tEquations are:\n" ); diff --git a/src/engine/PiecewiseLinearCaseSplit.h b/src/engine/PiecewiseLinearCaseSplit.h index aa034d9b84..c65800ceea 100644 --- a/src/engine/PiecewiseLinearCaseSplit.h +++ b/src/engine/PiecewiseLinearCaseSplit.h @@ -35,7 +35,7 @@ class PiecewiseLinearCaseSplit Store information regarding a new equation to be added. */ void addEquation( const Equation &equation ); - const List &getEquations() const; + const List &getEquations() const; /* Dump the case split - for debugging purposes. diff --git a/src/engine/PiecewiseLinearConstraint.cpp b/src/engine/PiecewiseLinearConstraint.cpp index 80241a4799..952c51a1dd 100644 --- a/src/engine/PiecewiseLinearConstraint.cpp +++ b/src/engine/PiecewiseLinearConstraint.cpp @@ -14,6 +14,7 @@ **/ #include "PiecewiseLinearConstraint.h" + #include "Statistics.h" PiecewiseLinearConstraint::PiecewiseLinearConstraint() @@ -65,15 +66,13 @@ bool PiecewiseLinearConstraint::isActive() const return _constraintActive; } -void PiecewiseLinearConstraint::registerBoundManager( - IBoundManager *boundManager ) +void PiecewiseLinearConstraint::registerBoundManager( IBoundManager *boundManager ) { ASSERT( _boundManager == nullptr ); _boundManager = boundManager; } -void PiecewiseLinearConstraint::initializeCDOs( - CVC4::context::Context *context ) +void PiecewiseLinearConstraint::initializeCDOs( CVC4::context::Context *context ) { ASSERT( _context == nullptr ); _context = context; @@ -101,8 +100,7 @@ void PiecewiseLinearConstraint::initializeCDPhaseStatus() { ASSERT( _context != nullptr ); ASSERT( _cdPhaseStatus == nullptr ); - _cdPhaseStatus = - new ( true ) CVC4::context::CDO( _context, _phaseStatus ); + _cdPhaseStatus = new ( true ) CVC4::context::CDO( _context, _phaseStatus ); } void PiecewiseLinearConstraint::cdoCleanup() @@ -141,8 +139,7 @@ void PiecewiseLinearConstraint::setPhaseStatus( PhaseStatus phaseStatus ) _phaseStatus = phaseStatus; } -void PiecewiseLinearConstraint::initializeDuplicateCDOs( - PiecewiseLinearConstraint *clone ) const +void PiecewiseLinearConstraint::initializeDuplicateCDOs( PiecewiseLinearConstraint *clone ) const { if ( clone->_context != nullptr ) { @@ -163,8 +160,7 @@ void PiecewiseLinearConstraint::initializeDuplicateCDOs( } } -void PiecewiseLinearConstraint::markInfeasible( - PhaseStatus infeasibleCase ) +void PiecewiseLinearConstraint::markInfeasible( PhaseStatus infeasibleCase ) { _cdInfeasibleCases->push_back( infeasibleCase ); } @@ -179,8 +175,7 @@ PhaseStatus PiecewiseLinearConstraint::nextFeasibleCase() List allCases = getAllCases(); for ( PhaseStatus thisCase : allCases ) { - auto loc = - std::find( _cdInfeasibleCases->begin(), _cdInfeasibleCases->end(), thisCase ); + auto loc = std::find( _cdInfeasibleCases->begin(), _cdInfeasibleCases->end(), thisCase ); // Case is not infeasible, return it as feasible if ( loc == _cdInfeasibleCases->end() ) @@ -195,7 +190,8 @@ PhaseStatus PiecewiseLinearConstraint::nextFeasibleCase() bool PiecewiseLinearConstraint::isCaseInfeasible( PhaseStatus phase ) const { ASSERT( _cdInfeasibleCases ); - return std::find( _cdInfeasibleCases->begin(), _cdInfeasibleCases->end(), phase ) != _cdInfeasibleCases->end(); + return std::find( _cdInfeasibleCases->begin(), _cdInfeasibleCases->end(), phase ) != + _cdInfeasibleCases->end(); } void PiecewiseLinearConstraint::setStatistics( Statistics *statistics ) diff --git a/src/engine/PiecewiseLinearConstraint.h b/src/engine/PiecewiseLinearConstraint.h index 0f7f1181ef..536146622f 100644 --- a/src/engine/PiecewiseLinearConstraint.h +++ b/src/engine/PiecewiseLinearConstraint.h @@ -104,9 +104,7 @@ class PiecewiseLinearConstraint : public ITableau::VariableWatcher bool operator==( const Fix &other ) const { - return - _variable == other._variable && - FloatUtils::areEqual( _value, other._value ); + return _variable == other._variable && FloatUtils::areEqual( _value, other._value ); } unsigned _variable; @@ -151,8 +149,12 @@ class PiecewiseLinearConstraint : public ITableau::VariableWatcher /* The variable watcher notifcation callbacks, about a change in a variable's value or bounds. */ - virtual void notifyLowerBound( unsigned /* variable */, double /* bound */ ) {} - virtual void notifyUpperBound( unsigned /* variable */, double /* bound */ ) {} + virtual void notifyLowerBound( unsigned /* variable */, double /* bound */ ) + { + } + virtual void notifyUpperBound( unsigned /* variable */, double /* bound */ ) + { + } /* Turn the constraint on/off. @@ -223,7 +225,9 @@ class PiecewiseLinearConstraint : public ITableau::VariableWatcher /* Dump the current state of the constraint. */ - virtual void dump( String & ) const {} + virtual void dump( String & ) const + { + } /* Preprocessing related functions, to inform that a variable has been eliminated completely @@ -244,7 +248,7 @@ class PiecewiseLinearConstraint : public ITableau::VariableWatcher Transform the piecewise linear constraint so that each disjunct contains only bound constraints. */ - virtual void transformToUseAuxVariables( InputQuery & ) {}; + virtual void transformToUseAuxVariables( InputQuery & ){}; void setStatistics( Statistics *statistics ); @@ -252,15 +256,22 @@ class PiecewiseLinearConstraint : public ITableau::VariableWatcher Before solving: get additional auxiliary euqations (typically bound-dependent) that this constraint would like to add to the equation pool. */ - virtual void addAuxiliaryEquationsAfterPreprocessing( InputQuery - &/* inputQuery */ ) {} + virtual void addAuxiliaryEquationsAfterPreprocessing( InputQuery & /* inputQuery */ ) + { + } /* Whether the constraint can contribute the SoI cost function. */ - virtual bool supportSoI() const { return false; }; + virtual bool supportSoI() const + { + return false; + }; - virtual bool supportVariableElimination() const { return true; }; + virtual bool supportVariableElimination() const + { + return true; + }; /* Ask the piecewise linear constraint to add its cost term corresponding to @@ -269,8 +280,10 @@ class PiecewiseLinearConstraint : public ITableau::VariableWatcher Minimizing the added term should lead to the constraint being "closer to satisfied" in the given phase status. */ - virtual void getCostFunctionComponent( LinearExpression &/* cost */, - PhaseStatus /* phase */ ) const {} + virtual void getCostFunctionComponent( LinearExpression & /* cost */, + PhaseStatus /* phase */ ) const + { + } /* Return the phase status corresponding to the values of the input @@ -278,8 +291,8 @@ class PiecewiseLinearConstraint : public ITableau::VariableWatcher variable's assignment is positive, then the method returns RELU_PHASE_ACTIVE. Otherwise, it returns RELU_PHASE_INACTIVE. */ - virtual PhaseStatus getPhaseStatusInAssignment( const Map - &/* assignment */ ) const + virtual PhaseStatus + getPhaseStatusInAssignment( const Map & /* assignment */ ) const { throw MarabouError( MarabouError::FEATURE_NOT_YET_SUPPORTED ); } @@ -454,9 +467,10 @@ class PiecewiseLinearConstraint : public ITableau::VariableWatcher } /* - Add a variable to the list of aux vars designated in the Tableau, add connect it to the constraintAuxVariable + Add a variable to the list of aux vars designated in the Tableau, add connect it to the + constraintAuxVariable */ - virtual void addTableauAuxVar( unsigned tableauAuxVar, unsigned constraintAuxVar ) = 0; + virtual void addTableauAuxVar( unsigned tableauAuxVar, unsigned constraintAuxVar ) = 0; /* Get the native auxiliary vars @@ -620,7 +634,6 @@ class PiecewiseLinearConstraint : public ITableau::VariableWatcher } List _tableauAuxVars; - }; #endif // __PiecewiseLinearConstraint_h__ diff --git a/src/engine/PolarityBasedDivider.cpp b/src/engine/PolarityBasedDivider.cpp index 5087ce1a3f..851977a572 100644 --- a/src/engine/PolarityBasedDivider.cpp +++ b/src/engine/PolarityBasedDivider.cpp @@ -13,10 +13,11 @@ **/ +#include "PolarityBasedDivider.h" + #include "Debug.h" #include "EngineState.h" #include "FloatUtils.h" -#include "PolarityBasedDivider.h" #include "MStringf.h" #include "PiecewiseLinearCaseSplit.h" @@ -25,13 +26,12 @@ PolarityBasedDivider::PolarityBasedDivider( std::shared_ptr engine ) { } -void PolarityBasedDivider::createSubQueries( unsigned numNewSubqueries, const - String queryIdPrefix, const - unsigned previousDepth, const - PiecewiseLinearCaseSplit - &previousSplit, const unsigned - timeoutInSeconds, SubQueries - &subQueries ) +void PolarityBasedDivider::createSubQueries( unsigned numNewSubqueries, + const String queryIdPrefix, + const unsigned previousDepth, + const PiecewiseLinearCaseSplit &previousSplit, + const unsigned timeoutInSeconds, + SubQueries &subQueries ) { unsigned numBisects = (unsigned)log2( numNewSubqueries ); @@ -45,8 +45,7 @@ void PolarityBasedDivider::createSubQueries( unsigned numNewSubqueries, const List newSplits; for ( const auto &split : splits ) { - PiecewiseLinearConstraint *pLConstraintToSplit = - getPLConstraintToSplit( *split ); + PiecewiseLinearConstraint *pLConstraintToSplit = getPLConstraintToSplit( *split ); if ( pLConstraintToSplit == NULL ) { auto newSplit = new PiecewiseLinearCaseSplit(); @@ -91,8 +90,8 @@ void PolarityBasedDivider::createSubQueries( unsigned numNewSubqueries, const } } -PiecewiseLinearConstraint *PolarityBasedDivider::getPLConstraintToSplit -( const PiecewiseLinearCaseSplit &split ) +PiecewiseLinearConstraint * +PolarityBasedDivider::getPLConstraintToSplit( const PiecewiseLinearCaseSplit &split ) { _engine->applySnCSplit( split, "" ); diff --git a/src/engine/PolarityBasedDivider.h b/src/engine/PolarityBasedDivider.h index 7b2774c0cd..e5f4d909c0 100644 --- a/src/engine/PolarityBasedDivider.h +++ b/src/engine/PolarityBasedDivider.h @@ -29,8 +29,7 @@ class PolarityBasedDivider : public QueryDivider void createSubQueries( unsigned numNewSubQueries, const String queryIdPrefix, const unsigned previousDepth, - const PiecewiseLinearCaseSplit - &previousSplit, + const PiecewiseLinearCaseSplit &previousSplit, const unsigned timeoutInSeconds, SubQueries &subQueries ); @@ -41,9 +40,7 @@ class PolarityBasedDivider : public QueryDivider Aong the K earliest unfixed ReLUs in the topological order, pick the one with polarity closest to 0. K is equal to GlobalConfiguration::POLARITY_CAONDIDATES_THRESHOLD */ - PiecewiseLinearConstraint *getPLConstraintToSplit( const - PiecewiseLinearCaseSplit - &split ); + PiecewiseLinearConstraint *getPLConstraintToSplit( const PiecewiseLinearCaseSplit &split ); }; #endif // __LargestIntervalDivider_h__ diff --git a/src/engine/PrecisionRestorer.cpp b/src/engine/PrecisionRestorer.cpp index fd56523ecd..aa1b1f6254 100644 --- a/src/engine/PrecisionRestorer.cpp +++ b/src/engine/PrecisionRestorer.cpp @@ -13,10 +13,11 @@ **/ +#include "PrecisionRestorer.h" + #include "Debug.h" #include "FloatUtils.h" #include "MalformedBasisException.h" -#include "PrecisionRestorer.h" #include "MarabouError.h" #include "SmtCore.h" #include "TableauStateStorageLevel.h" @@ -24,8 +25,7 @@ void PrecisionRestorer::storeInitialEngineState( const IEngine &engine ) { - engine.storeState( _initialEngineState, - TableauStateStorageLevel::STORE_ENTIRE_TABLEAU_STATE ); + engine.storeState( _initialEngineState, TableauStateStorageLevel::STORE_ENTIRE_TABLEAU_STATE ); } void PrecisionRestorer::restoreInitialEngineState( IEngine &engine ) @@ -46,8 +46,7 @@ void PrecisionRestorer::restorePrecision( IEngine &engine, Set shouldBeBasic = tableau.getBasicVariables(); EngineState targetEngineState; - engine.storeState( targetEngineState, - TableauStateStorageLevel::STORE_NONE ); + engine.storeState( targetEngineState, TableauStateStorageLevel::STORE_NONE ); BoundExplainer boundExplainerBackup( targetN, targetM, engine.getContext() ); Vector groundUpperBoundsBackup; @@ -92,11 +91,9 @@ void PrecisionRestorer::restorePrecision( IEngine &engine, // is added. If we fail to restore the dimensions, we cannot restore the // basics. - bool dimensionsRestored = - ( tableau.getN() == targetN ) && ( tableau.getM() == targetM ); + bool dimensionsRestored = ( tableau.getN() == targetN ) && ( tableau.getM() == targetM ); - ASSERT( dimensionsRestored || - GlobalConfiguration::USE_COLUMN_MERGING_EQUATIONS ); + ASSERT( dimensionsRestored || GlobalConfiguration::USE_COLUMN_MERGING_EQUATIONS ); Set currentBasics = tableau.getBasicVariables(); @@ -130,10 +127,9 @@ void PrecisionRestorer::restorePrecision( IEngine &engine, } catch ( MalformedBasisException & ) { - throw MarabouError( - MarabouError::RESTORATION_FAILED_TO_REFACTORIZE_BASIS, - "Precision restoration failed - could not refactorize " - "basis after setting basics" ); + throw MarabouError( MarabouError::RESTORATION_FAILED_TO_REFACTORIZE_BASIS, + "Precision restoration failed - could not refactorize " + "basis after setting basics" ); } } } @@ -166,10 +162,8 @@ void PrecisionRestorer::restorePrecision( IEngine &engine, DEBUG( { // Same dimensions - ASSERT( GlobalConfiguration::USE_COLUMN_MERGING_EQUATIONS || - tableau.getN() == targetN ); - ASSERT( GlobalConfiguration::USE_COLUMN_MERGING_EQUATIONS || - tableau.getM() == targetM ); + ASSERT( GlobalConfiguration::USE_COLUMN_MERGING_EQUATIONS || tableau.getN() == targetN ); + ASSERT( GlobalConfiguration::USE_COLUMN_MERGING_EQUATIONS || tableau.getM() == targetM ); // Constraints should be in the same state before and after restoration for ( const auto &pair : targetEngineState._plConstraintToState ) @@ -178,13 +172,11 @@ void PrecisionRestorer::restorePrecision( IEngine &engine, // Only active constraints need to be synchronized ASSERT( !pair.second->isActive() || pair.second->phaseFixed() == pair.first->phaseFixed() ); - ASSERT( pair.second->constraintObsolete() == - pair.first->constraintObsolete() ); + ASSERT( pair.second->constraintObsolete() == pair.first->constraintObsolete() ); } EngineState currentEngineState; - engine.storeState( currentEngineState, - TableauStateStorageLevel::STORE_NONE ); + engine.storeState( currentEngineState, TableauStateStorageLevel::STORE_NONE ); ASSERT( currentEngineState._numPlConstraintsDisabledByValidSplits == targetEngineState._numPlConstraintsDisabledByValidSplits ); @@ -192,4 +184,3 @@ void PrecisionRestorer::restorePrecision( IEngine &engine, tableau.verifyInvariants(); } ); } - diff --git a/src/engine/Preprocessor.cpp b/src/engine/Preprocessor.cpp index bd3b85878e..74fc719869 100644 --- a/src/engine/Preprocessor.cpp +++ b/src/engine/Preprocessor.cpp @@ -13,16 +13,17 @@ **/ +#include "Preprocessor.h" + #include "Debug.h" -#include "Options.h" #include "FloatUtils.h" #include "InfeasibleQueryException.h" #include "InputQuery.h" #include "MStringf.h" #include "Map.h" -#include "PiecewiseLinearFunctionType.h" -#include "Preprocessor.h" #include "MarabouError.h" +#include "Options.h" +#include "PiecewiseLinearFunctionType.h" #include "Statistics.h" #include "Tightening.h" @@ -57,7 +58,8 @@ void Preprocessor::freeMemoryIfNeeded() } } -std::unique_ptr Preprocessor::preprocess( const InputQuery &query, bool attemptVariableElimination ) +std::unique_ptr Preprocessor::preprocess( const InputQuery &query, + bool attemptVariableElimination ) { _preprocessed = std::unique_ptr( new InputQuery( query ) ); @@ -89,8 +91,8 @@ std::unique_ptr Preprocessor::preprocess( const InputQuery &query, b { unsigned oldNumberOfVariables = _preprocessed->getNumberOfVariables(); _preprocessed->_networkLevelReasoner->mergeConsecutiveWSLayers(); - _preprocessed = std::unique_ptr - ( new InputQuery( _preprocessed->_networkLevelReasoner->generateInputQuery() ) ); + _preprocessed = std::unique_ptr( + new InputQuery( _preprocessed->_networkLevelReasoner->generateInputQuery() ) ); _preprocessed->setNumberOfVariables( oldNumberOfVariables ); } } @@ -106,7 +108,8 @@ std::unique_ptr Preprocessor::preprocess( const InputQuery &query, b if ( !constraint->supportVariableElimination() ) for ( const auto &var : constraint->getParticipatingVariables() ) _uneliminableVariables.insert( var ); - for ( const auto &constraint : _preprocessed->getNonlinearConstraints() ) { + for ( const auto &constraint : _preprocessed->getNonlinearConstraints() ) + { if ( !constraint->supportVariableElimination() ) for ( const auto &var : constraint->getParticipatingVariables() ) _uneliminableVariables.insert( var ); @@ -140,20 +143,20 @@ std::unique_ptr Preprocessor::preprocess( const InputQuery &query, b */ unsigned tighteningRound = 0; bool continueTightening = true; - while ( continueTightening && tighteningRound++ < GlobalConfiguration::PREPROCESSSING_MAX_TIGHTEING_ROUND ) + while ( continueTightening && + tighteningRound++ < GlobalConfiguration::PREPROCESSSING_MAX_TIGHTEING_ROUND ) { - DEBUG({ - for ( const auto &equation : _preprocessed->getEquations() ) - ASSERT( !equation.containsRedundantAddends() ); - }); + DEBUG( { + for ( const auto &equation : _preprocessed->getEquations() ) + ASSERT( !equation.containsRedundantAddends() ); + } ); continueTightening = processEquations(); continueTightening = processConstraints() || continueTightening; if ( attemptVariableElimination ) continueTightening = processIdenticalVariables() || continueTightening; if ( _statistics ) - _statistics-> - incUnsignedAttribute( Statistics::PP_NUM_TIGHTENING_ITERATIONS ); + _statistics->incUnsignedAttribute( Statistics::PP_NUM_TIGHTENING_ITERATIONS ); } collectFixedValues(); @@ -172,10 +175,8 @@ std::unique_ptr Preprocessor::preprocess( const InputQuery &query, b _preprocessed->setUpperBound( i, getUpperBound( i ) ); } - ASSERT( _preprocessed->getLowerBounds().size() == - _preprocessed->getNumberOfVariables() ); - ASSERT( _preprocessed->getUpperBounds().size() == - _preprocessed->getNumberOfVariables() ); + ASSERT( _preprocessed->getLowerBounds().size() == _preprocessed->getNumberOfVariables() ); + ASSERT( _preprocessed->getUpperBounds().size() == _preprocessed->getNumberOfVariables() ); return std::move( _preprocessed ); } @@ -203,11 +204,11 @@ void Preprocessor::separateMergedAndFixed() _fixedVariables[merged.first] = merged.second; } - DEBUG({ - // After this operation, the merged and fixed variable sets are disjoint - for ( const auto &fixed : _fixedVariables ) - ASSERT( !_mergedVariables.exists( fixed.first ) ); - }); + DEBUG( { + // After this operation, the merged and fixed variable sets are disjoint + for ( const auto &fixed : _fixedVariables ) + ASSERT( !_mergedVariables.exists( fixed.first ) ); + } ); } void Preprocessor::transformConstraintsIfNeeded() @@ -372,29 +373,21 @@ bool Preprocessor::processEquations() */ if ( ciSign[xi] == NEGATIVE ) { - validLb = - ( ( type == Equation::LE ) || ( type == Equation::EQ ) ) - && - ( excludedFromLB.empty() || - ( excludedFromLB.size() == 1 && excludedFromLB.exists( xi ) ) ); - validUb = - ( ( type == Equation::GE ) || ( type == Equation::EQ ) ) - && - ( excludedFromUB.empty() || - ( excludedFromUB.size() == 1 && excludedFromUB.exists( xi ) ) ); + validLb = ( ( type == Equation::LE ) || ( type == Equation::EQ ) ) && + ( excludedFromLB.empty() || + ( excludedFromLB.size() == 1 && excludedFromLB.exists( xi ) ) ); + validUb = ( ( type == Equation::GE ) || ( type == Equation::EQ ) ) && + ( excludedFromUB.empty() || + ( excludedFromUB.size() == 1 && excludedFromUB.exists( xi ) ) ); } else { - validLb = - ( ( type == Equation::GE ) || ( type == Equation::EQ ) ) - && - ( excludedFromUB.empty() || - ( excludedFromUB.size() == 1 && excludedFromUB.exists( xi ) ) ); - validUb = - ( ( type == Equation::LE ) || ( type == Equation::EQ ) ) - && - ( excludedFromLB.empty() || - ( excludedFromLB.size() == 1 && excludedFromLB.exists( xi ) ) ); + validLb = ( ( type == Equation::GE ) || ( type == Equation::EQ ) ) && + ( excludedFromUB.empty() || + ( excludedFromUB.size() == 1 && excludedFromUB.exists( xi ) ) ); + validUb = ( ( type == Equation::LE ) || ( type == Equation::EQ ) ) && + ( excludedFromLB.empty() || + ( excludedFromLB.size() == 1 && excludedFromLB.exists( xi ) ) ); } // Now compute the actual bounds and see if they are tighter @@ -417,11 +410,7 @@ bool Preprocessor::processEquations() lowerBound /= -ci; - if ( - FloatUtils::gt( - lowerBound, getLowerBound( xi ), epsilon - ) - ) + if ( FloatUtils::gt( lowerBound, getLowerBound( xi ), epsilon ) ) { tighterBoundFound = true; setLowerBound( xi, lowerBound ); @@ -445,11 +434,7 @@ bool Preprocessor::processEquations() upperBound /= -ci; - if ( - FloatUtils::lt( - upperBound, getUpperBound( xi ), epsilon - ) - ) + if ( FloatUtils::lt( upperBound, getUpperBound( xi ), epsilon ) ) { tighterBoundFound = true; setUpperBound( xi, upperBound ); @@ -484,7 +469,8 @@ bool Preprocessor::processEquations() double lb = getLowerBound( var ); double ub = getUpperBound( var ); - if ( FloatUtils::areEqual( lb, ub, GlobalConfiguration::PREPROCESSOR_ALMOST_FIXED_THRESHOLD ) ) + if ( FloatUtils::areEqual( + lb, ub, GlobalConfiguration::PREPROCESSOR_ALMOST_FIXED_THRESHOLD ) ) setUpperBound( var, getLowerBound( var ) ); else allFixed = false; @@ -500,7 +486,10 @@ bool Preprocessor::processEquations() for ( const auto &addend : equation->_addends ) sum += addend._coefficient * getLowerBound( addend._variable ); - if ( FloatUtils::areDisequal( sum, equation->_scalar, GlobalConfiguration::PREPROCESSOR_ALMOST_FIXED_THRESHOLD ) ) + if ( FloatUtils::areDisequal( + sum, + equation->_scalar, + GlobalConfiguration::PREPROCESSOR_ALMOST_FIXED_THRESHOLD ) ) { throw InfeasibleQueryException(); } @@ -536,7 +525,8 @@ bool Preprocessor::processConstraints() } else if ( ( tightening._type == Tightening::UB ) && - ( FloatUtils::lt( tightening._value, getUpperBound( tightening._variable ) ) ) ) + ( FloatUtils::lt( tightening._value, + getUpperBound( tightening._variable ) ) ) ) { tighterBoundFound = true; setUpperBound( tightening._variable, tightening._value ); @@ -545,8 +535,7 @@ bool Preprocessor::processConstraints() if ( FloatUtils::areEqual( getLowerBound( tightening._variable ), getUpperBound( tightening._variable ), GlobalConfiguration::PREPROCESSOR_ALMOST_FIXED_THRESHOLD ) ) - setUpperBound( tightening._variable, - getLowerBound( tightening._variable ) ); + setUpperBound( tightening._variable, getLowerBound( tightening._variable ) ); if ( FloatUtils::gt( getLowerBound( tightening._variable ), getUpperBound( tightening._variable ), @@ -578,7 +567,8 @@ bool Preprocessor::processConstraints() } else if ( ( tightening._type == Tightening::UB ) && - ( FloatUtils::lt( tightening._value, getUpperBound( tightening._variable ) ) ) ) + ( FloatUtils::lt( tightening._value, + getUpperBound( tightening._variable ) ) ) ) { tighterBoundFound = true; setUpperBound( tightening._variable, tightening._value ); @@ -587,8 +577,7 @@ bool Preprocessor::processConstraints() if ( FloatUtils::areEqual( getLowerBound( tightening._variable ), getUpperBound( tightening._variable ), GlobalConfiguration::PREPROCESSOR_ALMOST_FIXED_THRESHOLD ) ) - setUpperBound( tightening._variable, - getLowerBound( tightening._variable ) ); + setUpperBound( tightening._variable, getLowerBound( tightening._variable ) ); if ( FloatUtils::gt( getLowerBound( tightening._variable ), getUpperBound( tightening._variable ), @@ -634,8 +623,7 @@ bool Preprocessor::processIdenticalVariables() unsigned v2 = term2._variable; // Input and output variables should not be merged - if ( _uneliminableVariables.exists( v1 ) || - _uneliminableVariables.exists( v2 ) ) + if ( _uneliminableVariables.exists( v1 ) || _uneliminableVariables.exists( v2 ) ) { ++equation; continue; @@ -645,14 +633,10 @@ bool Preprocessor::processIdenticalVariables() found = true; double bestLowerBound = - getLowerBound( v1 ) > getLowerBound( v2 ) ? - getLowerBound( v1 ) : - getLowerBound( v2 ); + getLowerBound( v1 ) > getLowerBound( v2 ) ? getLowerBound( v1 ) : getLowerBound( v2 ); double bestUpperBound = - getUpperBound( v1 ) < getUpperBound( v2 ) ? - getUpperBound( v1 ) : - getUpperBound( v2 ); + getUpperBound( v1 ) < getUpperBound( v2 ) ? getUpperBound( v1 ) : getUpperBound( v2 ); equation = equations.erase( equation ); @@ -731,19 +715,19 @@ void Preprocessor::eliminateVariables() // If there's nothing to eliminate, we just eliminate obsolete constraints. if ( _fixedVariables.empty() && _mergedVariables.empty() ) { - List &constraints( _preprocessed->getPiecewiseLinearConstraints() ); + List &constraints( + _preprocessed->getPiecewiseLinearConstraints() ); List::iterator constraint = constraints.begin(); while ( constraint != constraints.end() ) { - if ( (*constraint)->constraintObsolete() ) + if ( ( *constraint )->constraintObsolete() ) { if ( _statistics ) - _statistics->incUnsignedAttribute - ( Statistics::PP_NUM_CONSTRAINTS_REMOVED ); + _statistics->incUnsignedAttribute( Statistics::PP_NUM_CONSTRAINTS_REMOVED ); if ( _preprocessed->_networkLevelReasoner ) - _preprocessed->_networkLevelReasoner-> - removeConstraintFromTopologicalOrder( *constraint ); + _preprocessed->_networkLevelReasoner->removeConstraintFromTopologicalOrder( + *constraint ); delete *constraint; *constraint = NULL; constraint = constraints.erase( constraint ); @@ -756,11 +740,10 @@ void Preprocessor::eliminateVariables() List::iterator nlConstraint = nlConstraints.begin(); while ( nlConstraint != nlConstraints.end() ) { - if ( (*nlConstraint)->constraintObsolete() ) + if ( ( *nlConstraint )->constraintObsolete() ) { if ( _statistics ) - _statistics->incUnsignedAttribute - ( Statistics::PP_NUM_CONSTRAINTS_REMOVED ); + _statistics->incUnsignedAttribute( Statistics::PP_NUM_CONSTRAINTS_REMOVED ); delete *nlConstraint; *nlConstraint = NULL; @@ -774,8 +757,7 @@ void Preprocessor::eliminateVariables() if ( _statistics ) _statistics->setUnsignedAttribute( Statistics::PP_NUM_ELIMINATED_VARS, - _fixedVariables.size() + - _mergedVariables.size() ); + _fixedVariables.size() + _mergedVariables.size() ); // Check and remove any fixed variables from the debugging solution for ( unsigned i = 0; i < _preprocessed->getNumberOfVariables(); ++i ) @@ -784,11 +766,12 @@ void Preprocessor::eliminateVariables() { if ( !FloatUtils::areEqual( _fixedVariables[i], _preprocessed->_debuggingSolution[i] ) ) throw MarabouError( MarabouError::DEBUGGING_ERROR, - Stringf( "Variable %u fixed to %.5lf, " - "contradicts possible solution %.5lf", - i, - _fixedVariables[i], - _preprocessed->_debuggingSolution[i] ).ascii() ); + Stringf( "Variable %u fixed to %.5lf, " + "contradicts possible solution %.5lf", + i, + _fixedVariables[i], + _preprocessed->_debuggingSolution[i] ) + .ascii() ); _preprocessed->_debuggingSolution.erase( i ); } @@ -804,16 +787,16 @@ void Preprocessor::eliminateVariables() if ( _preprocessed->_debuggingSolution.exists( newVar ) ) { - - if ( !FloatUtils::areEqual ( _preprocessed->_debuggingSolution[i], - _preprocessed->_debuggingSolution[newVar] ) ) + if ( !FloatUtils::areEqual( _preprocessed->_debuggingSolution[i], + _preprocessed->_debuggingSolution[newVar] ) ) throw MarabouError( MarabouError::DEBUGGING_ERROR, - Stringf( "Variable %u fixed to %.5lf, " - "merged into %u which was fixed to %.5lf", - i, - _preprocessed->_debuggingSolution[i], - newVar, - _preprocessed->_debuggingSolution[newVar] ).ascii() ); + Stringf( "Variable %u fixed to %.5lf, " + "merged into %u which was fixed to %.5lf", + i, + _preprocessed->_debuggingSolution[i], + newVar, + _preprocessed->_debuggingSolution[newVar] ) + .ascii() ); } else { @@ -886,8 +869,7 @@ void Preprocessor::eliminateVariables() if ( equation->_addends.empty() ) { if ( _statistics ) - _statistics->incUnsignedAttribute - ( Statistics::PP_NUM_EQUATIONS_REMOVED ); + _statistics->incUnsignedAttribute( Statistics::PP_NUM_EQUATIONS_REMOVED ); // No addends left, scalar should be 0 if ( !FloatUtils::isZero( equation->_scalar ) ) @@ -897,33 +879,34 @@ void Preprocessor::eliminateVariables() } else ++equation; - } + } // Let the piecewise-linear constraints know of any eliminated variables, and remove // the constraints themselves if they become obsolete. - List &constraints( _preprocessed->getPiecewiseLinearConstraints() ); + List &constraints( + _preprocessed->getPiecewiseLinearConstraints() ); List::iterator constraint = constraints.begin(); while ( constraint != constraints.end() ) { - List participatingVariables = (*constraint)->getParticipatingVariables(); + List participatingVariables = ( *constraint )->getParticipatingVariables(); for ( unsigned variable : participatingVariables ) { if ( _uneliminableVariables.exists( variable ) ) continue; - if ( (*constraint)->supportVariableElimination() && _fixedVariables.exists( variable ) ) - (*constraint)->eliminateVariable( variable, _fixedVariables.at( variable ) ); + if ( ( *constraint )->supportVariableElimination() && + _fixedVariables.exists( variable ) ) + ( *constraint )->eliminateVariable( variable, _fixedVariables.at( variable ) ); } - if ( (*constraint)->constraintObsolete() ) + if ( ( *constraint )->constraintObsolete() ) { if ( _statistics ) - _statistics->incUnsignedAttribute - ( Statistics::PP_NUM_CONSTRAINTS_REMOVED ); + _statistics->incUnsignedAttribute( Statistics::PP_NUM_CONSTRAINTS_REMOVED ); if ( _preprocessed->_networkLevelReasoner ) - _preprocessed->_networkLevelReasoner-> - removeConstraintFromTopologicalOrder( *constraint ); + _preprocessed->_networkLevelReasoner->removeConstraintFromTopologicalOrder( + *constraint ); delete *constraint; *constraint = NULL; constraint = constraints.erase( constraint ); @@ -949,23 +932,23 @@ void Preprocessor::eliminateVariables() List::iterator nlConstraint = nlConstraints.begin(); while ( nlConstraint != nlConstraints.end() ) { - List participatingVariables = (*nlConstraint)->getParticipatingVariables(); + List participatingVariables = ( *nlConstraint )->getParticipatingVariables(); for ( unsigned variable : participatingVariables ) { if ( _uneliminableVariables.exists( variable ) ) continue; - if ( (*nlConstraint)->supportVariableElimination() && _fixedVariables.exists( variable ) ) + if ( ( *nlConstraint )->supportVariableElimination() && + _fixedVariables.exists( variable ) ) { - (*nlConstraint)->eliminateVariable( variable, _fixedVariables.at( variable ) ); + ( *nlConstraint )->eliminateVariable( variable, _fixedVariables.at( variable ) ); } } - if ( (*nlConstraint)->constraintObsolete() ) + if ( ( *nlConstraint )->constraintObsolete() ) { if ( _statistics ) - _statistics->incUnsignedAttribute - ( Statistics::PP_NUM_CONSTRAINTS_REMOVED ); + _statistics->incUnsignedAttribute( Statistics::PP_NUM_CONSTRAINTS_REMOVED ); delete *nlConstraint; *nlConstraint = NULL; @@ -977,24 +960,25 @@ void Preprocessor::eliminateVariables() // Let the remaining nonlinear constraints know of any changes in indices. for ( const auto &nlConstraint : nlConstraints ) - { - List participatingVariables = nlConstraint->getParticipatingVariables(); + { + List participatingVariables = nlConstraint->getParticipatingVariables(); for ( unsigned variable : participatingVariables ) { if ( _oldIndexToNewIndex.at( variable ) != variable ) nlConstraint->updateVariableIndex( variable, _oldIndexToNewIndex.at( variable ) ); } - } + } // Let the NLR know of changes in indices and merged variables if ( _preprocessed->_networkLevelReasoner ) - _preprocessed->_networkLevelReasoner->updateVariableIndices( _oldIndexToNewIndex, _mergedVariables ); + _preprocessed->_networkLevelReasoner->updateVariableIndices( _oldIndexToNewIndex, + _mergedVariables ); // Update the lower/upper bound maps for ( unsigned i = 0; i < _preprocessed->getNumberOfVariables(); ++i ) { if ( ( _fixedVariables.exists( i ) || _mergedVariables.exists( i ) ) && - !_uneliminableVariables.exists( i ) ) + !_uneliminableVariables.exists( i ) ) continue; ASSERT( _oldIndexToNewIndex.at( i ) <= i ); diff --git a/src/engine/Preprocessor.h b/src/engine/Preprocessor.h index 1e3e158ff0..f1877f6ff5 100644 --- a/src/engine/Preprocessor.h +++ b/src/engine/Preprocessor.h @@ -33,7 +33,8 @@ class Preprocessor /* Main method of this class: preprocess the input query */ - std::unique_ptr preprocess( const InputQuery &query, bool attemptVariableElimination = true ); + std::unique_ptr preprocess( const InputQuery &query, + bool attemptVariableElimination = true ); /* Have the preprocessor start reporting statistics. @@ -58,7 +59,6 @@ class Preprocessor unsigned getNewIndex( unsigned oldIndex ) const; private: - void freeMemoryIfNeeded(); inline double getLowerBound( unsigned var ) diff --git a/src/engine/ProjectedSteepestEdge.cpp b/src/engine/ProjectedSteepestEdge.cpp index 237bd6a127..6bc71c7336 100644 --- a/src/engine/ProjectedSteepestEdge.cpp +++ b/src/engine/ProjectedSteepestEdge.cpp @@ -13,11 +13,12 @@ **/ +#include "ProjectedSteepestEdge.h" + #include "Debug.h" #include "FloatUtils.h" #include "ITableau.h" #include "MStringf.h" -#include "ProjectedSteepestEdge.h" #include "MarabouError.h" #include "Statistics.h" #include "TableauRow.h" @@ -74,7 +75,8 @@ void ProjectedSteepestEdgeRule::initialize( const ITableau &tableau ) _referenceSpace = new char[_n]; if ( !_referenceSpace ) - throw MarabouError( MarabouError::ALLOCATION_FAILED, "ProjectedSteepestEdgeRule::referenceSpace" ); + throw MarabouError( MarabouError::ALLOCATION_FAILED, + "ProjectedSteepestEdgeRule::referenceSpace" ); _gamma = new double[_n - _m]; if ( !_gamma ) @@ -93,7 +95,7 @@ void ProjectedSteepestEdgeRule::initialize( const ITableau &tableau ) void ProjectedSteepestEdgeRule::resetReferenceSpace( const ITableau &tableau ) { - memset( _referenceSpace, 0, _n * sizeof(char) ); + memset( _referenceSpace, 0, _n * sizeof( char ) ); for ( unsigned i = 0; i < _n - _m; ++i ) { @@ -105,8 +107,7 @@ void ProjectedSteepestEdgeRule::resetReferenceSpace( const ITableau &tableau ) _errorInGamma = 0.0; if ( _statistics ) - _statistics->incLongAttribute - ( Statistics::PSE_NUM_RESET_REFERENCE_SPACE ); + _statistics->incLongAttribute( Statistics::PSE_NUM_RESET_REFERENCE_SPACE ); } bool ProjectedSteepestEdgeRule::select( ITableau &tableau, @@ -156,8 +157,9 @@ bool ProjectedSteepestEdgeRule::select( ITableau &tableau, { unsigned contender = *it; gammaValue = _gamma[*it]; - double contenderValue = - ( gammaValue < DBL_EPSILON ) ? 0 : ( costFunction[*it] * costFunction[*it] ) / gammaValue; + double contenderValue = ( gammaValue < DBL_EPSILON ) + ? 0 + : ( costFunction[*it] * costFunction[*it] ) / gammaValue; if ( contenderValue > bestValue ) { @@ -201,7 +203,8 @@ void ProjectedSteepestEdgeRule::prePivotHook( const ITableau &tableau, bool fake // Update gamma[entering] to the accurate value, taking the pivot into account double accurateGamma; _errorInGamma = computeAccurateGamma( accurateGamma, tableau ); - _gamma[enteringIndex] = accurateGamma / ( changeColumn[leavingIndex] * changeColumn[leavingIndex] ); + _gamma[enteringIndex] = + accurateGamma / ( changeColumn[leavingIndex] * changeColumn[leavingIndex] ); unsigned m = tableau.getM(); unsigned n = tableau.getN(); @@ -252,7 +255,8 @@ void ProjectedSteepestEdgeRule::prePivotHook( const ITableau &tableau, bool fake PSE_LOG( "PrePivotHook done" ); } -double ProjectedSteepestEdgeRule::computeAccurateGamma( double &accurateGamma, const ITableau &tableau ) +double ProjectedSteepestEdgeRule::computeAccurateGamma( double &accurateGamma, + const ITableau &tableau ) { unsigned entering = tableau.getEnteringVariable(); unsigned enteringIndex = tableau.variableToIndex( entering ); @@ -295,7 +299,9 @@ void ProjectedSteepestEdgeRule::postPivotHook( const ITableau &tableau, bool fak // If the error is too great, reset the reference space. if ( _errorInGamma > GlobalConfiguration::PSE_GAMMA_ERROR_THRESHOLD ) { - PSE_LOG( Stringf( "PostPivotHook reseting ref space (degradation). Error = %.15lf", _errorInGamma ).ascii() ); + PSE_LOG( Stringf( "PostPivotHook reseting ref space (degradation). Error = %.15lf", + _errorInGamma ) + .ascii() ); resetReferenceSpace( tableau ); return; } diff --git a/src/engine/ProjectedSteepestEdge.h b/src/engine/ProjectedSteepestEdge.h index eaf27e8a23..2780f03d9b 100644 --- a/src/engine/ProjectedSteepestEdge.h +++ b/src/engine/ProjectedSteepestEdge.h @@ -19,7 +19,8 @@ #include "IProjectedSteepestEdge.h" #include "SparseUnsortedList.h" -#define PSE_LOG( x, ... ) LOG( GlobalConfiguration::PROJECTED_STEEPEST_EDGE_LOGGING, "Projected SE: %s\n", x ) +#define PSE_LOG( x, ... ) \ + LOG( GlobalConfiguration::PROJECTED_STEEPEST_EDGE_LOGGING, "Projected SE: %s\n", x ) class ProjectedSteepestEdgeRule : public IProjectedSteepestEdgeRule { @@ -35,9 +36,8 @@ class ProjectedSteepestEdgeRule : public IProjectedSteepestEdgeRule /* Apply the projected steepest edge pivot selection rule. */ - bool select( ITableau &tableau, - const List &candidates, - const Set &excluded ); + bool + select( ITableau &tableau, const List &candidates, const Set &excluded ); /* We use this hook to update gamma according to the entering diff --git a/src/engine/PseudoImpactTracker.cpp b/src/engine/PseudoImpactTracker.cpp index e9f57f9a13..81673e1475 100644 --- a/src/engine/PseudoImpactTracker.cpp +++ b/src/engine/PseudoImpactTracker.cpp @@ -13,20 +13,21 @@ **/ -#include "GlobalConfiguration.h" #include "PseudoImpactTracker.h" +#include "GlobalConfiguration.h" + PseudoImpactTracker::PseudoImpactTracker() -{} +{ +} -void PseudoImpactTracker::updateScore( PiecewiseLinearConstraint *constraint, - double score ) +void PseudoImpactTracker::updateScore( PiecewiseLinearConstraint *constraint, double score ) { ASSERT( _plConstraintToScore.exists( constraint ) ); double alpha = GlobalConfiguration::EXPONENTIAL_MOVING_AVERAGE_ALPHA; double oldScore = _plConstraintToScore[constraint]; - double newScore = ( 1 - alpha ) * oldScore + alpha * score; + double newScore = ( 1 - alpha ) * oldScore + alpha * score; ASSERT( _scores.find( ScoreEntry( constraint, oldScore ) ) != _scores.end() ); _scores.erase( ScoreEntry( constraint, oldScore ) ); diff --git a/src/engine/PseudoImpactTracker.h b/src/engine/PseudoImpactTracker.h index 7b67d34e4b..335576eb11 100644 --- a/src/engine/PseudoImpactTracker.h +++ b/src/engine/PseudoImpactTracker.h @@ -29,8 +29,7 @@ class PseudoImpactTracker : public PLConstraintScoreTracker /* New score is the moving average of the input score and the previous score. */ - virtual void updateScore( PiecewiseLinearConstraint *constraint, - double score ) override; + virtual void updateScore( PiecewiseLinearConstraint *constraint, double score ) override; }; #endif // __PseudoImpactTracker_h__ diff --git a/src/engine/QueryDivider.cpp b/src/engine/QueryDivider.cpp index 2571c18ffe..782a55bff1 100644 --- a/src/engine/QueryDivider.cpp +++ b/src/engine/QueryDivider.cpp @@ -23,7 +23,8 @@ void QueryDivider::bisectInputRegion( const InputRegion &inputRegion, InputRegion inputRegion2; double mid = ( inputRegion._lowerBounds[dimensionToBisect] + - inputRegion._upperBounds[dimensionToBisect] ) / 2; + inputRegion._upperBounds[dimensionToBisect] ) / + 2; inputRegion1 = inputRegion; inputRegion1._upperBounds[dimensionToBisect] = mid; diff --git a/src/engine/QueryDivider.h b/src/engine/QueryDivider.h index 3440858857..96aea0e703 100644 --- a/src/engine/QueryDivider.h +++ b/src/engine/QueryDivider.h @@ -29,7 +29,7 @@ class QueryDivider Map _upperBounds; }; - virtual ~QueryDivider() {}; + virtual ~QueryDivider(){}; /* Divide the previousSubquery into |numNewSubQueries| new subqueries and diff --git a/src/engine/ReluConstraint.cpp b/src/engine/ReluConstraint.cpp index 6be58f9d01..539db6c919 100644 --- a/src/engine/ReluConstraint.cpp +++ b/src/engine/ReluConstraint.cpp @@ -14,22 +14,22 @@ #include "ReluConstraint.h" -#include "PiecewiseLinearConstraint.h" #include "Debug.h" #include "DivideStrategy.h" #include "FloatUtils.h" #include "GlobalConfiguration.h" +#include "ITableau.h" #include "InfeasibleQueryException.h" #include "InputQuery.h" -#include "ITableau.h" #include "MStringf.h" #include "MarabouError.h" #include "PiecewiseLinearCaseSplit.h" +#include "PiecewiseLinearConstraint.h" #include "Statistics.h" #include "TableauRow.h" #ifdef _WIN32 -#define __attribute__(x) +#define __attribute__( x ) #endif ReluConstraint::ReluConstraint( unsigned b, unsigned f ) @@ -124,12 +124,12 @@ void ReluConstraint::unregisterAsWatcher( ITableau *tableau ) void ReluConstraint::checkIfLowerBoundUpdateFixesPhase( unsigned variable, double bound ) { - if ( variable == _f && FloatUtils::isPositive( bound ) ) - setPhaseStatus( RELU_PHASE_ACTIVE ); - else if ( variable == _b && !FloatUtils::isNegative( bound ) ) - setPhaseStatus( RELU_PHASE_ACTIVE ); - else if ( _auxVarInUse && variable == _aux && FloatUtils::isPositive( bound ) ) - setPhaseStatus( RELU_PHASE_INACTIVE ); + if ( variable == _f && FloatUtils::isPositive( bound ) ) + setPhaseStatus( RELU_PHASE_ACTIVE ); + else if ( variable == _b && !FloatUtils::isNegative( bound ) ) + setPhaseStatus( RELU_PHASE_ACTIVE ); + else if ( _auxVarInUse && variable == _aux && FloatUtils::isPositive( bound ) ) + setPhaseStatus( RELU_PHASE_INACTIVE ); } void ReluConstraint::checkIfUpperBoundUpdateFixesPhase( unsigned variable, double bound ) @@ -144,12 +144,12 @@ void ReluConstraint::checkIfUpperBoundUpdateFixesPhase( unsigned variable, doubl void ReluConstraint::notifyLowerBound( unsigned variable, double newBound ) { if ( _statistics ) - _statistics->incLongAttribute( - Statistics::NUM_BOUND_NOTIFICATIONS_TO_PL_CONSTRAINTS ); + _statistics->incLongAttribute( Statistics::NUM_BOUND_NOTIFICATIONS_TO_PL_CONSTRAINTS ); if ( _boundManager == nullptr ) { - if ( existsLowerBound( variable ) && !FloatUtils::gt( newBound, getLowerBound( variable ) ) ) + if ( existsLowerBound( variable ) && + !FloatUtils::gt( newBound, getLowerBound( variable ) ) ) return; setLowerBound( variable, newBound ); checkIfLowerBoundUpdateFixesPhase( variable, newBound ); @@ -172,13 +172,13 @@ void ReluConstraint::notifyLowerBound( unsigned variable, double newBound ) { // If we're in the active phase, aux should be 0 if ( proofs && _auxVarInUse ) - _boundManager->addLemmaExplanationAndTightenBound( _aux, 0, BoundType::UPPER, { variable }, - BoundType::LOWER, getType() ); + _boundManager->addLemmaExplanationAndTightenBound( + _aux, 0, BoundType::UPPER, { variable }, BoundType::LOWER, getType() ); else if ( !proofs && _auxVarInUse ) _boundManager->tightenUpperBound( _aux, 0 ); - // After updating to active phase - unsigned partner = ( variable == _f ) ? _b : _f; + // After updating to active phase + unsigned partner = ( variable == _f ) ? _b : _f; _boundManager->tightenLowerBound( partner, bound, *_tighteningRow ); } @@ -186,9 +186,9 @@ void ReluConstraint::notifyLowerBound( unsigned variable, double newBound ) else if ( _auxVarInUse && variable == _b && FloatUtils::isZero( bound ) ) { if ( proofs && _auxVarInUse ) - _boundManager->addLemmaExplanationAndTightenBound( _aux, 0, BoundType::UPPER, { variable }, - BoundType::LOWER, getType() ); - else if ( !proofs && _auxVarInUse ) + _boundManager->addLemmaExplanationAndTightenBound( + _aux, 0, BoundType::UPPER, { variable }, BoundType::LOWER, getType() ); + else if ( !proofs && _auxVarInUse ) _boundManager->tightenUpperBound( _aux, 0 ); } @@ -197,12 +197,12 @@ void ReluConstraint::notifyLowerBound( unsigned variable, double newBound ) else if ( _auxVarInUse && variable == _aux && bound > 0 ) { if ( proofs ) - _boundManager->addLemmaExplanationAndTightenBound( _f, 0, BoundType::UPPER, { variable }, - BoundType::LOWER, getType() ); + _boundManager->addLemmaExplanationAndTightenBound( + _f, 0, BoundType::UPPER, { variable }, BoundType::LOWER, getType() ); else _boundManager->tightenUpperBound( _f, 0 ); - // After updating to inactive phase + // After updating to inactive phase _boundManager->tightenUpperBound( _b, -bound, *_tighteningRow ); } @@ -215,8 +215,12 @@ void ReluConstraint::notifyLowerBound( unsigned variable, double newBound ) if ( _phaseStatus == RELU_PHASE_INACTIVE ) _boundManager->tightenUpperBound( _aux, -bound, *_tighteningRow ); else if ( _phaseStatus == PHASE_NOT_FIXED ) - _boundManager->addLemmaExplanationAndTightenBound( _aux, -bound, BoundType::UPPER, { variable }, - BoundType::LOWER, getType() ); + _boundManager->addLemmaExplanationAndTightenBound( _aux, + -bound, + BoundType::UPPER, + { variable }, + BoundType::LOWER, + getType() ); } else _boundManager->tightenUpperBound( _aux, -bound ); @@ -227,8 +231,8 @@ void ReluConstraint::notifyLowerBound( unsigned variable, double newBound ) else if ( bound < 0 && variable == _f ) { if ( proofs ) - _boundManager->addLemmaExplanationAndTightenBound( _f, 0, BoundType::LOWER, { variable }, - BoundType::LOWER, getType() ); + _boundManager->addLemmaExplanationAndTightenBound( + _f, 0, BoundType::LOWER, { variable }, BoundType::LOWER, getType() ); else _boundManager->tightenLowerBound( _f, 0 ); } @@ -272,8 +276,12 @@ void ReluConstraint::notifyUpperBound( unsigned variable, double newBound ) else { if ( FloatUtils::isZero( bound ) ) - _boundManager->addLemmaExplanationAndTightenBound( _b, 0, BoundType::UPPER, { variable }, - BoundType::UPPER, getType() ); + _boundManager->addLemmaExplanationAndTightenBound( _b, + 0, + BoundType::UPPER, + { variable }, + BoundType::UPPER, + getType() ); // Bound cannot be negative if ReLU is inactive else if ( FloatUtils::isNegative( bound ) ) throw InfeasibleQueryException(); @@ -281,7 +289,6 @@ void ReluConstraint::notifyUpperBound( unsigned variable, double newBound ) } else _boundManager->tightenUpperBound( _b, bound ); - } else if ( variable == _b ) { @@ -289,8 +296,8 @@ void ReluConstraint::notifyUpperBound( unsigned variable, double newBound ) { // If b has a non-positive upper bound, f's upper bound is 0 if ( proofs ) - _boundManager->addLemmaExplanationAndTightenBound( _f, 0, BoundType::UPPER, { variable }, - BoundType::UPPER, getType() ); + _boundManager->addLemmaExplanationAndTightenBound( + _f, 0, BoundType::UPPER, { variable }, BoundType::UPPER, getType() ); else _boundManager->tightenUpperBound( _f, 0 ); @@ -308,8 +315,12 @@ void ReluConstraint::notifyUpperBound( unsigned variable, double newBound ) if ( _phaseStatus == RELU_PHASE_ACTIVE ) _boundManager->tightenUpperBound( _f, bound, *_tighteningRow ); else if ( _phaseStatus == PHASE_NOT_FIXED ) - _boundManager->addLemmaExplanationAndTightenBound( _f, bound, BoundType::UPPER, { variable }, - BoundType::UPPER, getType() ); + _boundManager->addLemmaExplanationAndTightenBound( _f, + bound, + BoundType::UPPER, + { variable }, + BoundType::UPPER, + getType() ); } else _boundManager->tightenUpperBound( _f, bound ); @@ -317,21 +328,25 @@ void ReluConstraint::notifyUpperBound( unsigned variable, double newBound ) } else if ( _auxVarInUse && variable == _aux ) { - if ( proofs ) - { + if ( proofs ) + { if ( _phaseStatus != RELU_PHASE_ACTIVE ) _boundManager->tightenLowerBound( _b, -bound, *_tighteningRow ); else { if ( FloatUtils::isZero( bound ) ) - _boundManager->addLemmaExplanationAndTightenBound( _b, 0, BoundType::LOWER, { variable }, - BoundType::UPPER, getType() ); + _boundManager->addLemmaExplanationAndTightenBound( _b, + 0, + BoundType::LOWER, + { variable }, + BoundType::UPPER, + getType() ); // Bound cannot be negative if ReLU is active else if ( FloatUtils::isNegative( bound ) ) throw InfeasibleQueryException(); } - } - else + } + else _boundManager->tightenLowerBound( _b, -bound ); } } @@ -345,9 +360,7 @@ bool ReluConstraint::participatingVariable( unsigned variable ) const List ReluConstraint::getParticipatingVariables() const { - return _auxVarInUse? - List( { _b, _f, _aux } ) : - List( { _b, _f } ); + return _auxVarInUse ? List( { _b, _f, _aux } ) : List( { _b, _f } ); } bool ReluConstraint::satisfied() const @@ -362,7 +375,8 @@ bool ReluConstraint::satisfied() const return false; if ( FloatUtils::isPositive( fValue ) ) - return FloatUtils::areEqual( bValue, fValue, GlobalConfiguration::CONSTRAINT_COMPARISON_TOLERANCE ); + return FloatUtils::areEqual( + bValue, fValue, GlobalConfiguration::CONSTRAINT_COMPARISON_TOLERANCE ); else return !FloatUtils::isPositive( bValue ); } @@ -435,7 +449,8 @@ List ReluConstraint::getSmartFixes( ITableau *ta double bDeltaToFDelta; double fDeltaToBDelta; - bool linearlyDependent = tableau->areLinearlyDependent( _b, _f, bDeltaToFDelta, fDeltaToBDelta ); + bool linearlyDependent = + tableau->areLinearlyDependent( _b, _f, bDeltaToFDelta, fDeltaToBDelta ); /* If b and f are linearly independent, there's nothing clever to be done - @@ -526,7 +541,7 @@ List ReluConstraint::getSmartFixes( ITableau *ta if ( !fIsBasic ) { - double newBValue = bValue + fDeltaToBDelta * (-fValue); + double newBValue = bValue + fDeltaToBDelta * ( -fValue ); if ( newBValue <= 0 ) fixes.append( PiecewiseLinearConstraint::Fix( _f, 0 ) ); } @@ -681,25 +696,29 @@ PiecewiseLinearCaseSplit ReluConstraint::getValidCaseSplit() const void ReluConstraint::dump( String &output ) const { output = Stringf( "ReluConstraint: x%u = ReLU( x%u ). Active? %s. PhaseStatus = %u (%s).\n", - _f, _b, + _f, + _b, _constraintActive ? "Yes" : "No", - _phaseStatus, phaseToString( _phaseStatus ).ascii() - ); + _phaseStatus, + phaseToString( _phaseStatus ).ascii() ); - output += Stringf( "b in [%s, %s], ", - existsLowerBound( _b ) ? Stringf( "%lf", getLowerBound( _b ) ).ascii() : "-inf", - existsUpperBound( _b ) ? Stringf( "%lf", getUpperBound( _b ) ).ascii() : "inf" ); + output += + Stringf( "b in [%s, %s], ", + existsLowerBound( _b ) ? Stringf( "%lf", getLowerBound( _b ) ).ascii() : "-inf", + existsUpperBound( _b ) ? Stringf( "%lf", getUpperBound( _b ) ).ascii() : "inf" ); - output += Stringf( "f in [%s, %s]", - existsLowerBound( _f ) ? Stringf( "%lf", getLowerBound( _f ) ).ascii() : "-inf", - existsUpperBound( _f ) ? Stringf( "%lf", getUpperBound( _f ) ).ascii() : "inf" ); + output += + Stringf( "f in [%s, %s]", + existsLowerBound( _f ) ? Stringf( "%lf", getLowerBound( _f ) ).ascii() : "-inf", + existsUpperBound( _f ) ? Stringf( "%lf", getUpperBound( _f ) ).ascii() : "inf" ); if ( _auxVarInUse ) { - output += Stringf( ". Aux var: %u. Range: [%s, %s]\n", - _aux, - existsLowerBound( _aux ) ? Stringf( "%lf", getLowerBound( _aux ) ).ascii() : "-inf", - existsUpperBound( _aux ) ? Stringf( "%lf", getUpperBound( _aux ) ).ascii() : "inf" ); + output += Stringf( + ". Aux var: %u. Range: [%s, %s]\n", + _aux, + existsLowerBound( _aux ) ? Stringf( "%lf", getLowerBound( _aux ) ).ascii() : "-inf", + existsUpperBound( _aux ) ? Stringf( "%lf", getUpperBound( _aux ) ).ascii() : "inf" ); } } @@ -710,8 +729,7 @@ void ReluConstraint::updateVariableIndex( unsigned oldIndex, unsigned newIndex ) ASSERT( _gurobi == NULL ); ASSERT( oldIndex == _b || oldIndex == _f || ( _auxVarInUse && oldIndex == _aux ) ); - ASSERT( !_lowerBounds.exists( newIndex ) && - !_upperBounds.exists( newIndex ) && + ASSERT( !_lowerBounds.exists( newIndex ) && !_upperBounds.exists( newIndex ) && newIndex != _b && newIndex != _f && ( !_auxVarInUse || newIndex != _aux ) ); if ( _lowerBounds.exists( oldIndex ) ) @@ -734,37 +752,37 @@ void ReluConstraint::updateVariableIndex( unsigned oldIndex, unsigned newIndex ) _aux = newIndex; } -void ReluConstraint::eliminateVariable( __attribute__((unused)) unsigned variable, - __attribute__((unused)) double fixedValue ) +void ReluConstraint::eliminateVariable( __attribute__( ( unused ) ) unsigned variable, + __attribute__( ( unused ) ) double fixedValue ) { ASSERT( variable == _b || variable == _f || ( _auxVarInUse && variable == _aux ) ); - DEBUG({ - if ( variable == _f ) + DEBUG( { + if ( variable == _f ) + { + ASSERT( FloatUtils::gte( fixedValue, 0.0 ) ); + } + + if ( variable == _f || variable == _b ) + { + if ( FloatUtils::gt( fixedValue, 0 ) ) { - ASSERT( FloatUtils::gte( fixedValue, 0.0 ) ); + ASSERT( _phaseStatus != RELU_PHASE_INACTIVE ); } - - if ( variable == _f || variable == _b ) + else if ( FloatUtils::lt( fixedValue, 0 ) ) { - if ( FloatUtils::gt( fixedValue, 0 ) ) - { - ASSERT( _phaseStatus != RELU_PHASE_INACTIVE ); - } - else if ( FloatUtils::lt( fixedValue, 0 ) ) - { - ASSERT( _phaseStatus != RELU_PHASE_ACTIVE ); - } + ASSERT( _phaseStatus != RELU_PHASE_ACTIVE ); } - else + } + else + { + // This is the aux variable + if ( FloatUtils::isPositive( fixedValue ) ) { - // This is the aux variable - if ( FloatUtils::isPositive( fixedValue ) ) - { - ASSERT( _phaseStatus != RELU_PHASE_ACTIVE ); - } + ASSERT( _phaseStatus != RELU_PHASE_ACTIVE ); } - }); + } + } ); // In a ReLU constraint, if a variable is removed the entire constraint can be discarded. _haveEliminatedVariables = true; @@ -777,8 +795,8 @@ bool ReluConstraint::constraintObsolete() const void ReluConstraint::getEntailedTightenings( List &tightenings ) const { - ASSERT( existsLowerBound( _b ) && existsLowerBound( _f ) && - existsUpperBound( _b ) && existsUpperBound( _f ) ); + ASSERT( existsLowerBound( _b ) && existsLowerBound( _f ) && existsUpperBound( _b ) && + existsUpperBound( _f ) ); ASSERT( !_auxVarInUse || ( existsLowerBound( _aux ) && existsUpperBound( _aux ) ) ); @@ -798,8 +816,7 @@ void ReluConstraint::getEntailedTightenings( List &tightenings ) con } // Determine if we are in the active phase, inactive phase or unknown phase - if ( !FloatUtils::isNegative( bLowerBound ) || - FloatUtils::isPositive( fLowerBound ) || + if ( !FloatUtils::isNegative( bLowerBound ) || FloatUtils::isPositive( fLowerBound ) || ( _auxVarInUse && FloatUtils::isZero( auxUpperBound ) ) ) { // Active case; @@ -821,8 +838,7 @@ void ReluConstraint::getEntailedTightenings( List &tightenings ) con tightenings.append( Tightening( _b, 0, Tightening::LB ) ); tightenings.append( Tightening( _f, 0, Tightening::LB ) ); } - else if ( FloatUtils::isNegative( bUpperBound ) || - FloatUtils::isZero( fUpperBound ) || + else if ( FloatUtils::isNegative( bUpperBound ) || FloatUtils::isZero( fUpperBound ) || ( _auxVarInUse && FloatUtils::isPositive( auxLowerBound ) ) ) { // Inactive case @@ -923,19 +939,17 @@ void ReluConstraint::transformToUseAuxVariables( InputQuery &inputQuery ) // Generally, aux.ub = -b.lb. However, if b.lb is positive (active // phase), then aux.ub needs to be 0 - double auxUpperBound = - bLowerBounds > 0 ? 0 : -bLowerBounds; + double auxUpperBound = bLowerBounds > 0 ? 0 : -bLowerBounds; inputQuery.setUpperBound( _aux, auxUpperBound ); // We now care about the auxiliary variable, as well _auxVarInUse = true; } -void ReluConstraint::getCostFunctionComponent( LinearExpression &cost, - PhaseStatus phase ) const +void ReluConstraint::getCostFunctionComponent( LinearExpression &cost, PhaseStatus phase ) const { // If the constraint is not active or is fixed, it contributes nothing - if( !isActive() || phaseFixed() ) + if ( !isActive() || phaseFixed() ) return; // This should not be called when the linear constraints have @@ -966,12 +980,11 @@ void ReluConstraint::getCostFunctionComponent( LinearExpression &cost, } } -PhaseStatus ReluConstraint::getPhaseStatusInAssignment( const Map - &assignment ) const +PhaseStatus +ReluConstraint::getPhaseStatusInAssignment( const Map &assignment ) const { ASSERT( assignment.exists( _b ) ); - return FloatUtils::isNegative( assignment[_b] ) ? - RELU_PHASE_INACTIVE : RELU_PHASE_ACTIVE; + return FloatUtils::isNegative( assignment[_b] ) ? RELU_PHASE_INACTIVE : RELU_PHASE_ACTIVE; } bool ReluConstraint::haveOutOfBoundVariables() const @@ -979,12 +992,16 @@ bool ReluConstraint::haveOutOfBoundVariables() const double bValue = getAssignment( _b ); double fValue = getAssignment( _f ); - if ( FloatUtils::gt( getLowerBound( _b ), bValue, GlobalConfiguration::CONSTRAINT_COMPARISON_TOLERANCE ) - || FloatUtils::lt( getUpperBound( _b ), bValue, GlobalConfiguration::CONSTRAINT_COMPARISON_TOLERANCE ) ) + if ( FloatUtils::gt( + getLowerBound( _b ), bValue, GlobalConfiguration::CONSTRAINT_COMPARISON_TOLERANCE ) || + FloatUtils::lt( + getUpperBound( _b ), bValue, GlobalConfiguration::CONSTRAINT_COMPARISON_TOLERANCE ) ) return true; - if ( FloatUtils::gt( getLowerBound( _f ), fValue, GlobalConfiguration::CONSTRAINT_COMPARISON_TOLERANCE ) - || FloatUtils::lt( getUpperBound( _f ), fValue, GlobalConfiguration::CONSTRAINT_COMPARISON_TOLERANCE ) ) + if ( FloatUtils::gt( + getLowerBound( _f ), fValue, GlobalConfiguration::CONSTRAINT_COMPARISON_TOLERANCE ) || + FloatUtils::lt( + getUpperBound( _f ), fValue, GlobalConfiguration::CONSTRAINT_COMPARISON_TOLERANCE ) ) return true; return false; @@ -1028,8 +1045,10 @@ double ReluConstraint::computePolarity() const { double currentLb = getLowerBound( _b ); double currentUb = getUpperBound( _b ); - if ( currentLb >= 0 ) return 1; - if ( currentUb <= 0 ) return -1; + if ( currentLb >= 0 ) + return 1; + if ( currentUb <= 0 ) + return -1; double width = currentUb - currentLb; double sum = currentUb + currentLb; return sum / width; @@ -1053,13 +1072,14 @@ void ReluConstraint::updateScoreBasedOnPolarity() void ReluConstraint::createTighteningRow() { // Create the row only when needed and when not already created - if ( !_boundManager->getBoundExplainer() || _tighteningRow || !_auxVarInUse || _tableauAuxVars.empty() ) + if ( !_boundManager->getBoundExplainer() || _tighteningRow || !_auxVarInUse || + _tableauAuxVars.empty() ) return; - _tighteningRow = std::unique_ptr( new TableauRow ( 3 ) ); + _tighteningRow = std::unique_ptr( new TableauRow( 3 ) ); // f = b + aux + counterpart (an additional aux variable of tableau) - _tighteningRow->_lhs = _f; + _tighteningRow->_lhs = _f; _tighteningRow->_row[0] = TableauRow::Entry( _b, 1 ); _tighteningRow->_row[1] = TableauRow::Entry( _aux, 1 ); _tighteningRow->_row[2] = TableauRow::Entry( _tableauAuxVars.back(), 1 ); diff --git a/src/engine/ReluConstraint.h b/src/engine/ReluConstraint.h index 925d75fa83..958cba79b3 100644 --- a/src/engine/ReluConstraint.h +++ b/src/engine/ReluConstraint.h @@ -193,8 +193,8 @@ class ReluConstraint : public PiecewiseLinearConstraint Return the phase status corresponding to the values of the *input* variables in the given assignment. */ - virtual PhaseStatus getPhaseStatusInAssignment( const Map - &assignment ) const override; + virtual PhaseStatus + getPhaseStatusInAssignment( const Map &assignment ) const override; /* Returns string with shape: relu, _f, _b @@ -240,6 +240,7 @@ class ReluConstraint : public PiecewiseLinearConstraint void updateScoreBasedOnPolarity() override; const List getNativeAuxVars() const override; + private: unsigned _b, _f; bool _auxVarInUse; diff --git a/src/engine/RoundConstraint.cpp b/src/engine/RoundConstraint.cpp index d00b5abbed..9a35e797a4 100644 --- a/src/engine/RoundConstraint.cpp +++ b/src/engine/RoundConstraint.cpp @@ -142,8 +142,7 @@ List RoundConstraint::getParticipatingVariables() const return List( { _b, _f } ); } -void RoundConstraint::addAuxiliaryEquationsAfterPreprocessing( InputQuery - &inputQuery ) +void RoundConstraint::addAuxiliaryEquationsAfterPreprocessing( InputQuery &inputQuery ) { // Since at this point we can only encode equality, // we encode the following: diff --git a/src/engine/RoundConstraint.h b/src/engine/RoundConstraint.h index abdd694262..2ce06559d2 100644 --- a/src/engine/RoundConstraint.h +++ b/src/engine/RoundConstraint.h @@ -72,8 +72,7 @@ class RoundConstraint : public NonlinearConstraint /* Encoding the convex relaxation of the round constraint */ - void addAuxiliaryEquationsAfterPreprocessing( InputQuery - &inputQuery ) override; + void addAuxiliaryEquationsAfterPreprocessing( InputQuery &inputQuery ) override; /* Preprocessing related functions, to inform that a variable has diff --git a/src/engine/RowBoundTightener.cpp b/src/engine/RowBoundTightener.cpp index 48000ee642..0eae855e68 100644 --- a/src/engine/RowBoundTightener.cpp +++ b/src/engine/RowBoundTightener.cpp @@ -13,10 +13,11 @@ **/ +#include "RowBoundTightener.h" + #include "Debug.h" #include "InfeasibleQueryException.h" #include "MarabouError.h" -#include "RowBoundTightener.h" #include "SparseUnsortedList.h" #include "Statistics.h" @@ -138,8 +139,8 @@ void RowBoundTightener::examineImplicitInvertedBasisMatrix( bool untilSaturation // The tightening procedure may throw an exception, in which case we need // to release the rows. unsigned newBoundsLearned; - unsigned maxNumberOfIterations = untilSaturation ? - GlobalConfiguration::ROW_BOUND_TIGHTENER_SATURATION_ITERATIONS : 1; + unsigned maxNumberOfIterations = + untilSaturation ? GlobalConfiguration::ROW_BOUND_TIGHTENER_SATURATION_ITERATIONS : 1; do { newBoundsLearned = onePassOverInvertedBasisRows(); @@ -188,7 +189,7 @@ void RowBoundTightener::examineInvertedBasisMatrix( bool untilSaturation ) row->_row[j]._coefficient = 0; for ( const auto &entry : *column ) - row->_row[j]._coefficient -= invB[i*_m + entry._index] * entry._value; + row->_row[j]._coefficient -= invB[i * _m + entry._index] * entry._value; } // Store the lhs variable @@ -200,16 +201,15 @@ void RowBoundTightener::examineInvertedBasisMatrix( bool untilSaturation ) // to release the rows. unsigned newBoundsLearned; - unsigned maxNumberOfIterations = untilSaturation ? - GlobalConfiguration::ROW_BOUND_TIGHTENER_SATURATION_ITERATIONS : 1; + unsigned maxNumberOfIterations = + untilSaturation ? GlobalConfiguration::ROW_BOUND_TIGHTENER_SATURATION_ITERATIONS : 1; do { newBoundsLearned = onePassOverInvertedBasisRows(); if ( _statistics && ( newBoundsLearned > 0 ) ) - _statistics-> - incLongAttribute( Statistics::NUM_TIGHTENINGS_FROM_EXPLICIT_BASIS, - newBoundsLearned ); + _statistics->incLongAttribute( Statistics::NUM_TIGHTENINGS_FROM_EXPLICIT_BASIS, + newBoundsLearned ); --maxNumberOfIterations; } @@ -236,7 +236,7 @@ unsigned RowBoundTightener::onePassOverInvertedBasisRows() unsigned RowBoundTightener::tightenOnSingleInvertedBasisRow( const TableauRow &row ) { - /* + /* A row is of the form y = sum ci xi + b @@ -296,11 +296,18 @@ unsigned RowBoundTightener::tightenOnSingleInvertedBasisRow( const TableauRow &r } } - result += registerTighterLowerBound( y, lowerBound - GlobalConfiguration::EXPLICIT_BASIS_BOUND_TIGHTENING_ROUNDING_CONSTANT, row ); - result += registerTighterUpperBound( y, upperBound + GlobalConfiguration::EXPLICIT_BASIS_BOUND_TIGHTENING_ROUNDING_CONSTANT, row ); + result += registerTighterLowerBound( + y, + lowerBound - GlobalConfiguration::EXPLICIT_BASIS_BOUND_TIGHTENING_ROUNDING_CONSTANT, + row ); + result += registerTighterUpperBound( + y, + upperBound + GlobalConfiguration::EXPLICIT_BASIS_BOUND_TIGHTENING_ROUNDING_CONSTANT, + row ); if ( FloatUtils::gt( getLowerBound( y ), getUpperBound( y ) ) ) { - ASSERT( FloatUtils::gt( _boundManager.getLowerBound( y ), _boundManager.getUpperBound( y ) ) ); + ASSERT( + FloatUtils::gt( _boundManager.getLowerBound( y ), _boundManager.getUpperBound( y ) ) ); throw InfeasibleQueryException(); } @@ -341,7 +348,9 @@ unsigned RowBoundTightener::tightenOnSingleInvertedBasisRow( const TableauRow &r for ( unsigned i = 0; i < n - m; ++i ) { // If ci = 0, nothing to do. - if ( _ciSign[i] == ZERO || FloatUtils::lt( abs( row[i] ), GlobalConfiguration::MINIMAL_COEFFICIENT_FOR_TIGHTENING ) ) + if ( _ciSign[i] == ZERO || + FloatUtils::lt( abs( row[i] ), + GlobalConfiguration::MINIMAL_COEFFICIENT_FOR_TIGHTENING ) ) continue; lowerBound = auxLb; @@ -373,11 +382,18 @@ unsigned RowBoundTightener::tightenOnSingleInvertedBasisRow( const TableauRow &r // If a tighter bound is found, store it xi = row._row[i]._var; - result += registerTighterLowerBound( xi, lowerBound - GlobalConfiguration::EXPLICIT_BASIS_BOUND_TIGHTENING_ROUNDING_CONSTANT, row ); - result += registerTighterUpperBound( xi, upperBound + GlobalConfiguration::EXPLICIT_BASIS_BOUND_TIGHTENING_ROUNDING_CONSTANT, row ); + result += registerTighterLowerBound( + xi, + lowerBound - GlobalConfiguration::EXPLICIT_BASIS_BOUND_TIGHTENING_ROUNDING_CONSTANT, + row ); + result += registerTighterUpperBound( + xi, + upperBound + GlobalConfiguration::EXPLICIT_BASIS_BOUND_TIGHTENING_ROUNDING_CONSTANT, + row ); if ( FloatUtils::gt( getLowerBound( xi ), getUpperBound( xi ) ) ) { - ASSERT( FloatUtils::gt( _boundManager.getLowerBound( xi ), _boundManager.getUpperBound( xi ) ) ); + ASSERT( FloatUtils::gt( _boundManager.getLowerBound( xi ), + _boundManager.getUpperBound( xi ) ) ); throw InfeasibleQueryException(); } } @@ -393,16 +409,15 @@ void RowBoundTightener::examineConstraintMatrix( bool untilSaturation ) If working until saturation, do single passes over the matrix until no new bounds are learned. Otherwise, just do a single pass. */ - unsigned maxNumberOfIterations = untilSaturation ? - GlobalConfiguration::ROW_BOUND_TIGHTENER_SATURATION_ITERATIONS : 1; + unsigned maxNumberOfIterations = + untilSaturation ? GlobalConfiguration::ROW_BOUND_TIGHTENER_SATURATION_ITERATIONS : 1; do { newBoundsLearned = onePassOverConstraintMatrix(); if ( _statistics && ( newBoundsLearned > 0 ) ) - _statistics-> - incLongAttribute( Statistics::NUM_TIGHTENINGS_FROM_CONSTRAINT_MATRIX, - newBoundsLearned ); + _statistics->incLongAttribute( Statistics::NUM_TIGHTENINGS_FROM_CONSTRAINT_MATRIX, + newBoundsLearned ); --maxNumberOfIterations; } @@ -550,15 +565,14 @@ unsigned RowBoundTightener::tightenOnSingleConstraintRow( unsigned row ) void RowBoundTightener::examinePivotRow() { - if ( _statistics ) + if ( _statistics ) _statistics->incLongAttribute( Statistics::NUM_ROWS_EXAMINED_BY_ROW_TIGHTENER ); const TableauRow &row( *_tableau.getPivotRow() ); unsigned newBoundsLearned = tightenOnSingleInvertedBasisRow( row ); if ( _statistics && ( newBoundsLearned > 0 ) ) - _statistics->incLongAttribute( Statistics::NUM_TIGHTENINGS_FROM_ROWS, - newBoundsLearned ); + _statistics->incLongAttribute( Statistics::NUM_TIGHTENINGS_FROM_ROWS, newBoundsLearned ); } void RowBoundTightener::getRowTightenings( List &tightenings ) const diff --git a/src/engine/RowBoundTightener.h b/src/engine/RowBoundTightener.h index 961a9207f2..dc665fe1fb 100644 --- a/src/engine/RowBoundTightener.h +++ b/src/engine/RowBoundTightener.h @@ -16,8 +16,8 @@ #ifndef __RowBoundTightener_h__ #define __RowBoundTightener_h__ -#include "IBoundManager.h" #include "Equation.h" +#include "IBoundManager.h" #include "IRowBoundTightener.h" #include "ITableau.h" #include "Queue.h" @@ -40,7 +40,7 @@ class RowBoundTightener : public IRowBoundTightener */ inline double getLowerBound( unsigned var ) const { - return _lowerBounds[var];// _boundManager.getLowerBound( var ); + return _lowerBounds[var]; // _boundManager.getLowerBound( var ); } /* @@ -48,7 +48,7 @@ class RowBoundTightener : public IRowBoundTightener */ inline double getUpperBound( unsigned var ) const { - return _upperBounds[var];//_boundManager.getUpperBound( var ); + return _upperBounds[var]; //_boundManager.getUpperBound( var ); } /* @@ -56,43 +56,55 @@ class RowBoundTightener : public IRowBoundTightener */ inline unsigned registerTighterLowerBound( unsigned variable, double newLowerBound ) { - unsigned tighteningsToAdd = _boundManager.tightenLowerBound( variable, newLowerBound ) ? 1u : 0u; + unsigned tighteningsToAdd = + _boundManager.tightenLowerBound( variable, newLowerBound ) ? 1u : 0u; return tighteningsToAdd; } inline unsigned registerTighterUpperBound( unsigned variable, double newUpperBound ) { - unsigned tighteningsToAdd = _boundManager.tightenUpperBound( variable, newUpperBound ) ? 1u : 0u; + unsigned tighteningsToAdd = + _boundManager.tightenUpperBound( variable, newUpperBound ) ? 1u : 0u; return tighteningsToAdd; } /* Register a new tighter bound with an explanation generated by a row */ - inline unsigned registerTighterLowerBound( unsigned variable, double newLowerBound, const TableauRow &row ) + inline unsigned + registerTighterLowerBound( unsigned variable, double newLowerBound, const TableauRow &row ) { - unsigned tighteningsToAdd = _boundManager.tightenLowerBound( variable, newLowerBound, row ) ? 1u : 0u; + unsigned tighteningsToAdd = + _boundManager.tightenLowerBound( variable, newLowerBound, row ) ? 1u : 0u; return tighteningsToAdd; } - inline unsigned registerTighterUpperBound( unsigned variable, double newUpperBound, const TableauRow &row ) + inline unsigned + registerTighterUpperBound( unsigned variable, double newUpperBound, const TableauRow &row ) { - unsigned tighteningsToAdd = _boundManager.tightenUpperBound( variable, newUpperBound, row ) ? 1u : 0u; + unsigned tighteningsToAdd = + _boundManager.tightenUpperBound( variable, newUpperBound, row ) ? 1u : 0u; return tighteningsToAdd; } /* Register a new tighter bound with an explanation generated by a row */ - inline unsigned registerTighterLowerBound( unsigned variable, double newLowerBound, const SparseUnsortedList &row ) + inline unsigned registerTighterLowerBound( unsigned variable, + double newLowerBound, + const SparseUnsortedList &row ) { - unsigned tighteningsToAdd = _boundManager.tightenLowerBound( variable, newLowerBound, row ) ? 1u : 0u; + unsigned tighteningsToAdd = + _boundManager.tightenLowerBound( variable, newLowerBound, row ) ? 1u : 0u; return tighteningsToAdd; } - inline unsigned registerTighterUpperBound( unsigned variable, double newUpperBound, const SparseUnsortedList &row ) + inline unsigned registerTighterUpperBound( unsigned variable, + double newUpperBound, + const SparseUnsortedList &row ) { - unsigned tighteningsToAdd = _boundManager.tightenUpperBound( variable, newUpperBound, row ) ? 1u : 0u; + unsigned tighteningsToAdd = + _boundManager.tightenUpperBound( variable, newUpperBound, row ) ? 1u : 0u; return tighteningsToAdd; } @@ -156,8 +168,8 @@ class RowBoundTightener : public IRowBoundTightener /* Direct pointers to _boundManager arrays to avoid multiple dereferencing. */ - const double * _lowerBounds; - const double * _upperBounds; + const double *_lowerBounds; + const double *_upperBounds; /* diff --git a/src/engine/SigmoidConstraint.cpp b/src/engine/SigmoidConstraint.cpp index fae4d15fff..009613d106 100644 --- a/src/engine/SigmoidConstraint.cpp +++ b/src/engine/SigmoidConstraint.cpp @@ -14,7 +14,6 @@ #include "SigmoidConstraint.h" -#include "NonlinearConstraint.h" #include "Debug.h" #include "DivideStrategy.h" #include "FloatUtils.h" @@ -23,11 +22,12 @@ #include "InputQuery.h" #include "MStringf.h" #include "MarabouError.h" +#include "NonlinearConstraint.h" #include "Statistics.h" #include "TableauRow.h" #ifdef _WIN32 -#define __attribute__(x) +#define __attribute__( x ) #endif SigmoidConstraint::SigmoidConstraint( unsigned b, unsigned f ) @@ -96,12 +96,11 @@ void SigmoidConstraint::notifyLowerBound( unsigned variable, double bound ) if ( tightenLowerBound( variable, bound ) ) { - if ( variable == _f && - !FloatUtils::areEqual( bound, 0 ) && + if ( variable == _f && !FloatUtils::areEqual( bound, 0 ) && !FloatUtils::areEqual( bound, 1 ) ) - tightenLowerBound( _b, sigmoidInverse( bound ) ); + tightenLowerBound( _b, sigmoidInverse( bound ) ); else if ( variable == _b ) - tightenLowerBound( _f, sigmoid( bound ) ); + tightenLowerBound( _f, sigmoid( bound ) ); } } @@ -115,8 +114,7 @@ void SigmoidConstraint::notifyUpperBound( unsigned variable, double bound ) if ( tightenUpperBound( variable, bound ) ) { - if ( variable == _f && - !FloatUtils::areEqual( bound, 0 ) && + if ( variable == _f && !FloatUtils::areEqual( bound, 0 ) && !FloatUtils::areEqual( bound, 1 ) ) tightenUpperBound( _b, sigmoidInverse( bound ) ); else if ( variable == _b ) @@ -138,20 +136,21 @@ void SigmoidConstraint::dump( String &output ) const { output = Stringf( "SigmoidConstraint: x%u = Sigmoid( x%u ).\n", _f, _b ); - output += Stringf( "b in [%s, %s], ", - existsLowerBound( _b ) ? Stringf( "%lf", getLowerBound( _b ) ).ascii() : "-inf", - existsUpperBound( _b ) ? Stringf( "%lf", getUpperBound( _b ) ).ascii() : "inf" ); + output += + Stringf( "b in [%s, %s], ", + existsLowerBound( _b ) ? Stringf( "%lf", getLowerBound( _b ) ).ascii() : "-inf", + existsUpperBound( _b ) ? Stringf( "%lf", getUpperBound( _b ) ).ascii() : "inf" ); - output += Stringf( "f in [%s, %s]", - existsLowerBound( _f ) ? Stringf( "%lf", getLowerBound( _f ) ).ascii() : "1", - existsUpperBound( _f ) ? Stringf( "%lf", getUpperBound( _f ) ).ascii() : "0" ); + output += + Stringf( "f in [%s, %s]", + existsLowerBound( _f ) ? Stringf( "%lf", getLowerBound( _f ) ).ascii() : "1", + existsUpperBound( _f ) ? Stringf( "%lf", getUpperBound( _f ) ).ascii() : "0" ); } void SigmoidConstraint::updateVariableIndex( unsigned oldIndex, unsigned newIndex ) { - ASSERT( oldIndex == _b || oldIndex == _f ); - ASSERT( !_lowerBounds.exists( newIndex ) && - !_upperBounds.exists( newIndex ) && + ASSERT( oldIndex == _b || oldIndex == _f ); + ASSERT( !_lowerBounds.exists( newIndex ) && !_upperBounds.exists( newIndex ) && newIndex != _b && newIndex != _f ); if ( _lowerBounds.exists( oldIndex ) ) @@ -172,8 +171,8 @@ void SigmoidConstraint::updateVariableIndex( unsigned oldIndex, unsigned newInde _f = newIndex; } -void SigmoidConstraint::eliminateVariable( __attribute__((unused)) unsigned variable, - __attribute__((unused)) double fixedValue ) +void SigmoidConstraint::eliminateVariable( __attribute__( ( unused ) ) unsigned variable, + __attribute__( ( unused ) ) double fixedValue ) { ASSERT( variable == _b || variable == _f ); @@ -188,8 +187,8 @@ bool SigmoidConstraint::constraintObsolete() const void SigmoidConstraint::getEntailedTightenings( List &tightenings ) const { - ASSERT( existsLowerBound( _b ) && existsLowerBound( _f ) && - existsUpperBound( _b ) && existsUpperBound( _f ) ); + ASSERT( existsLowerBound( _b ) && existsLowerBound( _f ) && existsUpperBound( _b ) && + existsUpperBound( _f ) ); double bLowerBound = getLowerBound( _b ); double fLowerBound = getLowerBound( _f ); @@ -211,7 +210,8 @@ bool SigmoidConstraint::satisfied() const double bValue = getAssignment( _b ); double fValue = getAssignment( _f ); - return FloatUtils::areEqual( sigmoid( bValue ), fValue, GlobalConfiguration::CONSTRAINT_COMPARISON_TOLERANCE ); + return FloatUtils::areEqual( + sigmoid( bValue ), fValue, GlobalConfiguration::CONSTRAINT_COMPARISON_TOLERANCE ); } String SigmoidConstraint::serializeToString() const @@ -231,22 +231,22 @@ unsigned SigmoidConstraint::getF() const double SigmoidConstraint::sigmoid( double x ) { - if ( x > GlobalConfiguration::SIGMOID_CUTOFF_CONSTANT ) - return 1 - GlobalConfiguration::DEFAULT_EPSILON_FOR_COMPARISONS; - else if ( x < -GlobalConfiguration::SIGMOID_CUTOFF_CONSTANT ) - return GlobalConfiguration::DEFAULT_EPSILON_FOR_COMPARISONS; - else - return 1 / ( 1 + std::exp( -x ) ); + if ( x > GlobalConfiguration::SIGMOID_CUTOFF_CONSTANT ) + return 1 - GlobalConfiguration::DEFAULT_EPSILON_FOR_COMPARISONS; + else if ( x < -GlobalConfiguration::SIGMOID_CUTOFF_CONSTANT ) + return GlobalConfiguration::DEFAULT_EPSILON_FOR_COMPARISONS; + else + return 1 / ( 1 + std::exp( -x ) ); } double SigmoidConstraint::sigmoidInverse( double y ) { - if ( FloatUtils::areEqual( y, 0 ) ) - return FloatUtils::negativeInfinity(); - else if ( FloatUtils::areEqual( y, 1 ) ) - return FloatUtils::infinity(); - else - return log( y / ( 1 - y ) ); + if ( FloatUtils::areEqual( y, 0 ) ) + return FloatUtils::negativeInfinity(); + else if ( FloatUtils::areEqual( y, 1 ) ) + return FloatUtils::infinity(); + else + return log( y / ( 1 - y ) ); } double SigmoidConstraint::sigmoidDerivative( double x ) diff --git a/src/engine/SigmoidConstraint.h b/src/engine/SigmoidConstraint.h index f8545af72a..c46bee4d2a 100644 --- a/src/engine/SigmoidConstraint.h +++ b/src/engine/SigmoidConstraint.h @@ -41,7 +41,7 @@ class SigmoidConstraint : public NonlinearConstraint /* Restore the state of this constraint from the given one. */ - void restoreState( const NonlinearConstraint *state ) override; + void restoreState( const NonlinearConstraint *state ) override; /* Register/unregister the constraint with a talbeau. @@ -77,7 +77,10 @@ class SigmoidConstraint : public NonlinearConstraint void updateVariableIndex( unsigned oldIndex, unsigned newIndex ) override; bool constraintObsolete() const override; - bool supportVariableElimination() const override { return true; }; + bool supportVariableElimination() const override + { + return true; + }; /* Get the tightenings entailed by the constraint. diff --git a/src/engine/SignConstraint.cpp b/src/engine/SignConstraint.cpp index 99cc340899..4ab8f6b7d9 100644 --- a/src/engine/SignConstraint.cpp +++ b/src/engine/SignConstraint.cpp @@ -17,9 +17,9 @@ #include "Debug.h" #include "FloatUtils.h" #include "GlobalConfiguration.h" +#include "ITableau.h" #include "InfeasibleQueryException.h" #include "InputQuery.h" -#include "ITableau.h" #include "MStringf.h" #include "MarabouError.h" #include "PiecewiseLinearCaseSplit.h" @@ -27,7 +27,7 @@ #include "Statistics.h" #ifdef _WIN32 -#define __attribute__(x) +#define __attribute__( x ) #endif SignConstraint::SignConstraint( unsigned b, unsigned f ) @@ -223,8 +223,7 @@ bool SignConstraint::phaseFixed() const return _phaseStatus != PHASE_NOT_FIXED; } -void SignConstraint::addAuxiliaryEquationsAfterPreprocessing( InputQuery - &inputQuery ) +void SignConstraint::addAuxiliaryEquationsAfterPreprocessing( InputQuery &inputQuery ) { /* If the phase is not fixed, add _f <= -2/lb_b * _b + 1 @@ -239,8 +238,7 @@ void SignConstraint::addAuxiliaryEquationsAfterPreprocessing( InputQuery double lowerBound = inputQuery.getLowerBound( _b ); double upperBound = inputQuery.getUpperBound( _b ); - ASSERT( FloatUtils::lt( lowerBound, 0 ) && - FloatUtils::gte( upperBound, 0 ) ); + ASSERT( FloatUtils::lt( lowerBound, 0 ) && FloatUtils::gte( upperBound, 0 ) ); // Create the aux variable unsigned auxUpper = inputQuery.getNumberOfVariables(); @@ -249,7 +247,7 @@ void SignConstraint::addAuxiliaryEquationsAfterPreprocessing( InputQuery // Create and add the equation Equation equation( Equation::EQ ); equation.addAddend( 1.0, _f ); - equation.addAddend( 2/lowerBound, _b ); + equation.addAddend( 2 / lowerBound, _b ); equation.addAddend( 1.0, auxUpper ); equation.setScalar( 1 ); inputQuery.addEquation( equation ); @@ -265,7 +263,7 @@ void SignConstraint::addAuxiliaryEquationsAfterPreprocessing( InputQuery // Create and add the equation Equation equation2( Equation::EQ ); equation2.addAddend( 1.0, _f ); - equation2.addAddend( -2/upperBound, _b ); + equation2.addAddend( -2 / upperBound, _b ); equation2.addAddend( 1.0, auxLower ); equation2.setScalar( -1 ); inputQuery.addEquation( equation2 ); @@ -302,11 +300,10 @@ String SignConstraint::serializeToString() const return Stringf( "sign,%u,%u", _f, _b ); } -void SignConstraint::getCostFunctionComponent( LinearExpression &cost, - PhaseStatus phase ) const +void SignConstraint::getCostFunctionComponent( LinearExpression &cost, PhaseStatus phase ) const { // If the constraint is not active or is fixed, it contributes nothing - if( !isActive() || phaseFixed() ) + if ( !isActive() || phaseFixed() ) return; ASSERT( phase == SIGN_PHASE_NEGATIVE || phase == SIGN_PHASE_POSITIVE ); @@ -335,13 +332,11 @@ void SignConstraint::getCostFunctionComponent( LinearExpression &cost, } } -PhaseStatus SignConstraint::getPhaseStatusInAssignment( const - Map - &assignment ) const +PhaseStatus +SignConstraint::getPhaseStatusInAssignment( const Map &assignment ) const { ASSERT( assignment.exists( _b ) ); - return FloatUtils::isNegative( assignment[_b] ) ? - SIGN_PHASE_NEGATIVE : SIGN_PHASE_POSITIVE; + return FloatUtils::isNegative( assignment[_b] ) ? SIGN_PHASE_NEGATIVE : SIGN_PHASE_POSITIVE; } bool SignConstraint::haveOutOfBoundVariables() const @@ -349,12 +344,16 @@ bool SignConstraint::haveOutOfBoundVariables() const double bValue = getAssignment( _b ); double fValue = getAssignment( _f ); - if ( FloatUtils::gt( getLowerBound( _b ), bValue, GlobalConfiguration::CONSTRAINT_COMPARISON_TOLERANCE ) - || FloatUtils::lt( getUpperBound( _b ), bValue, GlobalConfiguration::CONSTRAINT_COMPARISON_TOLERANCE ) ) + if ( FloatUtils::gt( + getLowerBound( _b ), bValue, GlobalConfiguration::CONSTRAINT_COMPARISON_TOLERANCE ) || + FloatUtils::lt( + getUpperBound( _b ), bValue, GlobalConfiguration::CONSTRAINT_COMPARISON_TOLERANCE ) ) return true; - if ( FloatUtils::gt( getLowerBound( _f ), fValue, GlobalConfiguration::CONSTRAINT_COMPARISON_TOLERANCE ) - || FloatUtils::lt( getUpperBound( _f ), fValue, GlobalConfiguration::CONSTRAINT_COMPARISON_TOLERANCE ) ) + if ( FloatUtils::gt( + getLowerBound( _f ), fValue, GlobalConfiguration::CONSTRAINT_COMPARISON_TOLERANCE ) || + FloatUtils::lt( + getUpperBound( _f ), fValue, GlobalConfiguration::CONSTRAINT_COMPARISON_TOLERANCE ) ) return true; return false; @@ -403,10 +402,10 @@ void SignConstraint::notifyLowerBound( unsigned variable, double bound ) if ( FloatUtils::gt( bound, 1 ) ) throw InfeasibleQueryException(); - _boundManager->addLemmaExplanationAndTightenBound( _f, 1, BoundType::LOWER, { variable }, - BoundType::LOWER, getType() ); - _boundManager->addLemmaExplanationAndTightenBound( _b, 0, BoundType::LOWER, { variable }, - BoundType::LOWER, getType() ); + _boundManager->addLemmaExplanationAndTightenBound( + _f, 1, BoundType::LOWER, { variable }, BoundType::LOWER, getType() ); + _boundManager->addLemmaExplanationAndTightenBound( + _b, 0, BoundType::LOWER, { variable }, BoundType::LOWER, getType() ); } else { @@ -421,8 +420,8 @@ void SignConstraint::notifyLowerBound( unsigned variable, double bound ) if ( _boundManager != nullptr ) { if ( _boundManager->shouldProduceProofs() ) - _boundManager->addLemmaExplanationAndTightenBound( _f, 1, BoundType::LOWER, { variable }, - BoundType::LOWER, getType() ); + _boundManager->addLemmaExplanationAndTightenBound( + _f, 1, BoundType::LOWER, { variable }, BoundType::LOWER, getType() ); else _boundManager->tightenLowerBound( _f, 1 ); } @@ -450,13 +449,13 @@ void SignConstraint::notifyUpperBound( unsigned variable, double bound ) if ( _boundManager->shouldProduceProofs() ) { // If ub of f is < -1, we have a contradiction - if ( FloatUtils::lt( bound, -1 ) ) + if ( FloatUtils::lt( bound, -1 ) ) throw InfeasibleQueryException(); - _boundManager->addLemmaExplanationAndTightenBound( _f, -1, BoundType::UPPER, { variable }, - BoundType::UPPER, getType() ); - _boundManager->addLemmaExplanationAndTightenBound( _b, 0, BoundType::UPPER, { variable }, - BoundType::UPPER, getType() ); + _boundManager->addLemmaExplanationAndTightenBound( + _f, -1, BoundType::UPPER, { variable }, BoundType::UPPER, getType() ); + _boundManager->addLemmaExplanationAndTightenBound( + _b, 0, BoundType::UPPER, { variable }, BoundType::UPPER, getType() ); } else { @@ -471,8 +470,8 @@ void SignConstraint::notifyUpperBound( unsigned variable, double bound ) if ( _boundManager != nullptr ) { if ( _boundManager->shouldProduceProofs() ) - _boundManager->addLemmaExplanationAndTightenBound( _f, -1, BoundType::UPPER, { variable }, - BoundType::UPPER, getType() ); + _boundManager->addLemmaExplanationAndTightenBound( + _f, -1, BoundType::UPPER, { variable }, BoundType::UPPER, getType() ); else _boundManager->tightenUpperBound( _f, -1 ); } @@ -503,8 +502,8 @@ List SignConstraint::getSmartFixes( ITableau * ) void SignConstraint::getEntailedTightenings( List &tightenings ) const { - ASSERT( existsLowerBound( _b ) && existsLowerBound( _f ) && - existsUpperBound( _b ) && existsUpperBound( _f ) ); + ASSERT( existsLowerBound( _b ) && existsLowerBound( _f ) && existsUpperBound( _b ) && + existsUpperBound( _f ) ); double bLowerBound = getLowerBound( _b ); double fLowerBound = getLowerBound( _f ); @@ -517,15 +516,13 @@ void SignConstraint::getEntailedTightenings( List &tightenings ) con tightenings.append( Tightening( _f, 1, Tightening::UB ) ); // Additional bounds can only be propagated if we are in the POSITIVE or NEGATIVE phases - if ( !FloatUtils::isNegative( bLowerBound ) || - FloatUtils::gt( fLowerBound, -1 ) ) + if ( !FloatUtils::isNegative( bLowerBound ) || FloatUtils::gt( fLowerBound, -1 ) ) { // Positive case tightenings.append( Tightening( _b, 0, Tightening::LB ) ); tightenings.append( Tightening( _f, 1, Tightening::LB ) ); } - else if ( FloatUtils::isNegative( bUpperBound ) || - FloatUtils::lt( fUpperBound, 1 ) ) + else if ( FloatUtils::isNegative( bUpperBound ) || FloatUtils::lt( fUpperBound, 1 ) ) { // Negative case tightenings.append( Tightening( _b, 0, Tightening::UB ) ); @@ -541,8 +538,7 @@ void SignConstraint::updateVariableIndex( unsigned oldIndex, unsigned newIndex ) ASSERT( oldIndex == _b || oldIndex == _f ); ASSERT( !_boundManager ); - ASSERT( !_lowerBounds.exists( newIndex ) && - !_upperBounds.exists( newIndex ) && + ASSERT( !_lowerBounds.exists( newIndex ) && !_upperBounds.exists( newIndex ) && newIndex != _b && newIndex != _f ); if ( existsLowerBound( oldIndex ) ) @@ -563,38 +559,38 @@ void SignConstraint::updateVariableIndex( unsigned oldIndex, unsigned newIndex ) _f = newIndex; } -void SignConstraint::eliminateVariable( __attribute__((unused)) unsigned variable, - __attribute__((unused)) double fixedValue ) +void SignConstraint::eliminateVariable( __attribute__( ( unused ) ) unsigned variable, + __attribute__( ( unused ) ) double fixedValue ) { ASSERT( variable == _b || variable == _f ); - DEBUG({ - if ( variable == _f ) - { - ASSERT( ( FloatUtils::areEqual( fixedValue, 1 ) ) || - ( FloatUtils::areEqual( fixedValue,-1 ) ) ); - - if ( FloatUtils::areEqual( fixedValue, 1 ) ) - { - ASSERT( _phaseStatus != SIGN_PHASE_NEGATIVE ); - } - else if (FloatUtils::areEqual( fixedValue, -1 ) ) - { - ASSERT( _phaseStatus != SIGN_PHASE_POSITIVE ); - } - } - else if ( variable == _b ) - { - if ( FloatUtils::gte( fixedValue, 0 ) ) - { - ASSERT( _phaseStatus != SIGN_PHASE_NEGATIVE ); - } - else if ( FloatUtils::lt( fixedValue, 0 ) ) - { - ASSERT( _phaseStatus != SIGN_PHASE_POSITIVE ); - } - } - }); + DEBUG( { + if ( variable == _f ) + { + ASSERT( ( FloatUtils::areEqual( fixedValue, 1 ) ) || + ( FloatUtils::areEqual( fixedValue, -1 ) ) ); + + if ( FloatUtils::areEqual( fixedValue, 1 ) ) + { + ASSERT( _phaseStatus != SIGN_PHASE_NEGATIVE ); + } + else if ( FloatUtils::areEqual( fixedValue, -1 ) ) + { + ASSERT( _phaseStatus != SIGN_PHASE_POSITIVE ); + } + } + else if ( variable == _b ) + { + if ( FloatUtils::gte( fixedValue, 0 ) ) + { + ASSERT( _phaseStatus != SIGN_PHASE_NEGATIVE ); + } + else if ( FloatUtils::lt( fixedValue, 0 ) ) + { + ASSERT( _phaseStatus != SIGN_PHASE_POSITIVE ); + } + } + } ); // In a Sign constraint, if a variable is removed the entire constraint can be discarded. _haveEliminatedVariables = true; @@ -613,26 +609,31 @@ unsigned SignConstraint::getF() const void SignConstraint::dump( String &output ) const { output = Stringf( "SignConstraint: x%u = Sign( x%u ). Active? %s. PhaseStatus = %u (%s). ", - _f, _b, + _f, + _b, _constraintActive ? "Yes" : "No", - _phaseStatus, phaseToString( _phaseStatus ).ascii() - ); + _phaseStatus, + phaseToString( _phaseStatus ).ascii() ); - output += Stringf( "b in [%s, %s], ", - existsLowerBound( _b ) ? Stringf( "%lf", getLowerBound( _b ) ).ascii() : "-inf", - existsUpperBound( _b ) ? Stringf( "%lf", getUpperBound( _b ) ).ascii() : "inf" ); + output += + Stringf( "b in [%s, %s], ", + existsLowerBound( _b ) ? Stringf( "%lf", getLowerBound( _b ) ).ascii() : "-inf", + existsUpperBound( _b ) ? Stringf( "%lf", getUpperBound( _b ) ).ascii() : "inf" ); - output += Stringf( "f in [%s, %s]\n", - existsLowerBound( _f ) ? Stringf( "%lf", getLowerBound( _f ) ).ascii() : "-inf", - existsUpperBound( _f ) ? Stringf( "%lf", getUpperBound( _f ) ).ascii() : "inf" ); + output += + Stringf( "f in [%s, %s]\n", + existsLowerBound( _f ) ? Stringf( "%lf", getLowerBound( _f ) ).ascii() : "-inf", + existsUpperBound( _f ) ? Stringf( "%lf", getUpperBound( _f ) ).ascii() : "inf" ); } double SignConstraint::computePolarity() const { double currentLb = getLowerBound( _b ); double currentUb = getUpperBound( _b ); - if ( !FloatUtils::isNegative( currentLb ) ) return 1; - if ( FloatUtils::isNegative( currentUb ) ) return -1; + if ( !FloatUtils::isNegative( currentLb ) ) + return 1; + if ( FloatUtils::isNegative( currentUb ) ) + return -1; double width = currentUb - currentLb; double sum = currentUb + currentLb; return sum / width; @@ -640,8 +641,8 @@ double SignConstraint::computePolarity() const void SignConstraint::updateDirection() { - _direction = ( FloatUtils::isNegative( computePolarity() ) ) ? - SIGN_PHASE_NEGATIVE : SIGN_PHASE_POSITIVE; + _direction = + ( FloatUtils::isNegative( computePolarity() ) ) ? SIGN_PHASE_NEGATIVE : SIGN_PHASE_POSITIVE; } PhaseStatus SignConstraint::getDirection() const @@ -660,6 +661,7 @@ bool SignConstraint::supportPolarity() const } // No aux vars in Sign constraint, so the function is suppressed -void SignConstraint::addTableauAuxVar( unsigned /* tableauAuxVar */, unsigned /* constraintAuxVar */ ) +void SignConstraint::addTableauAuxVar( unsigned /* tableauAuxVar */, + unsigned /* constraintAuxVar */ ) { } diff --git a/src/engine/SignConstraint.h b/src/engine/SignConstraint.h index 367f494f28..6023176bec 100644 --- a/src/engine/SignConstraint.h +++ b/src/engine/SignConstraint.h @@ -138,8 +138,7 @@ class SignConstraint : public PiecewiseLinearConstraint _f + 2/lb_b * _b + aux_ub = 1, 0 <= aux_ub <= 1 - lb_f - 2 * ub_b/lb_b _f - 2/ub_b * _b + aux2_lb = -1, -1 - ub_f + 2 * lb_b/ub_b <= aux_lb <= 0 */ - void addAuxiliaryEquationsAfterPreprocessing( InputQuery - &inputQuery ) override; + void addAuxiliaryEquationsAfterPreprocessing( InputQuery &inputQuery ) override; /* Preprocessing related functions, to inform that a variable has @@ -188,8 +187,8 @@ class SignConstraint : public PiecewiseLinearConstraint Return the phase status corresponding to the values of the *input* variables in the given assignment. */ - virtual PhaseStatus getPhaseStatusInAssignment( const Map - &assignment ) const override; + virtual PhaseStatus + getPhaseStatusInAssignment( const Map &assignment ) const override; /* Returns string with shape: sign, _f, _b diff --git a/src/engine/Simulator.cpp b/src/engine/Simulator.cpp index 097d5c8a56..75449ebc94 100644 --- a/src/engine/Simulator.cpp +++ b/src/engine/Simulator.cpp @@ -13,11 +13,12 @@ **/ +#include "Simulator.h" + #include "Debug.h" #include "FloatUtils.h" -#include "Preprocessor.h" #include "MarabouError.h" -#include "Simulator.h" +#include "Preprocessor.h" #ifdef _WIN32 #include @@ -29,7 +30,9 @@ void Simulator::runSimulations( const InputQuery &inputQuery, unsigned numberOfS runSimulations( inputQuery, numberOfSimulations, seed ); } -void Simulator::runSimulations( const InputQuery &inputQuery, unsigned numberOfSimulations, unsigned seed ) +void Simulator::runSimulations( const InputQuery &inputQuery, + unsigned numberOfSimulations, + unsigned seed ) { // Store the original query, so a fresh copy can be used in every simulation storeOriginalQuery( inputQuery ); @@ -59,10 +62,12 @@ void Simulator::storeOriginalQuery( const InputQuery &inputQuery ) _originalQuery = *( Preprocessor().preprocess( _originalQuery, false ) ); if ( _originalQuery.countInfiniteBounds() != 0 ) - throw MarabouError( MarabouError::SIMULATOR_ERROR, "Preprocessed query has infinite bounds" ); + throw MarabouError( MarabouError::SIMULATOR_ERROR, + "Preprocessed query has infinite bounds" ); if ( _originalQuery.getNumInputVariables() == 0 ) - throw MarabouError( MarabouError::SIMULATOR_ERROR, "Preprocessed query has no input variables" ); + throw MarabouError( MarabouError::SIMULATOR_ERROR, + "Preprocessed query has no input variables" ); } void Simulator::runSingleSimulation() @@ -75,7 +80,7 @@ void Simulator::runSingleSimulation() double lb = query.getLowerBound( input ); double ub = query.getUpperBound( input ); - double factor = ((double)rand()) / RAND_MAX; + double factor = ( (double)rand() ) / RAND_MAX; double value = lb + factor * ( ub - lb ); query.setLowerBound( input, value ); @@ -95,10 +100,10 @@ void Simulator::runSingleSimulation() // Make sure that a value has been calculated for every variable ASSERT( !preprocessor.variableIsMerged( i ) ); if ( !preprocessor.variableIsFixed( i ) ) - throw MarabouError( MarabouError::SIMULATOR_ERROR, "Could not calculate an exact assignment" ); + throw MarabouError( MarabouError::SIMULATOR_ERROR, + "Could not calculate an exact assignment" ); - ASSERT( FloatUtils::areEqual( query.getLowerBound( i ), - query.getUpperBound( i ) ) ); + ASSERT( FloatUtils::areEqual( query.getLowerBound( i ), query.getUpperBound( i ) ) ); result[i] = query.getLowerBound( i ); } diff --git a/src/engine/Simulator.h b/src/engine/Simulator.h index 03da460157..1bbca7b462 100644 --- a/src/engine/Simulator.h +++ b/src/engine/Simulator.h @@ -38,7 +38,8 @@ class Simulator passed for determinism; otherwise, time() will be used. */ void runSimulations( const InputQuery &inputQuery, unsigned numberOfSimulations ); - void runSimulations( const InputQuery &inputQuery, unsigned numberOfSimulations, unsigned seed ); + void + runSimulations( const InputQuery &inputQuery, unsigned numberOfSimulations, unsigned seed ); /* Obtain the results from previously-run simulations. diff --git a/src/engine/SmtCore.cpp b/src/engine/SmtCore.cpp index 49d818ad29..fe2977068c 100644 --- a/src/engine/SmtCore.cpp +++ b/src/engine/SmtCore.cpp @@ -13,6 +13,8 @@ **/ +#include "SmtCore.h" + #include "Debug.h" #include "DivideStrategy.h" #include "EngineState.h" @@ -24,7 +26,6 @@ #include "Options.h" #include "PseudoImpactTracker.h" #include "ReluConstraint.h" -#include "SmtCore.h" #include "UnsatCertificateNode.h" SmtCore::SmtCore( IEngine *engine ) @@ -34,7 +35,8 @@ SmtCore::SmtCore( IEngine *engine ) , _needToSplit( false ) , _constraintForSplitting( NULL ) , _stateId( 0 ) - , _constraintViolationThreshold( Options::get()->getInt( Options::CONSTRAINT_VIOLATION_THRESHOLD ) ) + , _constraintViolationThreshold( + Options::get()->getInt( Options::CONSTRAINT_VIOLATION_THRESHOLD ) ) , _deepSoIRejectionThreshold( Options::get()->getInt( Options::DEEP_SOI_REJECTION_THRESHOLD ) ) , _branchingHeuristic( Options::get()->getDivideStrategy() ) , _scoreTracker( nullptr ) @@ -78,8 +80,7 @@ void SmtCore::reportViolatedConstraint( PiecewiseLinearConstraint *constraint ) ++_constraintToViolationCount[constraint]; - if ( _constraintToViolationCount[constraint] >= - _constraintViolationThreshold ) + if ( _constraintToViolationCount[constraint] >= _constraintViolationThreshold ) { _needToSplit = true; if ( !pickSplitPLConstraint() ) @@ -97,14 +98,12 @@ unsigned SmtCore::getViolationCounts( PiecewiseLinearConstraint *constraint ) co return _constraintToViolationCount[constraint]; } -void SmtCore::initializeScoreTrackerIfNeeded( const - List - &plConstraints ) +void SmtCore::initializeScoreTrackerIfNeeded( + const List &plConstraints ) { if ( GlobalConfiguration::USE_DEEPSOI_LOCAL_SEARCH ) { - _scoreTracker = std::unique_ptr - ( new PseudoImpactTracker() ); + _scoreTracker = std::unique_ptr( new PseudoImpactTracker() ); _scoreTracker->initialize( plConstraints ); SMT_LOG( "\tTracking Pseudo Impact..." ); @@ -115,8 +114,7 @@ void SmtCore::reportRejectedPhasePatternProposal() { ++_numRejectedPhasePatternProposal; - if ( _numRejectedPhasePatternProposal >= - _deepSoIRejectionThreshold ) + if ( _numRejectedPhasePatternProposal >= _deepSoIRejectionThreshold ) { _needToSplit = true; _engine->applyAllBoundTightenings(); @@ -170,18 +168,17 @@ void SmtCore::performSplit() EngineState *stateBeforeSplits = new EngineState; stateBeforeSplits->_stateId = _stateId; ++_stateId; - _engine->storeState( *stateBeforeSplits, - TableauStateStorageLevel::STORE_BOUNDS_ONLY ); + _engine->storeState( *stateBeforeSplits, TableauStateStorageLevel::STORE_BOUNDS_ONLY ); _engine->preContextPushHook(); pushContext(); - UnsatCertificateNode* certificateNode = NULL; + UnsatCertificateNode *certificateNode = NULL; if ( _engine->shouldProduceProofs() && _engine->getUNSATCertificateRoot() ) { certificateNode = _engine->getUNSATCertificateCurrentPointer(); // Create children for UNSATCertificate current node, and assign a split to each of them ASSERT( certificateNode ); - for ( PiecewiseLinearCaseSplit& childSplit : splits ) + for ( PiecewiseLinearCaseSplit &childSplit : splits ) new UnsatCertificateNode( certificateNode, childSplit ); } @@ -192,7 +189,8 @@ void SmtCore::performSplit() if ( _engine->shouldProduceProofs() && _engine->getUNSATCertificateRoot() ) { - //Set the current node of the UNSAT certificate to be the child corresponding to the first split + // Set the current node of the UNSAT certificate to be the child corresponding to the first + // split UnsatCertificateNode *firstSplitChild = certificateNode->getChildBySplit( *split ); ASSERT( firstSplitChild ); _engine->setUNSATCertificateCurrentPointer( firstSplitChild ); @@ -216,14 +214,12 @@ void SmtCore::performSplit() if ( _statistics ) { unsigned level = getStackDepth(); - _statistics->setUnsignedAttribute( Statistics::CURRENT_DECISION_LEVEL, - level ); - if ( level > _statistics->getUnsignedAttribute - ( Statistics::MAX_DECISION_LEVEL ) ) - _statistics->setUnsignedAttribute( Statistics::MAX_DECISION_LEVEL, - level ); + _statistics->setUnsignedAttribute( Statistics::CURRENT_DECISION_LEVEL, level ); + if ( level > _statistics->getUnsignedAttribute( Statistics::MAX_DECISION_LEVEL ) ) + _statistics->setUnsignedAttribute( Statistics::MAX_DECISION_LEVEL, level ); struct timespec end = TimeUtils::sampleMicro(); - _statistics->incLongAttribute( Statistics::TOTAL_TIME_SMT_CORE_MICRO, TimeUtils::timePassed( start, end ) ); + _statistics->incLongAttribute( Statistics::TOTAL_TIME_SMT_CORE_MICRO, + TimeUtils::timePassed( start, end ) ); } _constraintForSplitting = NULL; @@ -231,7 +227,8 @@ void SmtCore::performSplit() unsigned SmtCore::getStackDepth() const { - ASSERT( ( _engine->inSnCMode() || _stack.size() == static_cast( _context.getLevel() ) ) ); + ASSERT( + ( _engine->inSnCMode() || _stack.size() == static_cast( _context.getLevel() ) ) ); return _stack.size(); } @@ -244,7 +241,8 @@ void SmtCore::popContext() if ( _statistics ) { _statistics->incUnsignedAttribute( Statistics::NUM_CONTEXT_POPS ); - _statistics->incLongAttribute( Statistics::TIME_CONTEXT_POP, TimeUtils::timePassed( start, end ) ); + _statistics->incLongAttribute( Statistics::TIME_CONTEXT_POP, + TimeUtils::timePassed( start, end ) ); } } @@ -257,7 +255,8 @@ void SmtCore::pushContext() if ( _statistics ) { _statistics->incUnsignedAttribute( Statistics::NUM_CONTEXT_PUSHES ); - _statistics->incLongAttribute( Statistics::TIME_CONTEXT_PUSH, TimeUtils::timePassed( start, end ) ); + _statistics->incLongAttribute( Statistics::TIME_CONTEXT_PUSH, + TimeUtils::timePassed( start, end ) ); } } @@ -299,7 +298,8 @@ bool SmtCore::popSplit() if ( _engine->shouldProduceProofs() && _engine->getUNSATCertificateCurrentPointer() ) { - UnsatCertificateNode *certificateNode = _engine->getUNSATCertificateCurrentPointer(); + UnsatCertificateNode *certificateNode = + _engine->getUNSATCertificateCurrentPointer(); _engine->setUNSATCertificateCurrentPointer( certificateNode->getParent() ); } @@ -330,7 +330,8 @@ bool SmtCore::popSplit() // popped stackEntry->_impliedValidSplits.clear(); - // Set the current node of the UNSAT certificate to be the child corresponding to the chosen split + // Set the current node of the UNSAT certificate to be the child corresponding to the chosen + // split if ( _engine->shouldProduceProofs() && _engine->getUNSATCertificateCurrentPointer() ) { UnsatCertificateNode *certificateNode = _engine->getUNSATCertificateCurrentPointer(); @@ -366,14 +367,12 @@ bool SmtCore::popSplit() if ( _statistics ) { unsigned level = getStackDepth(); - _statistics->setUnsignedAttribute( Statistics::CURRENT_DECISION_LEVEL, - level ); - if ( level > _statistics->getUnsignedAttribute - ( Statistics::MAX_DECISION_LEVEL ) ) - _statistics->setUnsignedAttribute( Statistics::MAX_DECISION_LEVEL, - level ); + _statistics->setUnsignedAttribute( Statistics::CURRENT_DECISION_LEVEL, level ); + if ( level > _statistics->getUnsignedAttribute( Statistics::MAX_DECISION_LEVEL ) ) + _statistics->setUnsignedAttribute( Statistics::MAX_DECISION_LEVEL, level ); struct timespec end = TimeUtils::sampleMicro(); - _statistics->incLongAttribute( Statistics::TOTAL_TIME_SMT_CORE_MICRO, TimeUtils::timePassed( start, end ) ); + _statistics->incLongAttribute( Statistics::TOTAL_TIME_SMT_CORE_MICRO, + TimeUtils::timePassed( start, end ) ); } checkSkewFromDebuggingSolution(); @@ -451,11 +450,13 @@ bool SmtCore::checkSkewFromDebuggingSolution() if ( stackEntry->_alternativeSplits.empty() ) { printf( "Error! Have a split that is non-compliant with the stored solution, " - "without alternatives:\n\t%s\n", error.ascii() ); + "without alternatives:\n\t%s\n", + error.ascii() ); throw MarabouError( MarabouError::DEBUGGING_ERROR ); } - // Active split is non-compliant but this is fine, because there are alternatives. We're done. + // Active split is non-compliant but this is fine, because there are alternatives. We're + // done. return false; } @@ -475,7 +476,8 @@ bool SmtCore::checkSkewFromDebuggingSolution() return true; } -bool SmtCore::splitAllowsStoredSolution( const PiecewiseLinearCaseSplit &split, String &error ) const +bool SmtCore::splitAllowsStoredSolution( const PiecewiseLinearCaseSplit &split, + String &error ) const { // False if the split prevents one of the values in the stored solution, true otherwise. error = ""; @@ -497,18 +499,20 @@ bool SmtCore::splitAllowsStoredSolution( const PiecewiseLinearCaseSplit &split, if ( ( bound._type == Tightening::LB ) && FloatUtils::gt( boundValue, solutionValue ) ) { - error = Stringf( "Variable %u: new LB is %.5lf, which contradicts possible solution %.5lf", - variable, - boundValue, - solutionValue ); + error = + Stringf( "Variable %u: new LB is %.5lf, which contradicts possible solution %.5lf", + variable, + boundValue, + solutionValue ); return false; } else if ( ( bound._type == Tightening::UB ) && FloatUtils::lt( boundValue, solutionValue ) ) { - error = Stringf( "Variable %u: new UB is %.5lf, which contradicts possible solution %.5lf", - variable, - boundValue, - solutionValue ); + error = + Stringf( "Variable %u: new UB is %.5lf, which contradicts possible solution %.5lf", + variable, + boundValue, + solutionValue ); return false; } } @@ -516,7 +520,8 @@ bool SmtCore::splitAllowsStoredSolution( const PiecewiseLinearCaseSplit &split, return true; } -PiecewiseLinearConstraint *SmtCore::chooseViolatedConstraintForFixing( List &_violatedPlConstraints ) const +PiecewiseLinearConstraint *SmtCore::chooseViolatedConstraintForFixing( + List &_violatedPlConstraints ) const { ASSERT( !_violatedPlConstraints.empty() ); @@ -563,8 +568,7 @@ void SmtCore::replaySmtStackEntry( SmtStackEntry *stackEntry ) EngineState *stateBeforeSplits = new EngineState; stateBeforeSplits->_stateId = _stateId; ++_stateId; - _engine->storeState( *stateBeforeSplits, - TableauStateStorageLevel::STORE_ENTIRE_TABLEAU_STATE ); + _engine->storeState( *stateBeforeSplits, TableauStateStorageLevel::STORE_ENTIRE_TABLEAU_STATE ); stackEntry->_engineState = stateBeforeSplits; // Apply all the splits @@ -577,14 +581,12 @@ void SmtCore::replaySmtStackEntry( SmtStackEntry *stackEntry ) if ( _statistics ) { unsigned level = getStackDepth(); - _statistics->setUnsignedAttribute( Statistics::CURRENT_DECISION_LEVEL, - level ); - if ( level > _statistics->getUnsignedAttribute - ( Statistics::MAX_DECISION_LEVEL ) ) - _statistics->setUnsignedAttribute( Statistics::MAX_DECISION_LEVEL, - level ); + _statistics->setUnsignedAttribute( Statistics::CURRENT_DECISION_LEVEL, level ); + if ( level > _statistics->getUnsignedAttribute( Statistics::MAX_DECISION_LEVEL ) ) + _statistics->setUnsignedAttribute( Statistics::MAX_DECISION_LEVEL, level ); struct timespec end = TimeUtils::sampleMicro(); - _statistics->incLongAttribute( Statistics::TOTAL_TIME_SMT_CORE_MICRO, TimeUtils::timePassed( start, end ) ); + _statistics->incLongAttribute( Statistics::TOTAL_TIME_SMT_CORE_MICRO, + TimeUtils::timePassed( start, end ) ); } } @@ -602,8 +604,7 @@ bool SmtCore::pickSplitPLConstraint() { if ( _needToSplit ) { - _constraintForSplitting = _engine->pickSplitPLConstraint - ( _branchingHeuristic ); + _constraintForSplitting = _engine->pickSplitPLConstraint( _branchingHeuristic ); } return _constraintForSplitting != NULL; } diff --git a/src/engine/SmtCore.h b/src/engine/SmtCore.h index db39ffa498..e5018ca2cc 100644 --- a/src/engine/SmtCore.h +++ b/src/engine/SmtCore.h @@ -17,12 +17,12 @@ #define __SmtCore_h__ #include "DivideStrategy.h" +#include "PLConstraintScoreTracker.h" #include "PiecewiseLinearCaseSplit.h" #include "PiecewiseLinearConstraint.h" -#include "PLConstraintScoreTracker.h" +#include "SmtStackEntry.h" #include "SmtState.h" #include "Stack.h" -#include "SmtStackEntry.h" #include "Statistics.h" #include "context/context.h" @@ -55,8 +55,7 @@ class SmtCore /* Initialize the score tracker with the given list of pl constraints. */ - void initializeScoreTrackerIfNeeded( const List - &plConstraints ); + void initializeScoreTrackerIfNeeded( const List &plConstraints ); /* Inform the SMT core that a SoI phase pattern proposal is rejected. @@ -66,8 +65,7 @@ class SmtCore /* Update the score of the constraint with the given score in the costTracker. */ - inline void updatePLConstraintScore( PiecewiseLinearConstraint *constraint, - double score ) + inline void updatePLConstraintScore( PiecewiseLinearConstraint *constraint, double score ) { ASSERT( _scoreTracker != nullptr ); _scoreTracker->updateScore( constraint, score ); @@ -90,7 +88,7 @@ class SmtCore Get the number of times a specific PL constraint has been reported as violated. */ - unsigned getViolationCounts( PiecewiseLinearConstraint* constraint ) const; + unsigned getViolationCounts( PiecewiseLinearConstraint *constraint ) const; /* Reset all reported violation counts and the number of rejected SoI @@ -151,7 +149,8 @@ class SmtCore Have the SMT core choose, among a set of violated PL constraints, which constraint should be repaired (without splitting) */ - PiecewiseLinearConstraint *chooseViolatedConstraintForFixing( List &_violatedPlConstraints ) const; + PiecewiseLinearConstraint *chooseViolatedConstraintForFixing( + List &_violatedPlConstraints ) const; inline void setBranchingHeuristics( DivideStrategy strategy ) { diff --git a/src/engine/SnCDivideStrategy.h b/src/engine/SnCDivideStrategy.h index 6308ae19c1..5966d78266 100644 --- a/src/engine/SnCDivideStrategy.h +++ b/src/engine/SnCDivideStrategy.h @@ -16,13 +16,12 @@ #ifndef __SnCDivideStrategy_h__ #define __SnCDivideStrategy_h__ -enum class SnCDivideStrategy -{ +enum class SnCDivideStrategy { // Input splitting LargestInterval = 0, // Relu splitting - Polarity, // Pick the ReLU with the polarity closest to 0 among the first K nodes + Polarity, // Pick the ReLU with the polarity closest to 0 among the first K nodes EarliestReLU, Auto diff --git a/src/engine/SoIInitializationStrategy.h b/src/engine/SoIInitializationStrategy.h index bdfb6d7fa2..57d2c7ef9e 100644 --- a/src/engine/SoIInitializationStrategy.h +++ b/src/engine/SoIInitializationStrategy.h @@ -16,8 +16,7 @@ #ifndef __SoIInitializationStrategy_h__ #define __SoIInitializationStrategy_h__ -enum class SoIInitializationStrategy -{ +enum class SoIInitializationStrategy { // When initialize the SoI function, add the cost term corresponding to the // activation pattern of the input assignment. INPUT_ASSIGNMENT, diff --git a/src/engine/SoISearchStrategy.h b/src/engine/SoISearchStrategy.h index cd0aa48dc6..942acc0529 100644 --- a/src/engine/SoISearchStrategy.h +++ b/src/engine/SoISearchStrategy.h @@ -16,8 +16,7 @@ #ifndef __SoISearchStrategy_h__ #define __SoISearchStrategy_h__ -enum class SoISearchStrategy -{ +enum class SoISearchStrategy { // Flip the SoI cost term of a random ReLU, // accept the change with certain probability MCMC, diff --git a/src/engine/SubQuery.h b/src/engine/SubQuery.h index fbfeab43b7..667bbfd9d4 100644 --- a/src/engine/SubQuery.h +++ b/src/engine/SubQuery.h @@ -39,8 +39,7 @@ struct SubQuery }; // Synchronized Queue containing the Sub-Queries shared by workers -typedef boost::lockfree::queue>WorkerQueue; +typedef boost::lockfree::queue> WorkerQueue; // A vector of Sub-Queries diff --git a/src/engine/SumOfInfeasibilitiesManager.cpp b/src/engine/SumOfInfeasibilitiesManager.cpp index 64e07da64d..a6a7e5a113 100644 --- a/src/engine/SumOfInfeasibilitiesManager.cpp +++ b/src/engine/SumOfInfeasibilitiesManager.cpp @@ -13,27 +13,26 @@ **/ +#include "SumOfInfeasibilitiesManager.h" + #include "FloatUtils.h" #include "MarabouError.h" #include "Options.h" -#include "SumOfInfeasibilitiesManager.h" - #include "Set.h" -SumOfInfeasibilitiesManager::SumOfInfeasibilitiesManager( const InputQuery - &inputQuery, - const ITableau - &tableau ) +SumOfInfeasibilitiesManager::SumOfInfeasibilitiesManager( const InputQuery &inputQuery, + const ITableau &tableau ) : _plConstraints( inputQuery.getPiecewiseLinearConstraints() ) , _networkLevelReasoner( inputQuery.getNetworkLevelReasoner() ) , _numberOfVariables( inputQuery.getNumberOfVariables() ) , _tableau( tableau ) , _initializationStrategy( Options::get()->getSoIInitializationStrategy() ) , _searchStrategy( Options::get()->getSoISearchStrategy() ) - , _probabilityDensityParameter( Options::get()->getFloat - ( Options::PROBABILITY_DENSITY_PARAMETER ) ) + , _probabilityDensityParameter( + Options::get()->getFloat( Options::PROBABILITY_DENSITY_PARAMETER ) ) , _statistics( NULL ) -{} +{ +} void SumOfInfeasibilitiesManager::resetPhasePattern() { @@ -54,9 +53,8 @@ LinearExpression SumOfInfeasibilitiesManager::getCurrentSoIPhasePattern() const if ( _statistics ) { struct timespec end = TimeUtils::sampleMicro(); - _statistics->incLongAttribute - ( Statistics::TOTAL_TIME_GETTING_SOI_PHASE_PATTERN_MICRO, - TimeUtils::timePassed( start, end ) ); + _statistics->incLongAttribute( Statistics::TOTAL_TIME_GETTING_SOI_PHASE_PATTERN_MICRO, + TimeUtils::timePassed( start, end ) ); } return cost; } @@ -72,9 +70,8 @@ LinearExpression SumOfInfeasibilitiesManager::getLastAcceptedSoIPhasePattern() c if ( _statistics ) { struct timespec end = TimeUtils::sampleMicro(); - _statistics->incLongAttribute - ( Statistics::TOTAL_TIME_GETTING_SOI_PHASE_PATTERN_MICRO, - TimeUtils::timePassed( start, end ) ); + _statistics->incLongAttribute( Statistics::TOTAL_TIME_GETTING_SOI_PHASE_PATTERN_MICRO, + TimeUtils::timePassed( start, end ) ); } return cost; } @@ -85,21 +82,19 @@ void SumOfInfeasibilitiesManager::initializePhasePattern() resetPhasePattern(); - if ( _initializationStrategy == SoIInitializationStrategy::INPUT_ASSIGNMENT - && _networkLevelReasoner ) + if ( _initializationStrategy == SoIInitializationStrategy::INPUT_ASSIGNMENT && + _networkLevelReasoner ) { initializePhasePatternWithCurrentInputAssignment(); } - else if ( _initializationStrategy - == SoIInitializationStrategy::CURRENT_ASSIGNMENT - || !_networkLevelReasoner ) + else if ( _initializationStrategy == SoIInitializationStrategy::CURRENT_ASSIGNMENT || + !_networkLevelReasoner ) { initializePhasePatternWithCurrentAssignment(); } else { - throw MarabouError - ( MarabouError::UNABLE_TO_INITIALIZATION_PHASE_PATTERN ); + throw MarabouError( MarabouError::UNABLE_TO_INITIALIZATION_PHASE_PATTERN ); } // Store constraints participating in the SoI @@ -112,9 +107,8 @@ void SumOfInfeasibilitiesManager::initializePhasePattern() if ( _statistics ) { struct timespec end = TimeUtils::sampleMicro(); - _statistics->incLongAttribute - ( Statistics::TOTAL_TIME_UPDATING_SOI_PHASE_PATTERN_MICRO, - TimeUtils::timePassed( start, end ) ); + _statistics->incLongAttribute( Statistics::TOTAL_TIME_UPDATING_SOI_PHASE_PATTERN_MICRO, + TimeUtils::timePassed( start, end ) ); } } @@ -133,8 +127,7 @@ void SumOfInfeasibilitiesManager::initializePhasePatternWithCurrentInputAssignme for ( const auto &plConstraint : _plConstraints ) { ASSERT( !_currentPhasePattern.exists( plConstraint ) ); - if ( plConstraint->supportSoI() && - plConstraint->isActive() && !plConstraint->phaseFixed() ) + if ( plConstraint->supportSoI() && plConstraint->isActive() && !plConstraint->phaseFixed() ) { // Set the phase status corresponding to the current assignment. _currentPhasePattern[plConstraint] = @@ -150,8 +143,7 @@ void SumOfInfeasibilitiesManager::initializePhasePatternWithCurrentAssignment() for ( const auto &plConstraint : _plConstraints ) { ASSERT( !_currentPhasePattern.exists( plConstraint ) ); - if ( plConstraint->supportSoI() && plConstraint->isActive() - && !plConstraint->phaseFixed() ) + if ( plConstraint->supportSoI() && plConstraint->isActive() && !plConstraint->phaseFixed() ) { // Set the phase status corresponding to the current assignment. _currentPhasePattern[plConstraint] = @@ -182,32 +174,26 @@ void SumOfInfeasibilitiesManager::proposePhasePatternUpdate() if ( _statistics ) { struct timespec end = TimeUtils::sampleMicro(); - _statistics->incLongAttribute - ( Statistics::NUM_PROPOSED_PHASE_PATTERN_UPDATE ); - _statistics->incLongAttribute - ( Statistics::TOTAL_TIME_UPDATING_SOI_PHASE_PATTERN_MICRO, - TimeUtils::timePassed( start, end ) ); + _statistics->incLongAttribute( Statistics::NUM_PROPOSED_PHASE_PATTERN_UPDATE ); + _statistics->incLongAttribute( Statistics::TOTAL_TIME_UPDATING_SOI_PHASE_PATTERN_MICRO, + TimeUtils::timePassed( start, end ) ); } } void SumOfInfeasibilitiesManager::proposePhasePatternUpdateRandomly() { SOI_LOG( "Proposing phase pattern update randomly..." ); - DEBUG({ - // _plConstraintsInCurrentPhasePattern should contain the same - // plConstraints in _currentPhasePattern - ASSERT( _plConstraintsInCurrentPhasePattern.size() == - _currentPhasePattern.size() ); - for ( const auto &pair : _currentPhasePattern ) - ASSERT( _plConstraintsInCurrentPhasePattern.exists - ( pair.first ) ); - }); + DEBUG( { + // _plConstraintsInCurrentPhasePattern should contain the same + // plConstraints in _currentPhasePattern + ASSERT( _plConstraintsInCurrentPhasePattern.size() == _currentPhasePattern.size() ); + for ( const auto &pair : _currentPhasePattern ) + ASSERT( _plConstraintsInCurrentPhasePattern.exists( pair.first ) ); + } ); // First, pick a pl constraint whose cost component we will update. - unsigned index = ( unsigned ) T::rand() % - _plConstraintsInCurrentPhasePattern.size(); - PiecewiseLinearConstraint *plConstraintToUpdate = - _plConstraintsInCurrentPhasePattern[index]; + unsigned index = (unsigned)T::rand() % _plConstraintsInCurrentPhasePattern.size(); + PiecewiseLinearConstraint *plConstraintToUpdate = _plConstraintsInCurrentPhasePattern[index]; // Next, pick an alternative phase. PhaseStatus currentPhase = _currentPhasePattern[plConstraintToUpdate]; @@ -221,7 +207,7 @@ void SumOfInfeasibilitiesManager::proposePhasePatternUpdateRandomly() else { auto it = allPhases.begin(); - unsigned index = ( unsigned ) T::rand() % allPhases.size(); + unsigned index = (unsigned)T::rand() % allPhases.size(); while ( index > 0 ) { ++it; @@ -269,8 +255,8 @@ void SumOfInfeasibilitiesManager::proposePhasePatternUpdateWalksat() SOI_LOG( "Proposing phase pattern update with Walksat-based strategy - done" ); } -bool SumOfInfeasibilitiesManager::decideToAcceptCurrentProposal -( double costOfCurrentPhasePattern, double costOfProposedPhasePattern ) +bool SumOfInfeasibilitiesManager::decideToAcceptCurrentProposal( double costOfCurrentPhasePattern, + double costOfProposedPhasePattern ) { if ( costOfProposedPhasePattern < costOfCurrentPhasePattern ) return true; @@ -279,9 +265,8 @@ bool SumOfInfeasibilitiesManager::decideToAcceptCurrentProposal // The smaller the difference between the proposed phase pattern and the // current phase pattern, the more likely to accept the proposal. double prob = exp( -_probabilityDensityParameter * - ( costOfProposedPhasePattern - - costOfCurrentPhasePattern ) ); - return ( (double) T::rand() / RAND_MAX ) < prob; + ( costOfProposedPhasePattern - costOfCurrentPhasePattern ) ); + return ( (double)T::rand() / RAND_MAX ) < prob; } } @@ -294,12 +279,10 @@ void SumOfInfeasibilitiesManager::acceptCurrentPhasePattern() if ( _statistics ) { - _statistics->incLongAttribute - ( Statistics::NUM_ACCEPTED_PHASE_PATTERN_UPDATE ); + _statistics->incLongAttribute( Statistics::NUM_ACCEPTED_PHASE_PATTERN_UPDATE ); struct timespec end = TimeUtils::sampleMicro(); - _statistics->incLongAttribute - ( Statistics::TOTAL_TIME_UPDATING_SOI_PHASE_PATTERN_MICRO, - TimeUtils::timePassed( start, end ) ); + _statistics->incLongAttribute( Statistics::TOTAL_TIME_UPDATING_SOI_PHASE_PATTERN_MICRO, + TimeUtils::timePassed( start, end ) ); } } @@ -317,8 +300,8 @@ void SumOfInfeasibilitiesManager::updateCurrentPhasePatternForSatisfiedPLConstra } } -void SumOfInfeasibilitiesManager::removeCostComponentFromHeuristicCost -( PiecewiseLinearConstraint *constraint ) +void SumOfInfeasibilitiesManager::removeCostComponentFromHeuristicCost( + PiecewiseLinearConstraint *constraint ) { if ( _currentPhasePattern.exists( constraint ) ) { @@ -340,9 +323,8 @@ void SumOfInfeasibilitiesManager::obtainCurrentAssignment() if ( _statistics ) { struct timespec end = TimeUtils::sampleMicro(); - _statistics->incLongAttribute - ( Statistics::TOTAL_TIME_OBTAIN_CURRENT_ASSIGNMENT_MICRO, - TimeUtils::timePassed( start, end ) ); + _statistics->incLongAttribute( Statistics::TOTAL_TIME_OBTAIN_CURRENT_ASSIGNMENT_MICRO, + TimeUtils::timePassed( start, end ) ); } } @@ -351,26 +333,27 @@ void SumOfInfeasibilitiesManager::setStatistics( Statistics *statistics ) _statistics = statistics; } -void SumOfInfeasibilitiesManager::setPhaseStatusInLastAcceptedPhasePattern -( PiecewiseLinearConstraint *constraint, PhaseStatus phase ) +void SumOfInfeasibilitiesManager::setPhaseStatusInLastAcceptedPhasePattern( + PiecewiseLinearConstraint *constraint, + PhaseStatus phase ) { ASSERT( _lastAcceptedPhasePattern.exists( constraint ) && _plConstraintsInCurrentPhasePattern.exists( constraint ) ); _lastAcceptedPhasePattern[constraint] = phase; } -void SumOfInfeasibilitiesManager::setPhaseStatusInCurrentPhasePattern -( PiecewiseLinearConstraint *constraint, PhaseStatus phase ) +void SumOfInfeasibilitiesManager::setPhaseStatusInCurrentPhasePattern( + PiecewiseLinearConstraint *constraint, + PhaseStatus phase ) { ASSERT( _currentPhasePattern.exists( constraint ) && _plConstraintsInCurrentPhasePattern.exists( constraint ) ); _currentPhasePattern[constraint] = phase; } -void SumOfInfeasibilitiesManager::getCostReduction( PiecewiseLinearConstraint * - plConstraint, double - &reducedCost, PhaseStatus - &phaseOfReducedCost ) const +void SumOfInfeasibilitiesManager::getCostReduction( PiecewiseLinearConstraint *plConstraint, + double &reducedCost, + PhaseStatus &phaseOfReducedCost ) const { ASSERT( _currentPhasePattern.exists( plConstraint ) ); SOI_LOG( "Computing reduced cost for the current constraint..." ); @@ -380,8 +363,7 @@ void SumOfInfeasibilitiesManager::getCostReduction( PiecewiseLinearConstraint * List allPhases = plConstraint->getAllCases(); allPhases.erase( currentPhase ); ASSERT( allPhases.size() > 0 ); // Otherwise, the constraint must be fixed. - SOI_LOG( Stringf( "Number of alternative phases: %u", allPhases.size() ). - ascii() ); + SOI_LOG( Stringf( "Number of alternative phases: %u", allPhases.size() ).ascii() ); // Compute the violation of the plConstraint w.r.t. the current assignment // and the current cost component. @@ -399,17 +381,17 @@ void SumOfInfeasibilitiesManager::getCostReduction( PiecewiseLinearConstraint * plConstraint->getCostFunctionComponent( otherCostComponent, phase ); double otherCost = otherCostComponent.evaluate( _currentAssignment ); double currentReducedCost = currentCost - otherCost; - SOI_LOG( Stringf( "Reduced cost of phase %u: %.2f", - currentReducedCost, phase ).ascii() ); + SOI_LOG( Stringf( "Reduced cost of phase %u: %.2f", currentReducedCost, phase ).ascii() ); if ( FloatUtils::lt( currentReducedCost, reducedCost ) ) { reducedCost = currentReducedCost; phaseOfReducedCost = phase; } } - ASSERT( reducedCost != FloatUtils::infinity() && - phaseOfReducedCost != PHASE_NOT_FIXED ); + ASSERT( reducedCost != FloatUtils::infinity() && phaseOfReducedCost != PHASE_NOT_FIXED ); SOI_LOG( Stringf( "Largest reduced cost is %.2f and achieved with phase status %u", - reducedCost, phaseOfReducedCost ).ascii() ); + reducedCost, + phaseOfReducedCost ) + .ascii() ); SOI_LOG( "Computing reduced cost for the current constraint - done" ); } diff --git a/src/engine/SumOfInfeasibilitiesManager.h b/src/engine/SumOfInfeasibilitiesManager.h index f6bf16b38e..dbddb98eca 100644 --- a/src/engine/SumOfInfeasibilitiesManager.h +++ b/src/engine/SumOfInfeasibilitiesManager.h @@ -17,8 +17,8 @@ #define __SumOfInfeasibilitiesManager_h__ #include "GlobalConfiguration.h" -#include "InputQuery.h" #include "ITableau.h" +#include "InputQuery.h" #include "LinearExpression.h" #include "List.h" #include "NetworkLevelReasoner.h" @@ -26,18 +26,15 @@ #include "SoIInitializationStrategy.h" #include "SoISearchStrategy.h" #include "Statistics.h" -#include "Vector.h" - #include "T/stdlib.h" +#include "Vector.h" #define SOI_LOG( x, ... ) LOG( GlobalConfiguration::SOI_LOGGING, "SoIManager: %s\n", x ) class SumOfInfeasibilitiesManager { public: - - SumOfInfeasibilitiesManager( const InputQuery &inputQuery, const ITableau - &tableau ); + SumOfInfeasibilitiesManager( const InputQuery &inputQuery, const ITableau &tableau ); /* Returns the actual current phase pattern from _currentPhasePattern @@ -98,8 +95,7 @@ class SumOfInfeasibilitiesManager // might be fixed due to additional tightening. // In that case, we remove the cost term for that piecewise linear constraint // from the heuristic cost. - void removeCostComponentFromHeuristicCost( PiecewiseLinearConstraint - *constraint ); + void removeCostComponentFromHeuristicCost( PiecewiseLinearConstraint *constraint ); /* Obtain the current variable assignment from the Tableau. @@ -109,12 +105,11 @@ class SumOfInfeasibilitiesManager void setStatistics( Statistics *statistics ); /* For debug use */ - void setPhaseStatusInLastAcceptedPhasePattern( PiecewiseLinearConstraint - *constraint, + void setPhaseStatusInLastAcceptedPhasePattern( PiecewiseLinearConstraint *constraint, PhaseStatus phase ); - void setPhaseStatusInCurrentPhasePattern( PiecewiseLinearConstraint - *constraint, PhaseStatus phase ); + void setPhaseStatusInCurrentPhasePattern( PiecewiseLinearConstraint *constraint, + PhaseStatus phase ); private: @@ -205,8 +200,9 @@ class SumOfInfeasibilitiesManager Note that the phase can be negative, which means the current phase is (locally) optimal. */ - void getCostReduction( PiecewiseLinearConstraint *plConstraint, double - &reducedCost, PhaseStatus &phaseOfReducedCost ) const; + void getCostReduction( PiecewiseLinearConstraint *plConstraint, + double &reducedCost, + PhaseStatus &phaseOfReducedCost ) const; }; #endif // __SumOfInfeasibilitiesManager_h__ diff --git a/src/engine/SymbolicBoundTighteningType.h b/src/engine/SymbolicBoundTighteningType.h index 852e7b95a5..ca238af776 100644 --- a/src/engine/SymbolicBoundTighteningType.h +++ b/src/engine/SymbolicBoundTighteningType.h @@ -19,11 +19,10 @@ /* MILP solver bound tightening options */ -enum class SymbolicBoundTighteningType -{ - SYMBOLIC_BOUND_TIGHTENING = 0, - DEEP_POLY = 1, - NONE = 2, +enum class SymbolicBoundTighteningType { + SYMBOLIC_BOUND_TIGHTENING = 0, + DEEP_POLY = 1, + NONE = 2, }; #endif // __SymbolicBoundTighteningType_h__ diff --git a/src/engine/T/ConstraintMatrixAnalyzerFactory.h b/src/engine/T/ConstraintMatrixAnalyzerFactory.h index 6c6b40a220..af072c73b1 100644 --- a/src/engine/T/ConstraintMatrixAnalyzerFactory.h +++ b/src/engine/T/ConstraintMatrixAnalyzerFactory.h @@ -21,24 +21,23 @@ class IConstraintMatrixAnalyzer; class ISelector; -namespace T -{ - IConstraintMatrixAnalyzer *createConstraintMatrixAnalyzer(); - void discardConstraintMatrixAnalyzer( IConstraintMatrixAnalyzer *constraintMatrixAnalyzer ); -} +namespace T { +IConstraintMatrixAnalyzer *createConstraintMatrixAnalyzer(); +void discardConstraintMatrixAnalyzer( IConstraintMatrixAnalyzer *constraintMatrixAnalyzer ); +} // namespace T CXXTEST_SUPPLY( createConstraintMatrixAnalyzer, - IConstraintMatrixAnalyzer *, - createConstraintMatrixAnalyzer, - (), - T::createConstraintMatrixAnalyzer, - () ); + IConstraintMatrixAnalyzer *, + createConstraintMatrixAnalyzer, + (), + T::createConstraintMatrixAnalyzer, + () ); CXXTEST_SUPPLY_VOID( discardConstraintMatrixAnalyzer, - discardConstraintMatrixAnalyzer, - ( IConstraintMatrixAnalyzer *constraintMatrixAnalyzer ), - T::discardConstraintMatrixAnalyzer, - ( constraintMatrixAnalyzer ) ); + discardConstraintMatrixAnalyzer, + ( IConstraintMatrixAnalyzer * constraintMatrixAnalyzer ), + T::discardConstraintMatrixAnalyzer, + ( constraintMatrixAnalyzer ) ); #endif // __T__ConstraintMatrixAnalyzerFactory_h__ diff --git a/src/engine/T/CostFunctionManagerFactory.h b/src/engine/T/CostFunctionManagerFactory.h index b64834cd22..75dccce57c 100644 --- a/src/engine/T/CostFunctionManagerFactory.h +++ b/src/engine/T/CostFunctionManagerFactory.h @@ -21,24 +21,23 @@ class ICostFunctionManager; class ITableau; -namespace T -{ - ICostFunctionManager *createCostFunctionManager( ITableau *tableau ); - void discardCostFunctionManager( ICostFunctionManager *costFunctionManager ); -} +namespace T { +ICostFunctionManager *createCostFunctionManager( ITableau *tableau ); +void discardCostFunctionManager( ICostFunctionManager *costFunctionManager ); +} // namespace T CXXTEST_SUPPLY( createCostFunctionManager, - ICostFunctionManager *, - createCostFunctionManager, - ( ITableau *tableau ), - T::createCostFunctionManager, - ( tableau ) ); + ICostFunctionManager *, + createCostFunctionManager, + ( ITableau * tableau ), + T::createCostFunctionManager, + ( tableau ) ); CXXTEST_SUPPLY_VOID( discardCostFunctionManager, - discardCostFunctionManager, - ( ICostFunctionManager *costFunctionManager ), - T::discardCostFunctionManager, - ( costFunctionManager ) ); + discardCostFunctionManager, + ( ICostFunctionManager * costFunctionManager ), + T::discardCostFunctionManager, + ( costFunctionManager ) ); #endif // __T__CostFunctionManagerFactory_h__ diff --git a/src/engine/T/ProjectedSteepestEdgeFactory.h b/src/engine/T/ProjectedSteepestEdgeFactory.h index 6059d73dfb..e933a1743c 100644 --- a/src/engine/T/ProjectedSteepestEdgeFactory.h +++ b/src/engine/T/ProjectedSteepestEdgeFactory.h @@ -20,24 +20,23 @@ class IProjectedSteepestEdgeRule; -namespace T -{ - IProjectedSteepestEdgeRule *createProjectedSteepestEdgeRule(); - void discardProjectedSteepestEdgeRule( IProjectedSteepestEdgeRule *projectedSteepestEdgeRule ); -} +namespace T { +IProjectedSteepestEdgeRule *createProjectedSteepestEdgeRule(); +void discardProjectedSteepestEdgeRule( IProjectedSteepestEdgeRule *projectedSteepestEdgeRule ); +} // namespace T CXXTEST_SUPPLY( createProjectedSteepestEdgeRule, - IProjectedSteepestEdgeRule *, - createProjectedSteepestEdgeRule, - (), - T::createProjectedSteepestEdgeRule, - () ); + IProjectedSteepestEdgeRule *, + createProjectedSteepestEdgeRule, + (), + T::createProjectedSteepestEdgeRule, + () ); CXXTEST_SUPPLY_VOID( discardProjectedSteepestEdgeRule, - discardProjectedSteepestEdgeRule, - ( IProjectedSteepestEdgeRule *projectedSteepestEdgeRule ), - T::discardProjectedSteepestEdgeRule, - ( projectedSteepestEdgeRule ) ); + discardProjectedSteepestEdgeRule, + ( IProjectedSteepestEdgeRule * projectedSteepestEdgeRule ), + T::discardProjectedSteepestEdgeRule, + ( projectedSteepestEdgeRule ) ); #endif // __T__ProjectedSteepestEdgeFactory_h__ diff --git a/src/engine/T/RowBoundTightenerFactory.h b/src/engine/T/RowBoundTightenerFactory.h index 1e8b02aa67..4e48a13663 100644 --- a/src/engine/T/RowBoundTightenerFactory.h +++ b/src/engine/T/RowBoundTightenerFactory.h @@ -22,24 +22,23 @@ class IRowBoundTightener; class ITableau; -namespace T -{ - IRowBoundTightener *createRowBoundTightener( const ITableau &tableau ); - void discardRowBoundTightener( IRowBoundTightener *rowBoundTightener ); -} +namespace T { +IRowBoundTightener *createRowBoundTightener( const ITableau &tableau ); +void discardRowBoundTightener( IRowBoundTightener *rowBoundTightener ); +} // namespace T CXXTEST_SUPPLY( createRowBoundTightener, - IRowBoundTightener *, - createRowBoundTightener, - ( const ITableau &tableau ), - T::createRowBoundTightener, - ( tableau ) ); + IRowBoundTightener *, + createRowBoundTightener, + ( const ITableau &tableau ), + T::createRowBoundTightener, + ( tableau ) ); CXXTEST_SUPPLY_VOID( discardRowBoundTightener, - discardRowBoundTightener, - ( IRowBoundTightener *rowBoundTightener ), - T::discardRowBoundTightener, - ( rowBoundTightener ) ); + discardRowBoundTightener, + ( IRowBoundTightener * rowBoundTightener ), + T::discardRowBoundTightener, + ( rowBoundTightener ) ); #endif // __T__RowBoundTightenerFactory_h__ diff --git a/src/engine/T/TableauFactory.h b/src/engine/T/TableauFactory.h index ef3d8e017f..dd1415dada 100644 --- a/src/engine/T/TableauFactory.h +++ b/src/engine/T/TableauFactory.h @@ -22,22 +22,21 @@ class ITableau; class IBoundManager; class ISelector; -namespace T -{ - ITableau *createTableau( IBoundManager &BoundManager ); - void discardTableau( ITableau *tableau ); -} +namespace T { +ITableau *createTableau( IBoundManager &BoundManager ); +void discardTableau( ITableau *tableau ); +} // namespace T CXXTEST_SUPPLY( createTableau, ITableau *, createTableau, - ( IBoundManager &boundManager ), + ( IBoundManager & boundManager ), T::createTableau, ( boundManager ) ); CXXTEST_SUPPLY_VOID( discardTableau, discardTableau, - ( ITableau *tableau ), + ( ITableau * tableau ), T::discardTableau, ( tableau ) ); diff --git a/src/engine/Tableau.cpp b/src/engine/Tableau.cpp index 198af138d7..13c964837d 100644 --- a/src/engine/Tableau.cpp +++ b/src/engine/Tableau.cpp @@ -39,8 +39,8 @@ Tableau::Tableau( IBoundManager &boundManager ) : _boundManager( boundManager ) , _lowerBounds( _boundManager.getLowerBounds() ) , _upperBounds( _boundManager.getUpperBounds() ) - , _n ( 0 ) - , _m ( 0 ) + , _n( 0 ) + , _m( 0 ) , _A( NULL ) , _sparseColumnsOfA( NULL ) , _sparseRowsOfA( NULL ) @@ -221,7 +221,8 @@ void Tableau::setDimensions( unsigned m, unsigned n ) { _sparseColumnsOfA[i] = new SparseUnsortedList( _m ); if ( !_sparseColumnsOfA[i] ) - throw MarabouError( MarabouError::ALLOCATION_FAILED, "Tableau::sparseColumnsOfA[i]" ); + throw MarabouError( MarabouError::ALLOCATION_FAILED, + "Tableau::sparseColumnsOfA[i]" ); } _sparseRowsOfA = new SparseUnsortedList *[m]; @@ -235,7 +236,7 @@ void Tableau::setDimensions( unsigned m, unsigned n ) throw MarabouError( MarabouError::ALLOCATION_FAILED, "Tableau::sparseRowOfA[i]" ); } - _denseA = new double[m*n]; + _denseA = new double[m * n]; if ( !_denseA ) throw MarabouError( MarabouError::ALLOCATION_FAILED, "Tableau::denseA" ); @@ -243,7 +244,7 @@ void Tableau::setDimensions( unsigned m, unsigned n ) if ( !_changeColumn ) throw MarabouError( MarabouError::ALLOCATION_FAILED, "Tableau::changeColumn" ); - _pivotRow = new TableauRow( n-m ); + _pivotRow = new TableauRow( n - m ); if ( !_pivotRow ) throw MarabouError( MarabouError::ALLOCATION_FAILED, "Tableau::pivotRow" ); @@ -267,11 +268,12 @@ void Tableau::setDimensions( unsigned m, unsigned n ) if ( !_variableToIndex ) throw MarabouError( MarabouError::ALLOCATION_FAILED, "Tableau::variableToIndex" ); - _nonBasicIndexToVariable = new unsigned[n-m]; + _nonBasicIndexToVariable = new unsigned[n - m]; if ( !_nonBasicIndexToVariable ) - throw MarabouError( MarabouError::ALLOCATION_FAILED, "Tableau::nonBasicIndexToVariable" ); + throw MarabouError( MarabouError::ALLOCATION_FAILED, + "Tableau::nonBasicIndexToVariable" ); - _nonBasicAssignment = new double[n-m]; + _nonBasicAssignment = new double[n - m]; if ( !_nonBasicAssignment ) throw MarabouError( MarabouError::ALLOCATION_FAILED, "Tableau::nonBasicAssignment" ); @@ -311,7 +313,7 @@ void Tableau::setConstraintMatrix( const double *A ) for ( unsigned column = 0; column < _n; ++column ) { for ( unsigned row = 0; row < _m; ++row ) - _denseA[column*_m + row] = A[row*_n + column]; + _denseA[column * _m + row] = A[row * _n + column]; _sparseColumnsOfA[column]->initialize( _denseA + ( column * _m ), _m ); } @@ -388,7 +390,7 @@ void Tableau::computeAssignment() We first compute y (stored in _work), and then do an FTRAN pass to solve B*xB = y */ - memcpy( _workM, _b, sizeof(double) * _m ); + memcpy( _workM, _b, sizeof( double ) * _m ); // Compute a linear combination of the columns of AN for ( unsigned i = 0; i < _n - _m; ++i ) @@ -410,9 +412,8 @@ void Tableau::computeAssignment() bool Tableau::checkValueWithinBounds( unsigned variable, double value ) { - return - FloatUtils::gte( value, getLowerBound( variable ) ) && - FloatUtils::lte( value, getUpperBound( variable ) ); + return FloatUtils::gte( value, getLowerBound( variable ) ) && + FloatUtils::lte( value, getUpperBound( variable ) ); } void Tableau::computeBasicStatus() @@ -427,16 +428,14 @@ void Tableau::computeBasicStatus( unsigned basicIndex ) double value = _basicAssignment[basicIndex]; double lb = getLowerBound( variable ); - double relaxedLb = - lb - - ( GlobalConfiguration::BOUND_COMPARISON_ADDITIVE_TOLERANCE + - GlobalConfiguration::BOUND_COMPARISON_MULTIPLICATIVE_TOLERANCE * FloatUtils::abs( lb ) ); + double relaxedLb = lb - ( GlobalConfiguration::BOUND_COMPARISON_ADDITIVE_TOLERANCE + + GlobalConfiguration::BOUND_COMPARISON_MULTIPLICATIVE_TOLERANCE * + FloatUtils::abs( lb ) ); double ub = getUpperBound( variable ); - double relaxedUb = - ub + - ( GlobalConfiguration::BOUND_COMPARISON_ADDITIVE_TOLERANCE + - GlobalConfiguration::BOUND_COMPARISON_MULTIPLICATIVE_TOLERANCE * FloatUtils::abs( ub ) ); + double relaxedUb = ub + ( GlobalConfiguration::BOUND_COMPARISON_ADDITIVE_TOLERANCE + + GlobalConfiguration::BOUND_COMPARISON_MULTIPLICATIVE_TOLERANCE * + FloatUtils::abs( ub ) ); if ( value > relaxedUb ) { @@ -528,7 +527,7 @@ unsigned Tableau::variableToIndex( unsigned index ) const void Tableau::setRightHandSide( const double *b ) { - memcpy( _b, b, sizeof(double) * _m ); + memcpy( _b, b, sizeof( double ) * _m ); for ( unsigned i = 0; i < _m; ++i ) { @@ -647,10 +646,9 @@ bool Tableau::nonBasicCanIncrease( unsigned nonBasic ) const unsigned variable = _nonBasicIndexToVariable[nonBasic]; double ub = getUpperBound( variable ); - double tighterUb = - ub - - ( GlobalConfiguration::BOUND_COMPARISON_ADDITIVE_TOLERANCE + - GlobalConfiguration::BOUND_COMPARISON_MULTIPLICATIVE_TOLERANCE * FloatUtils::abs( ub ) ); + double tighterUb = ub - ( GlobalConfiguration::BOUND_COMPARISON_ADDITIVE_TOLERANCE + + GlobalConfiguration::BOUND_COMPARISON_MULTIPLICATIVE_TOLERANCE * + FloatUtils::abs( ub ) ); return _nonBasicAssignment[nonBasic] < tighterUb; } @@ -660,10 +658,9 @@ bool Tableau::nonBasicCanDecrease( unsigned nonBasic ) const unsigned variable = _nonBasicIndexToVariable[nonBasic]; double lb = getLowerBound( variable ); - double tighterLb = - lb + - ( GlobalConfiguration::BOUND_COMPARISON_ADDITIVE_TOLERANCE + - GlobalConfiguration::BOUND_COMPARISON_MULTIPLICATIVE_TOLERANCE * FloatUtils::abs( lb ) ); + double tighterLb = lb + ( GlobalConfiguration::BOUND_COMPARISON_ADDITIVE_TOLERANCE + + GlobalConfiguration::BOUND_COMPARISON_MULTIPLICATIVE_TOLERANCE * + FloatUtils::abs( lb ) ); return _nonBasicAssignment[nonBasic] > tighterLb; } @@ -698,11 +695,10 @@ bool Tableau::performingFakePivot() const void Tableau::performPivot() { - bool decrease; - unsigned nonBasic; - (void) decrease; - (void) nonBasic; + unsigned nonBasic; + (void)decrease; + (void)nonBasic; if ( _leavingVariable == _m ) { if ( _statistics ) @@ -717,11 +713,14 @@ void Tableau::performPivot() nonBasic = _nonBasicIndexToVariable[_enteringVariable]; TABLEAU_LOG( Stringf( "Performing 'fake' pivot. Variable x%u jumping to %s bound", - _nonBasicIndexToVariable[_enteringVariable], - decrease ? "LOWER" : "UPPER" ).ascii() ); + _nonBasicIndexToVariable[_enteringVariable], + decrease ? "LOWER" : "UPPER" ) + .ascii() ); TABLEAU_LOG( Stringf( "Current value: %.3lf. Range: [%.3lf, %.3lf]\n", - _nonBasicAssignment[_enteringVariable], - getLowerBound( nonBasic ), getUpperBound( nonBasic ) ).ascii() ); + _nonBasicAssignment[_enteringVariable], + getLowerBound( nonBasic ), + getUpperBound( nonBasic ) ) + .ascii() ); updateAssignmentForPivot(); @@ -740,17 +739,24 @@ void Tableau::performPivot() unsigned currentNonBasic = _nonBasicIndexToVariable[_enteringVariable]; TABLEAU_LOG( Stringf( "Tableau performing pivot. Entering: %u, Leaving: %u", - _nonBasicIndexToVariable[_enteringVariable], - _basicIndexToVariable[_leavingVariable] ).ascii() ); + _nonBasicIndexToVariable[_enteringVariable], + _basicIndexToVariable[_leavingVariable] ) + .ascii() ); TABLEAU_LOG( Stringf( "Leaving variable %s. Current value: %.15lf. Range: [%.15lf, %.15lf]", - _leavingVariableIncreases ? "increases" : "decreases", - _basicAssignment[_leavingVariable], - getLowerBound( currentBasic ), getUpperBound( currentBasic ) ).ascii() ); + _leavingVariableIncreases ? "increases" : "decreases", + _basicAssignment[_leavingVariable], + getLowerBound( currentBasic ), + getUpperBound( currentBasic ) ) + .ascii() ); TABLEAU_LOG( Stringf( "Entering variable %s. Current value: %.15lf. Range: [%.15lf, %.15lf]", - FloatUtils::isNegative( _costFunctionManager->getCostFunction()[_enteringVariable] ) ? - "increases" : "decreases", - _nonBasicAssignment[_enteringVariable], - getLowerBound( currentNonBasic ), getUpperBound( currentNonBasic ) ).ascii() ); + FloatUtils::isNegative( + _costFunctionManager->getCostFunction()[_enteringVariable] ) + ? "increases" + : "decreases", + _nonBasicAssignment[_enteringVariable], + getLowerBound( currentNonBasic ), + getUpperBound( currentNonBasic ) ) + .ascii() ); TABLEAU_LOG( Stringf( "Change ratio is: %.15lf\n", _changeRatio ).ascii() ); // As part of the pivot operation we use both the pivot row and @@ -758,7 +764,8 @@ void Tableau::performPivot() // numerical degradation issue. double pivotEntryByColumn = -_changeColumn[_leavingVariable]; double pivotEntryByRow = _pivotRow->_row[_enteringVariable]._coefficient; - if ( !FloatUtils::isZero( pivotEntryByRow - pivotEntryByColumn, GlobalConfiguration::PIVOT_ROW_AND_COLUMN_TOLERANCE ) ) + if ( !FloatUtils::isZero( pivotEntryByRow - pivotEntryByColumn, + GlobalConfiguration::PIVOT_ROW_AND_COLUMN_TOLERANCE ) ) throw MalformedBasisException(); updateAssignmentForPivot(); @@ -782,14 +789,14 @@ void Tableau::performPivot() // Update the basis factorization. The column corresponding to the // leaving variable is the one that has changed - _basisFactorization->updateToAdjacentBasis( _leavingVariable, - _changeColumn, - getAColumn( currentNonBasic ) ); + _basisFactorization->updateToAdjacentBasis( + _leavingVariable, _changeColumn, getAColumn( currentNonBasic ) ); if ( _statistics ) { struct timespec pivotEnd = TimeUtils::sampleMicro(); - _statistics->incLongAttribute( Statistics::TIME_PIVOTS_MICRO, TimeUtils::timePassed( pivotStart, pivotEnd ) ); + _statistics->incLongAttribute( Statistics::TIME_PIVOTS_MICRO, + TimeUtils::timePassed( pivotStart, pivotEnd ) ); } } @@ -824,9 +831,8 @@ void Tableau::performDegeneratePivot() _variableToIndex[currentNonBasic] = _leavingVariable; // Update the basis factorization - _basisFactorization->updateToAdjacentBasis( _leavingVariable, - _changeColumn, - getAColumn( currentNonBasic ) ); + _basisFactorization->updateToAdjacentBasis( + _leavingVariable, _changeColumn, getAColumn( currentNonBasic ) ); // Switch assignment values. No call to notify is required, // because values haven't changed. @@ -838,7 +844,8 @@ void Tableau::performDegeneratePivot() if ( _statistics ) { struct timespec pivotEnd = TimeUtils::sampleMicro(); - _statistics->incLongAttribute( Statistics::TIME_PIVOTS_MICRO, TimeUtils::timePassed( pivotStart, pivotEnd ) ); + _statistics->incLongAttribute( Statistics::TIME_PIVOTS_MICRO, + TimeUtils::timePassed( pivotStart, pivotEnd ) ); } } @@ -880,7 +887,8 @@ double Tableau::ratioConstraintPerBasic( unsigned basicIndex, double coefficient } double tolerance = GlobalConfiguration::RATIO_CONSTRAINT_ADDITIVE_TOLERANCE + - FloatUtils::abs( actualLowerBound ) * GlobalConfiguration::RATIO_CONSTRAINT_MULTIPLICATIVE_TOLERANCE; + FloatUtils::abs( actualLowerBound ) * + GlobalConfiguration::RATIO_CONSTRAINT_MULTIPLICATIVE_TOLERANCE; if ( _basicAssignment[basicIndex] <= actualLowerBound + tolerance ) { @@ -918,7 +926,8 @@ double Tableau::ratioConstraintPerBasic( unsigned basicIndex, double coefficient } double tolerance = GlobalConfiguration::RATIO_CONSTRAINT_ADDITIVE_TOLERANCE + - FloatUtils::abs( actualUpperBound ) * GlobalConfiguration::RATIO_CONSTRAINT_MULTIPLICATIVE_TOLERANCE; + FloatUtils::abs( actualUpperBound ) * + GlobalConfiguration::RATIO_CONSTRAINT_MULTIPLICATIVE_TOLERANCE; if ( _basicAssignment[basicIndex] >= actualUpperBound - tolerance ) { @@ -955,20 +964,21 @@ void Tableau::pickLeavingVariable( double *changeColumn ) void Tableau::standardRatioTest( double *changeColumn ) { ASSERT( !FloatUtils::isZero( _costFunctionManager->getCostFunction()[_enteringVariable] ) ); - bool decrease = FloatUtils::isPositive( _costFunctionManager->getCostFunction()[_enteringVariable] ); + bool decrease = + FloatUtils::isPositive( _costFunctionManager->getCostFunction()[_enteringVariable] ); - DEBUG({ - if ( decrease ) - { - ASSERTM( nonBasicCanDecrease( _enteringVariable ), - "Error! Entering variable needs to decrease but is at its lower bound" ); - } - else - { - ASSERTM( nonBasicCanIncrease( _enteringVariable ), - "Error! Entering variable needs to increase but is at its upper bound" ); - } - }); + DEBUG( { + if ( decrease ) + { + ASSERTM( nonBasicCanDecrease( _enteringVariable ), + "Error! Entering variable needs to decrease but is at its lower bound" ); + } + else + { + ASSERTM( nonBasicCanIncrease( _enteringVariable ), + "Error! Entering variable needs to increase but is at its upper bound" ); + } + } ); double lb = getLowerBound( _nonBasicIndexToVariable[_enteringVariable] ); double ub = getUpperBound( _nonBasicIndexToVariable[_enteringVariable] ); @@ -996,7 +1006,8 @@ void Tableau::standardRatioTest( double *changeColumn ) double ratio = ratioConstraintPerBasic( i, changeColumn[i], decrease ); if ( ( ratio > _changeRatio ) || - ( ( ratio == _changeRatio ) && ( FloatUtils::abs( changeColumn[i] ) > largestPivot ) ) ) + ( ( ratio == _changeRatio ) && + ( FloatUtils::abs( changeColumn[i] ) > largestPivot ) ) ) { _changeRatio = ratio; _leavingVariable = i; @@ -1027,7 +1038,8 @@ void Tableau::standardRatioTest( double *changeColumn ) double ratio = ratioConstraintPerBasic( i, changeColumn[i], decrease ); if ( ( ratio < _changeRatio ) || - ( ( ratio == _changeRatio ) && ( FloatUtils::abs( changeColumn[i] ) > largestPivot ) ) ) + ( ( ratio == _changeRatio ) && + ( FloatUtils::abs( changeColumn[i] ) > largestPivot ) ) ) { _changeRatio = ratio; _leavingVariable = i; @@ -1059,20 +1071,21 @@ void Tableau::harrisRatioTest( double *changeColumn ) ASSERT( !FloatUtils::isZero( _costFunctionManager->getCostFunction()[_enteringVariable] ) ); // Is the entering variable decreasing? - bool enteringDecreases = FloatUtils::isPositive( _costFunctionManager->getCostFunction()[_enteringVariable] ); + bool enteringDecreases = + FloatUtils::isPositive( _costFunctionManager->getCostFunction()[_enteringVariable] ); - DEBUG({ - if ( enteringDecreases ) - { - ASSERTM( nonBasicCanDecrease( _enteringVariable ), - "Error! Entering variable needs to decrease but is at its lower bound" ); - } - else - { - ASSERTM( nonBasicCanIncrease( _enteringVariable ), - "Error! Entering variable needs to increase but is at its upper bound" ); - } - }); + DEBUG( { + if ( enteringDecreases ) + { + ASSERTM( nonBasicCanDecrease( _enteringVariable ), + "Error! Entering variable needs to decrease but is at its lower bound" ); + } + else + { + ASSERTM( nonBasicCanIncrease( _enteringVariable ), + "Error! Entering variable needs to increase but is at its upper bound" ); + } + } ); /* Alfa: @@ -1115,12 +1128,15 @@ void Tableau::harrisRatioTest( double *changeColumn ) actualUpperBound = getUpperBound( basic ); // Determine the constraint imposed by this basic - double delta = GlobalConfiguration::HARRIS_RATIO_CONSTRAINT_ADDITIVE_TOLERANCE + - FloatUtils::abs( actualUpperBound ) * GlobalConfiguration::HARRIS_RATIO_CONSTRAINT_MULTIPLICATIVE_TOLERANCE; + double delta = + GlobalConfiguration::HARRIS_RATIO_CONSTRAINT_ADDITIVE_TOLERANCE + + FloatUtils::abs( actualUpperBound ) * + GlobalConfiguration::HARRIS_RATIO_CONSTRAINT_MULTIPLICATIVE_TOLERANCE; if ( _basicAssignment[i] > actualUpperBound ) - ratioConstraintPerBasic = - delta / changeColumn[i]; + ratioConstraintPerBasic = -delta / changeColumn[i]; else - ratioConstraintPerBasic = - ( ( actualUpperBound + delta ) - _basicAssignment[i] ) / changeColumn[i]; + ratioConstraintPerBasic = + -( ( actualUpperBound + delta ) - _basicAssignment[i] ) / changeColumn[i]; } else if ( changeColumn[i] <= -GlobalConfiguration::PIVOT_CHANGE_COLUMN_TOLERANCE ) { @@ -1139,12 +1155,15 @@ void Tableau::harrisRatioTest( double *changeColumn ) actualLowerBound = getLowerBound( basic ); // Determine the constraint imposed by this basic - double delta = GlobalConfiguration::HARRIS_RATIO_CONSTRAINT_ADDITIVE_TOLERANCE + - FloatUtils::abs( actualLowerBound ) * GlobalConfiguration::HARRIS_RATIO_CONSTRAINT_MULTIPLICATIVE_TOLERANCE; + double delta = + GlobalConfiguration::HARRIS_RATIO_CONSTRAINT_ADDITIVE_TOLERANCE + + FloatUtils::abs( actualLowerBound ) * + GlobalConfiguration::HARRIS_RATIO_CONSTRAINT_MULTIPLICATIVE_TOLERANCE; if ( _basicAssignment[i] < actualLowerBound ) ratioConstraintPerBasic = delta / changeColumn[i]; else - ratioConstraintPerBasic = - ( ( actualLowerBound - delta ) - _basicAssignment[i] ) / changeColumn[i]; + ratioConstraintPerBasic = + -( ( actualLowerBound - delta ) - _basicAssignment[i] ) / changeColumn[i]; } else { @@ -1189,12 +1208,15 @@ void Tableau::harrisRatioTest( double *changeColumn ) actualLowerBound = getLowerBound( basic ); // Determine the constraint imposed by this basic - double delta = GlobalConfiguration::HARRIS_RATIO_CONSTRAINT_ADDITIVE_TOLERANCE + - FloatUtils::abs( actualLowerBound ) * GlobalConfiguration::HARRIS_RATIO_CONSTRAINT_MULTIPLICATIVE_TOLERANCE; + double delta = + GlobalConfiguration::HARRIS_RATIO_CONSTRAINT_ADDITIVE_TOLERANCE + + FloatUtils::abs( actualLowerBound ) * + GlobalConfiguration::HARRIS_RATIO_CONSTRAINT_MULTIPLICATIVE_TOLERANCE; if ( _basicAssignment[i] < actualLowerBound ) ratioConstraintPerBasic = delta / changeColumn[i]; else - ratioConstraintPerBasic = - ( ( actualLowerBound - delta ) - _basicAssignment[i] ) / changeColumn[i]; + ratioConstraintPerBasic = + -( ( actualLowerBound - delta ) - _basicAssignment[i] ) / changeColumn[i]; } else if ( changeColumn[i] <= -GlobalConfiguration::PIVOT_CHANGE_COLUMN_TOLERANCE ) { @@ -1213,12 +1235,15 @@ void Tableau::harrisRatioTest( double *changeColumn ) actualUpperBound = getUpperBound( basic ); // Determine the constraint imposed by this basic - double delta = GlobalConfiguration::HARRIS_RATIO_CONSTRAINT_ADDITIVE_TOLERANCE + - FloatUtils::abs( actualUpperBound ) * GlobalConfiguration::HARRIS_RATIO_CONSTRAINT_MULTIPLICATIVE_TOLERANCE; + double delta = + GlobalConfiguration::HARRIS_RATIO_CONSTRAINT_ADDITIVE_TOLERANCE + + FloatUtils::abs( actualUpperBound ) * + GlobalConfiguration::HARRIS_RATIO_CONSTRAINT_MULTIPLICATIVE_TOLERANCE; if ( _basicAssignment[i] > actualUpperBound ) - ratioConstraintPerBasic = - delta / changeColumn[i]; + ratioConstraintPerBasic = -delta / changeColumn[i]; else - ratioConstraintPerBasic = - ( ( actualUpperBound + delta ) - _basicAssignment[i] ) / changeColumn[i]; + ratioConstraintPerBasic = + -( ( actualUpperBound + delta ) - _basicAssignment[i] ) / changeColumn[i]; } else { @@ -1285,7 +1310,8 @@ void Tableau::harrisRatioTest( double *changeColumn ) else actualUpperBound = getUpperBound( basic ); - ratioConstraintPerBasic = - ( actualUpperBound - _basicAssignment[i] ) / changeColumn[i]; + ratioConstraintPerBasic = + -( actualUpperBound - _basicAssignment[i] ) / changeColumn[i]; } else if ( changeColumn[i] <= -GlobalConfiguration::PIVOT_CHANGE_COLUMN_TOLERANCE ) { @@ -1303,7 +1329,8 @@ void Tableau::harrisRatioTest( double *changeColumn ) else actualLowerBound = getLowerBound( basic ); - ratioConstraintPerBasic = - ( actualLowerBound - _basicAssignment[i] ) / changeColumn[i]; + ratioConstraintPerBasic = + -( actualLowerBound - _basicAssignment[i] ) / changeColumn[i]; } else { @@ -1328,7 +1355,8 @@ void Tableau::harrisRatioTest( double *changeColumn ) largestPivot = pivot; _leavingVariable = i; _changeRatio = ratioConstraintPerBasic; - _leavingVariableIncreases = FloatUtils::isPositive( changeColumn[_leavingVariable] ); + _leavingVariableIncreases = + FloatUtils::isPositive( changeColumn[_leavingVariable] ); } } } @@ -1356,7 +1384,8 @@ void Tableau::harrisRatioTest( double *changeColumn ) else actualLowerBound = getLowerBound( basic ); - ratioConstraintPerBasic = - ( actualLowerBound - _basicAssignment[i] ) / changeColumn[i]; + ratioConstraintPerBasic = + -( actualLowerBound - _basicAssignment[i] ) / changeColumn[i]; } else if ( changeColumn[i] <= -GlobalConfiguration::PIVOT_CHANGE_COLUMN_TOLERANCE ) { @@ -1374,8 +1403,8 @@ void Tableau::harrisRatioTest( double *changeColumn ) else actualUpperBound = getUpperBound( basic ); - ratioConstraintPerBasic = - ( actualUpperBound - _basicAssignment[i] ) / changeColumn[i]; - + ratioConstraintPerBasic = + -( actualUpperBound - _basicAssignment[i] ) / changeColumn[i]; } else { @@ -1400,7 +1429,8 @@ void Tableau::harrisRatioTest( double *changeColumn ) largestPivot = pivot; _leavingVariable = i; _changeRatio = ratioConstraintPerBasic; - _leavingVariableIncreases = FloatUtils::isNegative( changeColumn[_leavingVariable] ); + _leavingVariableIncreases = + FloatUtils::isNegative( changeColumn[_leavingVariable] ); } } } @@ -1433,7 +1463,7 @@ const double *Tableau::getChangeColumn() const void Tableau::setChangeColumn( const double *column ) { - memcpy( _changeColumn, column, _m * sizeof(double) ); + memcpy( _changeColumn, column, _m * sizeof( double ) ); } void Tableau::computePivotRow() @@ -1490,8 +1520,11 @@ void Tableau::dumpAssignment() for ( unsigned i = 0; i < _n; ++i ) { bool basic = _basicVariables.exists( i ); - printf( "\tx%u (index: %u) --> %.5lf [%s]. ", i, _variableToIndex[i], - getValue( i ), basic ? "B" : "NB" ); + printf( "\tx%u (index: %u) --> %.5lf [%s]. ", + i, + _variableToIndex[i], + getValue( i ), + basic ? "B" : "NB" ); if ( getLowerBound( i ) != FloatUtils::negativeInfinity() ) printf( "Range: [ %.5lf, ", getLowerBound( i ) ); else @@ -1634,23 +1667,25 @@ void Tableau::storeState( TableauState &state, TableauStateStorageLevel level ) _sparseColumnsOfA[i]->storeIntoOther( state._sparseColumnsOfA[i] ); for ( unsigned i = 0; i < _m; ++i ) _sparseRowsOfA[i]->storeIntoOther( state._sparseRowsOfA[i] ); - memcpy( state._denseA, _denseA, sizeof(double) * _m * _n ); + memcpy( state._denseA, _denseA, sizeof( double ) * _m * _n ); // Store right hand side vector _b - memcpy( state._b, _b, sizeof(double) * _m ); + memcpy( state._b, _b, sizeof( double ) * _m ); // Basic variables state._basicVariables = _basicVariables; // Store the assignments - memcpy( state._basicAssignment, _basicAssignment, sizeof(double) *_m ); - memcpy( state._nonBasicAssignment, _nonBasicAssignment, sizeof(double) * ( _n - _m ) ); + memcpy( state._basicAssignment, _basicAssignment, sizeof( double ) * _m ); + memcpy( state._nonBasicAssignment, _nonBasicAssignment, sizeof( double ) * ( _n - _m ) ); state._basicAssignmentStatus = _basicAssignmentStatus; // Store the indices - memcpy( state._basicIndexToVariable, _basicIndexToVariable, sizeof(unsigned) * _m ); - memcpy( state._nonBasicIndexToVariable, _nonBasicIndexToVariable, sizeof(unsigned) * ( _n - _m ) ); - memcpy( state._variableToIndex, _variableToIndex, sizeof(unsigned) * _n ); + memcpy( state._basicIndexToVariable, _basicIndexToVariable, sizeof( unsigned ) * _m ); + memcpy( state._nonBasicIndexToVariable, + _nonBasicIndexToVariable, + sizeof( unsigned ) * ( _n - _m ) ); + memcpy( state._variableToIndex, _variableToIndex, sizeof( unsigned ) * _n ); // Store the basis factorization _basisFactorization->storeFactorization( state._basisFactorization ); @@ -1674,17 +1709,14 @@ void Tableau::updateVariablesToComplyWithBounds() for ( unsigned i = 0; i < _n - _m; ++i ) { unsigned variable = _nonBasicIndexToVariable[i]; - updateVariableToComplyWithLowerBoundUpdate( variable, - getLowerBound( variable ) ); - updateVariableToComplyWithUpperBoundUpdate( variable, - getUpperBound( variable ) ); + updateVariableToComplyWithLowerBoundUpdate( variable, getLowerBound( variable ) ); + updateVariableToComplyWithUpperBoundUpdate( variable, getUpperBound( variable ) ); } computeBasicStatus(); } } -void Tableau::restoreState( const TableauState &state, - TableauStateStorageLevel level ) +void Tableau::restoreState( const TableauState &state, TableauStateStorageLevel level ) { if ( level == TableauStateStorageLevel::STORE_BOUNDS_ONLY || _lpSolverType != LPSolverType::NATIVE ) @@ -1702,23 +1734,25 @@ void Tableau::restoreState( const TableauState &state, state._sparseColumnsOfA[i]->storeIntoOther( _sparseColumnsOfA[i] ); for ( unsigned i = 0; i < _m; ++i ) state._sparseRowsOfA[i]->storeIntoOther( _sparseRowsOfA[i] ); - memcpy( _denseA, state._denseA, sizeof(double) * _m * _n ); + memcpy( _denseA, state._denseA, sizeof( double ) * _m * _n ); // Restore right hand side vector _b - memcpy( _b, state._b, sizeof(double) * _m ); + memcpy( _b, state._b, sizeof( double ) * _m ); // Basic variables _basicVariables = state._basicVariables; // Restore the assignments - memcpy( _basicAssignment, state._basicAssignment, sizeof(double) *_m ); - memcpy( _nonBasicAssignment, state._nonBasicAssignment, sizeof(double) * ( _n - _m ) ); + memcpy( _basicAssignment, state._basicAssignment, sizeof( double ) * _m ); + memcpy( _nonBasicAssignment, state._nonBasicAssignment, sizeof( double ) * ( _n - _m ) ); _basicAssignmentStatus = state._basicAssignmentStatus; // Restore the indices - memcpy( _basicIndexToVariable, state._basicIndexToVariable, sizeof(unsigned) * _m ); - memcpy( _nonBasicIndexToVariable, state._nonBasicIndexToVariable, sizeof(unsigned) * ( _n - _m ) ); - memcpy( _variableToIndex, state._variableToIndex, sizeof(unsigned) * _n ); + memcpy( _basicIndexToVariable, state._basicIndexToVariable, sizeof( unsigned ) * _m ); + memcpy( _nonBasicIndexToVariable, + state._nonBasicIndexToVariable, + sizeof( unsigned ) * ( _n - _m ) ); + memcpy( _variableToIndex, state._variableToIndex, sizeof( unsigned ) * _n ); // Restore the basis factorization _basisFactorization->restoreFactorization( state._basisFactorization ); @@ -1751,7 +1785,7 @@ bool Tableau::allBoundsValid() const void Tableau::updateVariableToComplyWithLowerBoundUpdate( unsigned variable, double value ) { if ( _lpSolverType == LPSolverType::GUROBI ) - return; + return; unsigned index = _variableToIndex[variable]; if ( !_basicVariables.exists( variable ) ) @@ -1773,7 +1807,7 @@ void Tableau::updateVariableToComplyWithLowerBoundUpdate( unsigned variable, dou void Tableau::updateVariableToComplyWithUpperBoundUpdate( unsigned variable, double value ) { if ( _lpSolverType == LPSolverType::GUROBI ) - return; + return; unsigned index = _variableToIndex[variable]; if ( !_basicVariables.exists( variable ) ) @@ -1842,13 +1876,13 @@ unsigned Tableau::addEquation( const Equation &equation ) _workN[addend._variable] = addend._coefficient; _sparseColumnsOfA[addend._variable]->set( _m - 1, addend._coefficient ); _sparseRowsOfA[_m - 1]->set( addend._variable, addend._coefficient ); - _denseA[(addend._variable * _m) + _m - 1] = addend._coefficient; + _denseA[( addend._variable * _m ) + _m - 1] = addend._coefficient; } _workN[auxVariable] = 1; _sparseColumnsOfA[auxVariable]->set( _m - 1, 1 ); _sparseRowsOfA[_m - 1]->set( auxVariable, 1 ); - _denseA[(auxVariable * _m) + _m - 1] = 1; + _denseA[( auxVariable * _m ) + _m - 1] = 1; _A->addLastRow( _workN ); // Invalidate the cost function, so that it is recomputed in the next iteration. @@ -1970,7 +2004,8 @@ void Tableau::addRow() newSparseColumnsOfA[newN - 1] = new SparseUnsortedList( newM ); if ( !newSparseColumnsOfA[newN - 1] ) - throw MarabouError( MarabouError::ALLOCATION_FAILED, "Tableau::newSparseColumnsOfA[newN-1]" ); + throw MarabouError( MarabouError::ALLOCATION_FAILED, + "Tableau::newSparseColumnsOfA[newN-1]" ); delete[] _sparseColumnsOfA; _sparseColumnsOfA = newSparseColumnsOfA; @@ -2000,8 +2035,8 @@ void Tableau::addRow() for ( unsigned column = 0; column < _n; ++column ) { - memcpy( newDenseA + ( column * newM ), _denseA + ( column * _m ), sizeof(double) * _m ); - newDenseA[column*newM + newM - 1] = 0.0; + memcpy( newDenseA + ( column * newM ), _denseA + ( column * _m ), sizeof( double ) * _m ); + newDenseA[column * newM + newM - 1] = 0.0; } std::fill_n( newDenseA + ( newN - 1 ) * newM, newM, 0.0 ); @@ -2020,7 +2055,7 @@ void Tableau::addRow() if ( !newB ) throw MarabouError( MarabouError::ALLOCATION_FAILED, "Tableau::newB" ); std::fill( newB + _m, newB + newM, 0.0 ); - memcpy( newB, _b, _m * sizeof(double) ); + memcpy( newB, _b, _m * sizeof( double ) ); delete[] _b; _b = newB; @@ -2042,14 +2077,14 @@ void Tableau::addRow() unsigned *newBasicIndexToVariable = new unsigned[newM]; if ( !newBasicIndexToVariable ) throw MarabouError( MarabouError::ALLOCATION_FAILED, "Tableau::newBasicIndexToVariable" ); - memcpy( newBasicIndexToVariable, _basicIndexToVariable, _m * sizeof(unsigned) ); + memcpy( newBasicIndexToVariable, _basicIndexToVariable, _m * sizeof( unsigned ) ); delete[] _basicIndexToVariable; _basicIndexToVariable = newBasicIndexToVariable; unsigned *newVariableToIndex = new unsigned[newN]; if ( !newVariableToIndex ) throw MarabouError( MarabouError::ALLOCATION_FAILED, "Tableau::newVariableToIndex" ); - memcpy( newVariableToIndex, _variableToIndex, _n * sizeof(unsigned) ); + memcpy( newVariableToIndex, _variableToIndex, _n * sizeof( unsigned ) ); delete[] _variableToIndex; _variableToIndex = newVariableToIndex; @@ -2057,14 +2092,14 @@ void Tableau::addRow() double *newBasicAssignment = new double[newM]; if ( !newBasicAssignment ) throw MarabouError( MarabouError::ALLOCATION_FAILED, "Tableau::newAssignment" ); - memcpy( newBasicAssignment, _basicAssignment, sizeof(double) * _m ); + memcpy( newBasicAssignment, _basicAssignment, sizeof( double ) * _m ); delete[] _basicAssignment; _basicAssignment = newBasicAssignment; unsigned *newBasicStatus = new unsigned[newM]; if ( !newBasicStatus ) throw MarabouError( MarabouError::ALLOCATION_FAILED, "Tableau::newBasicStatus" ); - memcpy( newBasicStatus, _basicStatus, sizeof(unsigned) * _m ); + memcpy( newBasicStatus, _basicStatus, sizeof( unsigned ) * _m ); delete[] _basicStatus; _basicStatus = newBasicStatus; @@ -2238,16 +2273,14 @@ void Tableau::verifyInvariants() double value = _nonBasicAssignment[i]; double lb = getLowerBound( variable ); - double relaxedLb = - lb - - ( GlobalConfiguration::BOUND_COMPARISON_ADDITIVE_TOLERANCE + - GlobalConfiguration::BOUND_COMPARISON_MULTIPLICATIVE_TOLERANCE * FloatUtils::abs( lb ) ); + double relaxedLb = lb - ( GlobalConfiguration::BOUND_COMPARISON_ADDITIVE_TOLERANCE + + GlobalConfiguration::BOUND_COMPARISON_MULTIPLICATIVE_TOLERANCE * + FloatUtils::abs( lb ) ); double ub = getUpperBound( variable ); - double relaxedUb = - ub + - ( GlobalConfiguration::BOUND_COMPARISON_ADDITIVE_TOLERANCE + - GlobalConfiguration::BOUND_COMPARISON_MULTIPLICATIVE_TOLERANCE * FloatUtils::abs( ub ) ); + double relaxedUb = ub + ( GlobalConfiguration::BOUND_COMPARISON_ADDITIVE_TOLERANCE + + GlobalConfiguration::BOUND_COMPARISON_MULTIPLICATIVE_TOLERANCE * + FloatUtils::abs( ub ) ); if ( !( ( relaxedLb <= value ) && ( value <= relaxedUb ) ) ) { @@ -2259,7 +2292,11 @@ void Tableau::verifyInvariants() printf( "Tableau test invariants: bound violation!\n" ); printf( "Variable %u (non-basic #%u). Assignment: %.15lf. Range: [%.15lf, %.15lf]\n", - variable, i, _nonBasicAssignment[i], getLowerBound( variable ), getUpperBound( variable ) ); + variable, + i, + _nonBasicAssignment[i], + getLowerBound( variable ), + getUpperBound( variable ) ); printf( "RelaxedLB = %.15lf. RelaxedUB = %.15lf\n", relaxedLb, relaxedUb ); exit( 1 ); @@ -2340,7 +2377,8 @@ void Tableau::updateAssignmentForPivot() // A non-basic is hopping from one bound to the other. double enteringReducedCost = _costFunctionManager->getCostFunction()[_enteringVariable]; - bool nonBasicDecreases = ( enteringReducedCost >= +GlobalConfiguration::ENTRY_ELIGIBILITY_TOLERANCE ); + bool nonBasicDecreases = + ( enteringReducedCost >= +GlobalConfiguration::ENTRY_ELIGIBILITY_TOLERANCE ); unsigned nonBasic = _nonBasicIndexToVariable[_enteringVariable]; @@ -2354,14 +2392,15 @@ void Tableau::updateAssignmentForPivot() for ( unsigned i = 0; i < _m; ++i ) { if ( FloatUtils::isZero( _changeColumn[i] ) ) - continue; + continue; _basicAssignment[i] -= _changeColumn[i] * nonBasicDelta; computeBasicStatus( i ); } // Update the assignment for the non-basic variable - _nonBasicAssignment[_enteringVariable] = nonBasicDecreases ? getLowerBound( nonBasic ) : getUpperBound( nonBasic ); + _nonBasicAssignment[_enteringVariable] = + nonBasicDecreases ? getLowerBound( nonBasic ) : getUpperBound( nonBasic ); } else { @@ -2424,11 +2463,8 @@ void Tableau::updateCostFunctionForPivot() return; double pivotElement = -_changeColumn[_leavingVariable]; - double normalizedError = _costFunctionManager->updateCostFunctionForPivot( _enteringVariable, - _leavingVariable, - pivotElement, - _pivotRow, - _changeColumn ); + double normalizedError = _costFunctionManager->updateCostFunctionForPivot( + _enteringVariable, _leavingVariable, pivotElement, _pivotRow, _changeColumn ); if ( FloatUtils::gt( normalizedError, GlobalConfiguration::COST_FUNCTION_ERROR_THRESHOLD ) ) _costFunctionManager->invalidateCostFunction(); @@ -2550,7 +2586,7 @@ void Tableau::mergeColumns( unsigned x1, unsigned x2 ) // And the dense ones, too for ( unsigned i = 0; i < _m; ++i ) - _denseA[x1*_m + i] += _denseA[x2*_m + i]; + _denseA[x1 * _m + i] += _denseA[x2 * _m + i]; std::fill_n( _denseA + x2 * _m, _m, 0 ); computeAssignment(); @@ -2560,7 +2596,10 @@ void Tableau::mergeColumns( unsigned x1, unsigned x2 ) _statistics->incLongAttribute( Statistics::NUM_MERGED_COLUMNS ); } -bool Tableau::areLinearlyDependent( unsigned x1, unsigned x2, double &coefficient, double &inverseCoefficient ) +bool Tableau::areLinearlyDependent( unsigned x1, + unsigned x2, + double &coefficient, + double &inverseCoefficient ) { bool oneIsBasic = isBasic( x1 ); bool twoIsBasic = isBasic( x2 ); diff --git a/src/engine/Tableau.h b/src/engine/Tableau.h index 4f097f9125..dbb04c3a22 100644 --- a/src/engine/Tableau.h +++ b/src/engine/Tableau.h @@ -16,9 +16,9 @@ #ifndef __Tableau_h__ #define __Tableau_h__ -#include "IBoundManager.h" #include "GurobiWrapper.h" #include "IBasisFactorization.h" +#include "IBoundManager.h" #include "ITableau.h" #include "LPSolverType.h" #include "MString.h" @@ -36,7 +36,9 @@ class ICostFunctionManager; class PiecewiseLinearCaseSplit; class TableauState; -class Tableau : public ITableau, public IBasisFactorization::BasisColumnOracle +class Tableau + : public ITableau + , public IBasisFactorization::BasisColumnOracle { public: Tableau( IBoundManager &boundManager ); @@ -169,7 +171,10 @@ class Tableau : public ITableau, public IBasisFactorization::BasisColumnOracle /* Get BoundManager reference */ - IBoundManager &getBoundManager() const { return _boundManager; } + IBoundManager &getBoundManager() const + { + return _boundManager; + } /* Returns whether any variable's bounds are invalid. @@ -453,7 +458,10 @@ class Tableau : public ITableau, public IBasisFactorization::BasisColumnOracle The inverse coefficient is just 1/c. */ - bool areLinearlyDependent( unsigned x1, unsigned x2, double &coefficient, double &inverseCoefficient ); + bool areLinearlyDependent( unsigned x1, + unsigned x2, + double &coefficient, + double &inverseCoefficient ); /* When we start merging columns, variables effectively get renamed. @@ -475,6 +483,7 @@ class Tableau : public ITableau, public IBasisFactorization::BasisColumnOracle */ void tightenUpperBoundNaively( unsigned variable, double value ); void tightenLowerBoundNaively( unsigned variable, double value ); + private: /* Variable watchers @@ -496,8 +505,8 @@ class Tableau : public ITableau, public IBasisFactorization::BasisColumnOracle /* Direct pointers to _boundManager arrays to avoid multiple dereferencing. */ - const double * _lowerBounds; - const double * _upperBounds; + const double *_lowerBounds; + const double *_upperBounds; /* The dimensions of matrix A diff --git a/src/engine/TableauRow.cpp b/src/engine/TableauRow.cpp index 5c3fae5874..72a28698a1 100644 --- a/src/engine/TableauRow.cpp +++ b/src/engine/TableauRow.cpp @@ -13,9 +13,10 @@ **/ -#include "MarabouError.h" #include "TableauRow.h" +#include "MarabouError.h" + TableauRow::TableauRow( unsigned size ) : _size( size ) { diff --git a/src/engine/TableauState.cpp b/src/engine/TableauState.cpp index 4d9dab95d4..d3a4d03ddc 100644 --- a/src/engine/TableauState.cpp +++ b/src/engine/TableauState.cpp @@ -13,11 +13,12 @@ **/ +#include "TableauState.h" + #include "BasisFactorizationFactory.h" #include "CSRMatrix.h" #include "MarabouError.h" #include "SparseUnsortedList.h" -#include "TableauState.h" TableauState::TableauState() : _A( NULL ) @@ -135,7 +136,9 @@ TableauState::~TableauState() } } -void TableauState::setDimensions( unsigned m, unsigned n, const IBasisFactorization::BasisColumnOracle &oracle ) +void TableauState::setDimensions( unsigned m, + unsigned n, + const IBasisFactorization::BasisColumnOracle &oracle ) { _m = m; _n = n; @@ -152,7 +155,8 @@ void TableauState::setDimensions( unsigned m, unsigned n, const IBasisFactorizat { _sparseColumnsOfA[i] = new SparseUnsortedList; if ( !_sparseColumnsOfA[i] ) - throw MarabouError( MarabouError::ALLOCATION_FAILED, "TableauState::sparseColumnsOfA[i]" ); + throw MarabouError( MarabouError::ALLOCATION_FAILED, + "TableauState::sparseColumnsOfA[i]" ); } _sparseRowsOfA = new SparseUnsortedList *[m]; @@ -166,7 +170,7 @@ void TableauState::setDimensions( unsigned m, unsigned n, const IBasisFactorizat throw MarabouError( MarabouError::ALLOCATION_FAILED, "TableauState::sparseRowsOfA[i]" ); } - _denseA = new double[m*n]; + _denseA = new double[m * n]; if ( !_denseA ) throw MarabouError( MarabouError::ALLOCATION_FAILED, "TableauState::denseA" ); @@ -186,7 +190,7 @@ void TableauState::setDimensions( unsigned m, unsigned n, const IBasisFactorizat if ( !_basicAssignment ) throw MarabouError( MarabouError::ALLOCATION_FAILED, "TableauState::assignment" ); - _nonBasicAssignment = new double[n-m]; + _nonBasicAssignment = new double[n - m]; if ( !_nonBasicAssignment ) throw MarabouError( MarabouError::ALLOCATION_FAILED, "TableauState::nonBasicAssignment" ); @@ -194,9 +198,10 @@ void TableauState::setDimensions( unsigned m, unsigned n, const IBasisFactorizat if ( !_basicIndexToVariable ) throw MarabouError( MarabouError::ALLOCATION_FAILED, "TableauState::basicIndexToVariable" ); - _nonBasicIndexToVariable = new unsigned[n-m]; + _nonBasicIndexToVariable = new unsigned[n - m]; if ( !_nonBasicIndexToVariable ) - throw MarabouError( MarabouError::ALLOCATION_FAILED, "TableauState::nonBasicIndexToVariable" ); + throw MarabouError( MarabouError::ALLOCATION_FAILED, + "TableauState::nonBasicIndexToVariable" ); _variableToIndex = new unsigned[n]; if ( !_variableToIndex ) diff --git a/src/engine/TableauState.h b/src/engine/TableauState.h index d54d3e4fdf..758b3111be 100644 --- a/src/engine/TableauState.h +++ b/src/engine/TableauState.h @@ -37,11 +37,13 @@ class TableauState - The current indexing - The current basis */ + public: TableauState(); ~TableauState(); - void setDimensions( unsigned m, unsigned n, const IBasisFactorization::BasisColumnOracle &oracle ); + void + setDimensions( unsigned m, unsigned n, const IBasisFactorization::BasisColumnOracle &oracle ); /* Just create the bounds array. diff --git a/src/engine/TableauStateStorageLevel.h b/src/engine/TableauStateStorageLevel.h index ef357a66dd..b870618e76 100644 --- a/src/engine/TableauStateStorageLevel.h +++ b/src/engine/TableauStateStorageLevel.h @@ -16,8 +16,7 @@ #ifndef __TableauStateStorageLevel_h__ #define __TableauStateStorageLevel_h__ -enum class TableauStateStorageLevel -{ +enum class TableauStateStorageLevel { STORE_NONE = 0, STORE_BOUNDS_ONLY = 1, STORE_ENTIRE_TABLEAU_STATE = 2, diff --git a/src/engine/Tightening.h b/src/engine/Tightening.h index 055f0b4c48..b2ff1952d5 100644 --- a/src/engine/Tightening.h +++ b/src/engine/Tightening.h @@ -21,9 +21,9 @@ class Tightening { public: - enum BoundType { - LB = 0, - UB = 1, + enum BoundType { + LB = 0, + UB = 1, }; Tightening( unsigned variable, double value, BoundType type ) @@ -33,20 +33,20 @@ class Tightening { } - /* - The variable to tighten. - */ - unsigned _variable; + /* + The variable to tighten. + */ + unsigned _variable; - /* - Its new value. - */ - double _value; + /* + Its new value. + */ + double _value; - /* - Whether the tightening tightens the - lower bound or the upper bound. - */ + /* + Whether the tightening tightens the + lower bound or the upper bound. + */ BoundType _type; /* @@ -54,18 +54,13 @@ class Tightening */ bool operator==( const Tightening &other ) const { - return - ( _variable == other._variable ) && - ( _value == other._value ) && - ( _type == other._type ); + return ( _variable == other._variable ) && ( _value == other._value ) && + ( _type == other._type ); } void dump() const { - printf( "Tightening: x%u %s %.2lf\n", - _variable, - _type == LB ? ">=" : "<=", - _value ); + printf( "Tightening: x%u %s %.2lf\n", _variable, _type == LB ? ">=" : "<=", _value ); } }; diff --git a/src/engine/main.cpp b/src/engine/main.cpp index 59d710308a..f2ad594f5a 100644 --- a/src/engine/main.cpp +++ b/src/engine/main.cpp @@ -17,7 +17,7 @@ int main( int argc, char **argv ) { - return marabouMain(argc, argv); + return marabouMain( argc, argv ); } // diff --git a/src/engine/real/ConstraintMatrixAnalyzerFactory.cpp b/src/engine/real/ConstraintMatrixAnalyzerFactory.cpp index 8864884bc7..af7e204484 100644 --- a/src/engine/real/ConstraintMatrixAnalyzerFactory.cpp +++ b/src/engine/real/ConstraintMatrixAnalyzerFactory.cpp @@ -15,18 +15,17 @@ #include "ConstraintMatrixAnalyzer.h" -namespace T +namespace T { +IConstraintMatrixAnalyzer *createConstraintMatrixAnalyzer() { - IConstraintMatrixAnalyzer *createConstraintMatrixAnalyzer() - { - return new ConstraintMatrixAnalyzer(); - } + return new ConstraintMatrixAnalyzer(); +} - void discardConstraintMatrixAnalyzer( IConstraintMatrixAnalyzer *constraintMatrixAnalyzer ) - { - delete constraintMatrixAnalyzer; - } +void discardConstraintMatrixAnalyzer( IConstraintMatrixAnalyzer *constraintMatrixAnalyzer ) +{ + delete constraintMatrixAnalyzer; } +} // namespace T // // Local Variables: diff --git a/src/engine/real/CostFunctionManagerFactory.cpp b/src/engine/real/CostFunctionManagerFactory.cpp index ef28cf0311..1e514cb146 100644 --- a/src/engine/real/CostFunctionManagerFactory.cpp +++ b/src/engine/real/CostFunctionManagerFactory.cpp @@ -17,18 +17,17 @@ class ITableau; -namespace T +namespace T { +ICostFunctionManager *createCostFunctionManager( ITableau *tableau ) { - ICostFunctionManager *createCostFunctionManager( ITableau *tableau ) - { - return new CostFunctionManager( tableau ); - } + return new CostFunctionManager( tableau ); +} - void discardCostFunctionManager( ICostFunctionManager *costFunctionManager ) - { - delete costFunctionManager; - } +void discardCostFunctionManager( ICostFunctionManager *costFunctionManager ) +{ + delete costFunctionManager; } +} // namespace T // // Local Variables: diff --git a/src/engine/real/ProjectedSteepestEdgeFactory.cpp b/src/engine/real/ProjectedSteepestEdgeFactory.cpp index 3c057f065f..365acbc936 100644 --- a/src/engine/real/ProjectedSteepestEdgeFactory.cpp +++ b/src/engine/real/ProjectedSteepestEdgeFactory.cpp @@ -15,18 +15,17 @@ #include "ProjectedSteepestEdge.h" -namespace T +namespace T { +IProjectedSteepestEdgeRule *createProjectedSteepestEdgeRule() { - IProjectedSteepestEdgeRule *createProjectedSteepestEdgeRule() - { - return new ProjectedSteepestEdgeRule(); - } + return new ProjectedSteepestEdgeRule(); +} - void discardProjectedSteepestEdgeRule( IProjectedSteepestEdgeRule *projectedSteepestEdgeRule ) - { - delete projectedSteepestEdgeRule; - } +void discardProjectedSteepestEdgeRule( IProjectedSteepestEdgeRule *projectedSteepestEdgeRule ) +{ + delete projectedSteepestEdgeRule; } +} // namespace T // // Local Variables: diff --git a/src/engine/real/RowBoundTightenerFactory.cpp b/src/engine/real/RowBoundTightenerFactory.cpp index 65d413918c..2cb76a3324 100644 --- a/src/engine/real/RowBoundTightenerFactory.cpp +++ b/src/engine/real/RowBoundTightenerFactory.cpp @@ -15,18 +15,17 @@ #include "RowBoundTightener.h" -namespace T +namespace T { +IRowBoundTightener *createRowBoundTightener( const ITableau &tableau ) { - IRowBoundTightener *createRowBoundTightener( const ITableau &tableau ) - { - return new RowBoundTightener( tableau ); - } + return new RowBoundTightener( tableau ); +} - void discardRowBoundTightener( IRowBoundTightener *rowBoundTightener ) - { - delete rowBoundTightener; - } +void discardRowBoundTightener( IRowBoundTightener *rowBoundTightener ) +{ + delete rowBoundTightener; } +} // namespace T // // Local Variables: diff --git a/src/engine/real/TableauFactory.cpp b/src/engine/real/TableauFactory.cpp index ddee8d4c45..c48e14c1b0 100644 --- a/src/engine/real/TableauFactory.cpp +++ b/src/engine/real/TableauFactory.cpp @@ -15,18 +15,17 @@ #include "Tableau.h" -namespace T +namespace T { +ITableau *createTableau( IBoundManager &boundManager ) { - ITableau *createTableau( IBoundManager &boundManager ) - { - return new Tableau( boundManager ); - } + return new Tableau( boundManager ); +} - void discardTableau( ITableau *tableau ) - { - delete tableau; - } +void discardTableau( ITableau *tableau ) +{ + delete tableau; } +} // namespace T // // Local Variables: diff --git a/src/engine/tests/MockBoundManager.h b/src/engine/tests/MockBoundManager.h index 9cb115b1f0..d98b3993f5 100644 --- a/src/engine/tests/MockBoundManager.h +++ b/src/engine/tests/MockBoundManager.h @@ -14,40 +14,38 @@ #ifndef __MockBoundManager_h__ #define __MockBoundManager_h__ -#include "IBoundManager.h" #include "FloatUtils.h" +#include "IBoundManager.h" #include "List.h" -#include "Vector.h" #include "Map.h" -#include "Tightening.h" #include "MarabouError.h" +#include "Tightening.h" +#include "Vector.h" class Tableau; class MockBoundManager : public IBoundManager { public: MockBoundManager() - : _size( 0 ) - , _lowerBounds( nullptr ) - , _upperBounds( nullptr ) - , _tightenedLower( nullptr ) - , _tightenedUpper( nullptr ) - { - }; + : _size( 0 ) + , _lowerBounds( nullptr ) + , _upperBounds( nullptr ) + , _tightenedLower( nullptr ) + , _tightenedUpper( nullptr ){}; ~MockBoundManager() { if ( _lowerBounds != nullptr ) - delete [] _lowerBounds; + delete[] _lowerBounds; if ( _upperBounds != nullptr ) - delete [] _upperBounds; + delete[] _upperBounds; if ( _tightenedLower != nullptr ) - delete [] _tightenedLower; + delete[] _tightenedLower; if ( _tightenedUpper != nullptr ) - delete [] _tightenedUpper; + delete[] _tightenedUpper; }; /* @@ -57,7 +55,7 @@ class MockBoundManager : public IBoundManager */ unsigned registerNewVariable() { - return -1; + return -1; }; /* @@ -65,16 +63,16 @@ class MockBoundManager : public IBoundManager */ void initialize( unsigned size ) { - _lowerBounds = new double[size]; - _upperBounds = new double[size]; - _tightenedUpper = new bool[size]; - _tightenedLower = new bool[size]; + _lowerBounds = new double[size]; + _upperBounds = new double[size]; + _tightenedUpper = new bool[size]; + _tightenedLower = new bool[size]; - if ( _lowerBounds == nullptr || _upperBounds == nullptr || - _tightenedLower == nullptr || _tightenedUpper == nullptr ) - throw MarabouError( MarabouError::ALLOCATION_FAILED, "MockBoundManager" ); + if ( _lowerBounds == nullptr || _upperBounds == nullptr || _tightenedLower == nullptr || + _tightenedUpper == nullptr ) + throw MarabouError( MarabouError::ALLOCATION_FAILED, "MockBoundManager" ); - _size = size; + _size = size; } /* @@ -82,7 +80,7 @@ class MockBoundManager : public IBoundManager */ unsigned getNumberOfVariables() const { - return _size; + return _size; }; double getLowerBound( unsigned variable ) const @@ -95,31 +93,31 @@ class MockBoundManager : public IBoundManager */ bool tightenLowerBound( unsigned variable, double value ) { - if ( FloatUtils::lt( getLowerBound( variable), value ) ) - { - setLowerBound( variable, value); - _tightenedLower[variable] = true; - return true; - } + if ( FloatUtils::lt( getLowerBound( variable ), value ) ) + { + setLowerBound( variable, value ); + _tightenedLower[variable] = true; + return true; + } - return false; + return false; } double getUpperBound( unsigned variable ) const { - return _upperBounds[variable]; + return _upperBounds[variable]; } bool tightenUpperBound( unsigned variable, double value ) { - if ( FloatUtils::gt( getUpperBound( variable ), value ) ) - { - setUpperBound( variable, value); - _tightenedUpper[variable] = true; - return true; - } + if ( FloatUtils::gt( getUpperBound( variable ), value ) ) + { + setUpperBound( variable, value ); + _tightenedUpper[variable] = true; + return true; + } - return false; + return false; }; /* @@ -127,39 +125,37 @@ class MockBoundManager : public IBoundManager */ bool setLowerBound( unsigned variable, double value ) { - _lowerBounds[variable] = value; - return true; + _lowerBounds[variable] = value; + return true; }; bool setUpperBound( unsigned variable, double value ) { - _upperBounds[variable] = value; - return true; + _upperBounds[variable] = value; + return true; }; - const double * getLowerBounds() const + const double *getLowerBounds() const { return _lowerBounds; }; - const double * getUpperBounds() const + const double *getUpperBounds() const { return _upperBounds; }; - /* - Obtain a list of all the bound updates since the last call to - getTightenings. - */ + /* + Obtain a list of all the bound updates since the last call to + getTightenings. + */ void getTightenings( List &tightenings ) { - for ( unsigned var = 0; var < _size; ++var ) { if ( _tightenedLower[var] ) { - tightenings.append( - Tightening( var, _lowerBounds[var], Tightening::LB ) ); + tightenings.append( Tightening( var, _lowerBounds[var], Tightening::LB ) ); _tightenedLower[var] = false; } } @@ -168,8 +164,7 @@ class MockBoundManager : public IBoundManager { if ( _tightenedUpper[var] ) { - tightenings.append( - Tightening( var, _upperBounds[var], Tightening::UB ) ); + tightenings.append( Tightening( var, _upperBounds[var], Tightening::UB ) ); _tightenedUpper[var] = false; } } @@ -192,11 +187,11 @@ class MockBoundManager : public IBoundManager */ bool consistentBounds() const { - for ( unsigned i = 0; i < _size; ++i ) - if ( !consistentBounds( i ) ) - return false; + for ( unsigned i = 0; i < _size; ++i ) + if ( !consistentBounds( i ) ) + return false; - return true; + return true; } /* @@ -205,31 +200,34 @@ class MockBoundManager : public IBoundManager */ bool consistentBounds( unsigned variable ) const { - return getLowerBound( variable ) <= getUpperBound( variable ); + return getLowerBound( variable ) <= getUpperBound( variable ); }; - void registerTableau( ITableau */* tableau */ ) + void registerTableau( ITableau * /* tableau */ ) { } - void registerRowBoundTightener( IRowBoundTightener */* rowBoundTightener */ ) + void registerRowBoundTightener( IRowBoundTightener * /* rowBoundTightener */ ) { } - const BoundExplainer* getBoundExplainer() const + const BoundExplainer *getBoundExplainer() const { return NULL; } - void copyBoundExplainerContent( const BoundExplainer* /* boundsExplanations */ ) + void copyBoundExplainerContent( const BoundExplainer * /* boundsExplanations */ ) { } - void updateBoundExplanation( const TableauRow &/* row */, bool /* isUpper */, unsigned /* var */ ) + void + updateBoundExplanation( const TableauRow & /* row */, bool /* isUpper */, unsigned /* var */ ) { } - void updateBoundExplanationSparse( const SparseUnsortedList &/* row */, bool /* isUpper */, unsigned /* var */ ) + void updateBoundExplanationSparse( const SparseUnsortedList & /* row */, + bool /* isUpper */, + unsigned /* var */ ) { } @@ -245,29 +243,32 @@ class MockBoundManager : public IBoundManager /* Map _tightenedLower; */ /* Map _tightenedUpper; */ - bool tightenLowerBound( unsigned variable, double value, const TableauRow &/* row */ ) + bool tightenLowerBound( unsigned variable, double value, const TableauRow & /* row */ ) { return tightenLowerBound( variable, value ); } - bool tightenUpperBound( unsigned variable, double value, const TableauRow &/* row */ ) + bool tightenUpperBound( unsigned variable, double value, const TableauRow & /* row */ ) { return tightenUpperBound( variable, value ); } - bool tightenLowerBound( unsigned variable, double value, const SparseUnsortedList &/* row */ ) + bool tightenLowerBound( unsigned variable, double value, const SparseUnsortedList & /* row */ ) { return tightenLowerBound( variable, value ); } - bool tightenUpperBound( unsigned variable, double value, const SparseUnsortedList &/* row */ ) + bool tightenUpperBound( unsigned variable, double value, const SparseUnsortedList & /* row */ ) { return tightenUpperBound( variable, value ); } - bool addLemmaExplanationAndTightenBound(unsigned /* var */, double /* value */, BoundType /* affectedVarBound */, - const List &/* causingVar */, BoundType /* causingVarBound */, - PiecewiseLinearFunctionType /* constraintType */ ) + bool addLemmaExplanationAndTightenBound( unsigned /* var */, + double /* value */, + BoundType /* affectedVarBound */, + const List & /* causingVar */, + BoundType /* causingVarBound */, + PiecewiseLinearFunctionType /* constraintType */ ) { return true; } @@ -288,5 +289,3 @@ class MockBoundManager : public IBoundManager }; #endif // __MockBoundManager_h__ - - diff --git a/src/engine/tests/MockConstraintMatrixAnalyzer.h b/src/engine/tests/MockConstraintMatrixAnalyzer.h index 05d824437b..54f4091f56 100644 --- a/src/engine/tests/MockConstraintMatrixAnalyzer.h +++ b/src/engine/tests/MockConstraintMatrixAnalyzer.h @@ -21,37 +21,37 @@ class MockConstraintMatrixAnalyzer : public IConstraintMatrixAnalyzer { public: - MockConstraintMatrixAnalyzer() - { - wasCreated = false; - wasDiscarded = false; + MockConstraintMatrixAnalyzer() + { + wasCreated = false; + wasDiscarded = false; } ~MockConstraintMatrixAnalyzer() { } - bool wasCreated; - bool wasDiscarded; + bool wasCreated; + bool wasDiscarded; - void mockConstructor() - { - TS_ASSERT( !wasCreated ); - wasCreated = true; - } + void mockConstructor() + { + TS_ASSERT( !wasCreated ); + wasCreated = true; + } - void mockDestructor() - { - TS_ASSERT( wasCreated ); - TS_ASSERT( !wasDiscarded ); - wasDiscarded = true; - } + void mockDestructor() + { + TS_ASSERT( wasCreated ); + TS_ASSERT( !wasDiscarded ); + wasDiscarded = true; + } - void analyze( const double */* matrix */, unsigned /* m */, unsigned /* n */ ) + void analyze( const double * /* matrix */, unsigned /* m */, unsigned /* n */ ) { } - void analyze( const SparseUnsortedList **/* matrix */, unsigned /* m */, unsigned /* n */ ) + void analyze( const SparseUnsortedList ** /* matrix */, unsigned /* m */, unsigned /* n */ ) { } diff --git a/src/engine/tests/MockConstraintMatrixAnalyzerFactory.h b/src/engine/tests/MockConstraintMatrixAnalyzerFactory.h index f1f078a713..293c364dcb 100644 --- a/src/engine/tests/MockConstraintMatrixAnalyzerFactory.h +++ b/src/engine/tests/MockConstraintMatrixAnalyzerFactory.h @@ -19,32 +19,32 @@ #include "MockConstraintMatrixAnalyzer.h" #include "T/ConstraintMatrixAnalyzerFactory.h" -class MockConstraintMatrixAnalyzerFactory : - public T::Base_createConstraintMatrixAnalyzer, - public T::Base_discardConstraintMatrixAnalyzer +class MockConstraintMatrixAnalyzerFactory + : public T::Base_createConstraintMatrixAnalyzer + , public T::Base_discardConstraintMatrixAnalyzer { public: - MockConstraintMatrixAnalyzer mockConstraintMatrixAnalyzer; - - ~MockConstraintMatrixAnalyzerFactory() - { - if ( mockConstraintMatrixAnalyzer.wasCreated ) - { - TS_ASSERT( mockConstraintMatrixAnalyzer.wasDiscarded ); - } - } - - IConstraintMatrixAnalyzer *createConstraintMatrixAnalyzer() - { - mockConstraintMatrixAnalyzer.mockConstructor(); - return &mockConstraintMatrixAnalyzer; - } - - void discardConstraintMatrixAnalyzer( IConstraintMatrixAnalyzer *constraintMatrixAnalyzer ) - { - TS_ASSERT_EQUALS( constraintMatrixAnalyzer, &mockConstraintMatrixAnalyzer ); - mockConstraintMatrixAnalyzer.mockDestructor(); - } + MockConstraintMatrixAnalyzer mockConstraintMatrixAnalyzer; + + ~MockConstraintMatrixAnalyzerFactory() + { + if ( mockConstraintMatrixAnalyzer.wasCreated ) + { + TS_ASSERT( mockConstraintMatrixAnalyzer.wasDiscarded ); + } + } + + IConstraintMatrixAnalyzer *createConstraintMatrixAnalyzer() + { + mockConstraintMatrixAnalyzer.mockConstructor(); + return &mockConstraintMatrixAnalyzer; + } + + void discardConstraintMatrixAnalyzer( IConstraintMatrixAnalyzer *constraintMatrixAnalyzer ) + { + TS_ASSERT_EQUALS( constraintMatrixAnalyzer, &mockConstraintMatrixAnalyzer ); + mockConstraintMatrixAnalyzer.mockDestructor(); + } }; #endif // __MockConstraintMatrixAnalyzerFactory_h__ diff --git a/src/engine/tests/MockCostFunctionManager.h b/src/engine/tests/MockCostFunctionManager.h index b491ed0031..78a8cc5961 100644 --- a/src/engine/tests/MockCostFunctionManager.h +++ b/src/engine/tests/MockCostFunctionManager.h @@ -24,10 +24,10 @@ class MockCostFunctionManager : public ICostFunctionManager { public: - MockCostFunctionManager() - { - wasCreated = false; - wasDiscarded = false; + MockCostFunctionManager() + { + wasCreated = false; + wasDiscarded = false; initializeWasCalled = false; lastTableau = NULL; @@ -41,24 +41,24 @@ class MockCostFunctionManager : public ICostFunctionManager delete[] nextCostFunction; } - bool wasCreated; - bool wasDiscarded; + bool wasCreated; + bool wasDiscarded; ITableau *lastTableau; - void mockConstructor( ITableau *tableau ) - { - TS_ASSERT( !wasCreated ); - wasCreated = true; + void mockConstructor( ITableau *tableau ) + { + TS_ASSERT( !wasCreated ); + wasCreated = true; lastTableau = tableau; - } + } - void mockDestructor() - { - TS_ASSERT( wasCreated ); - TS_ASSERT( !wasDiscarded ); - wasDiscarded = true; - } + void mockDestructor() + { + TS_ASSERT( wasCreated ); + TS_ASSERT( !wasDiscarded ); + wasDiscarded = true; + } bool initializeWasCalled; void initialize() @@ -81,15 +81,15 @@ class MockCostFunctionManager : public ICostFunctionManager computeCoreCostFunctionCalled = true; } - void computeCostFunction( const Map &/* heuristicCost */ ) + void computeCostFunction( const Map & /* heuristicCost */ ) { } - void computeGivenCostFunction( const Map &/* heuristicCost */ ) + void computeGivenCostFunction( const Map & /* heuristicCost */ ) { } - double computeGivenCostFunctionDirectly( const Map &/* heuristicCost */ ) + double computeGivenCostFunctionDirectly( const Map & /* heuristicCost */ ) { return 0; } @@ -107,14 +107,14 @@ class MockCostFunctionManager : public ICostFunctionManager double updateCostFunctionForPivot( unsigned /* enteringVariableIndex */, unsigned /* leavingVariableIndex */, double /* pivotElement */, - const TableauRow */* pivotRow */, - const double */* changeColumn */ - ) + const TableauRow * /* pivotRow */, + const double * /* changeColumn */ + ) { return 0; } - Map nextBasicCost; + Map nextBasicCost; double getBasicCost( unsigned basicIndex ) const { TS_ASSERT( nextBasicCost.exists( basicIndex ) ); @@ -139,10 +139,10 @@ class MockCostFunctionManager : public ICostFunctionManager { } - const SparseUnsortedList* createRowOfCostFunction() const - { - return NULL; - } + const SparseUnsortedList *createRowOfCostFunction() const + { + return NULL; + } }; #endif // __MockCostFunctionManager_h__ diff --git a/src/engine/tests/MockCostFunctionManagerFactory.h b/src/engine/tests/MockCostFunctionManagerFactory.h index f0c805b322..65564a7d55 100644 --- a/src/engine/tests/MockCostFunctionManagerFactory.h +++ b/src/engine/tests/MockCostFunctionManagerFactory.h @@ -19,32 +19,32 @@ #include "MockCostFunctionManager.h" #include "T/CostFunctionManagerFactory.h" -class MockCostFunctionManagerFactory : - public T::Base_createCostFunctionManager, - public T::Base_discardCostFunctionManager +class MockCostFunctionManagerFactory + : public T::Base_createCostFunctionManager + , public T::Base_discardCostFunctionManager { public: - MockCostFunctionManager mockCostFunctionManager; - - ~MockCostFunctionManagerFactory() - { - if ( mockCostFunctionManager.wasCreated ) - { - TS_ASSERT( mockCostFunctionManager.wasDiscarded ); - } - } - - ICostFunctionManager *createCostFunctionManager( ITableau *tableau ) - { - mockCostFunctionManager.mockConstructor( tableau ); - return &mockCostFunctionManager; - } - - void discardCostFunctionManager( ICostFunctionManager *costFunctionManager ) - { - TS_ASSERT_EQUALS( costFunctionManager, &mockCostFunctionManager ); - mockCostFunctionManager.mockDestructor(); - } + MockCostFunctionManager mockCostFunctionManager; + + ~MockCostFunctionManagerFactory() + { + if ( mockCostFunctionManager.wasCreated ) + { + TS_ASSERT( mockCostFunctionManager.wasDiscarded ); + } + } + + ICostFunctionManager *createCostFunctionManager( ITableau *tableau ) + { + mockCostFunctionManager.mockConstructor( tableau ); + return &mockCostFunctionManager; + } + + void discardCostFunctionManager( ICostFunctionManager *costFunctionManager ) + { + TS_ASSERT_EQUALS( costFunctionManager, &mockCostFunctionManager ); + mockCostFunctionManager.mockDestructor(); + } }; #endif // __MockCostFunctionManagerFactory_h__ diff --git a/src/engine/tests/MockEngine.h b/src/engine/tests/MockEngine.h index 2083b6a6db..995d3694be 100644 --- a/src/engine/tests/MockEngine.h +++ b/src/engine/tests/MockEngine.h @@ -39,21 +39,21 @@ class MockEngine : public IEngine { } - bool wasCreated; - bool wasDiscarded; - - void mockConstructor() - { - TS_ASSERT( !wasCreated ); - wasCreated = true; - } - - void mockDestructor() - { - TS_ASSERT( wasCreated ); - TS_ASSERT( !wasDiscarded ); - wasDiscarded = true; - } + bool wasCreated; + bool wasDiscarded; + + void mockConstructor() + { + TS_ASSERT( !wasCreated ); + wasCreated = true; + } + + void mockDestructor() + { + TS_ASSERT( wasCreated ); + TS_ASSERT( !wasDiscarded ); + wasDiscarded = true; + } struct Bound { @@ -92,8 +92,8 @@ class MockEngine : public IEngine } } - void postContextPopHook() {}; - void preContextPushHook() {}; + void postContextPopHook(){}; + void preContextPushHook(){}; mutable EngineState *lastStoredState; void storeState( EngineState &state, TableauStateStorageLevel /*level*/ ) const @@ -177,7 +177,7 @@ class MockEngine : public IEngine { if ( !_constraintsToSplit.empty() ) { - PiecewiseLinearConstraint * ptr = *_constraintsToSplit.begin(); + PiecewiseLinearConstraint *ptr = *_constraintsToSplit.begin(); _constraintsToSplit.erase( ptr ); return ptr; } @@ -188,11 +188,11 @@ class MockEngine : public IEngine PiecewiseLinearConstraint *pickSplitPLConstraintSnC( SnCDivideStrategy /**/ ) { if ( !_constraintsToSplit.empty() ) - { - PiecewiseLinearConstraint * ptr = *_constraintsToSplit.begin(); - _constraintsToSplit.erase( ptr ); - return ptr; - } + { + PiecewiseLinearConstraint *ptr = *_constraintsToSplit.begin(); + _constraintsToSplit.erase( ptr ); + return ptr; + } else return NULL; } @@ -200,34 +200,44 @@ class MockEngine : public IEngine bool _snc; CVC4::context::Context _context; - void applySnCSplit( PiecewiseLinearCaseSplit /*split*/, String /*queryId*/) + void applySnCSplit( PiecewiseLinearCaseSplit /*split*/, String /*queryId*/ ) { _snc = true; _context.push(); } - bool inSnCMode() const { + bool inSnCMode() const + { return _snc; } - void applyAllBoundTightenings() {}; + void applyAllBoundTightenings(){}; - bool applyAllValidConstraintCaseSplits() { return false; }; + bool applyAllValidConstraintCaseSplits() + { + return false; + }; - CVC4::context::Context &getContext() { return _context; } + CVC4::context::Context &getContext() + { + return _context; + } - bool consistentBounds() const { return true; } + bool consistentBounds() const + { + return true; + } - double explainBound( unsigned /* var */, bool /* isUpper */ ) const + double explainBound( unsigned /* var */, bool /* isUpper */ ) const { return 0.0; } - void updateGroundUpperBound(unsigned /* var */, double /* value */ ) + void updateGroundUpperBound( unsigned /* var */, double /* value */ ) { } - void updateGroundLowerBound(unsigned /*var*/, double /*value*/ ) + void updateGroundLowerBound( unsigned /*var*/, double /*value*/ ) { } @@ -241,7 +251,7 @@ class MockEngine : public IEngine return NULL; } - void setUNSATCertificateCurrentPointer( UnsatCertificateNode */* node*/ ) + void setUNSATCertificateCurrentPointer( UnsatCertificateNode * /* node*/ ) { } diff --git a/src/engine/tests/MockProjectedSteepestEdge.h b/src/engine/tests/MockProjectedSteepestEdge.h index 9b8843d07b..0e09e6f1b2 100644 --- a/src/engine/tests/MockProjectedSteepestEdge.h +++ b/src/engine/tests/MockProjectedSteepestEdge.h @@ -21,39 +21,37 @@ class MockProjectedSteepestEdgeRule : public IProjectedSteepestEdgeRule { public: - MockProjectedSteepestEdgeRule() - { - wasCreated = false; - wasDiscarded = false; + MockProjectedSteepestEdgeRule() + { + wasCreated = false; + wasDiscarded = false; } ~MockProjectedSteepestEdgeRule() { } - bool wasCreated; - bool wasDiscarded; + bool wasCreated; + bool wasDiscarded; - void mockConstructor() - { - TS_ASSERT( !wasCreated ); - wasCreated = true; - } + void mockConstructor() + { + TS_ASSERT( !wasCreated ); + wasCreated = true; + } - void mockDestructor() - { - TS_ASSERT( wasCreated ); - TS_ASSERT( !wasDiscarded ); - wasDiscarded = true; - } + void mockDestructor() + { + TS_ASSERT( wasCreated ); + TS_ASSERT( !wasDiscarded ); + wasDiscarded = true; + } void initialize( const ITableau & ) { } - bool select( ITableau &, - const List &, - const Set & ) + bool select( ITableau &, const List &, const Set & ) { return true; } diff --git a/src/engine/tests/MockProjectedSteepestEdgeFactory.h b/src/engine/tests/MockProjectedSteepestEdgeFactory.h index d9d9a0601d..d236f189d5 100644 --- a/src/engine/tests/MockProjectedSteepestEdgeFactory.h +++ b/src/engine/tests/MockProjectedSteepestEdgeFactory.h @@ -19,32 +19,32 @@ #include "MockProjectedSteepestEdge.h" #include "T/ProjectedSteepestEdgeFactory.h" -class MockProjectedSteepestEdgeRuleFactory : - public T::Base_createProjectedSteepestEdgeRule, - public T::Base_discardProjectedSteepestEdgeRule +class MockProjectedSteepestEdgeRuleFactory + : public T::Base_createProjectedSteepestEdgeRule + , public T::Base_discardProjectedSteepestEdgeRule { public: - MockProjectedSteepestEdgeRule mockProjectedSteepestEdgeRule; - - ~MockProjectedSteepestEdgeRuleFactory() - { - if ( mockProjectedSteepestEdgeRule.wasCreated ) - { - TS_ASSERT( mockProjectedSteepestEdgeRule.wasDiscarded ); - } - } - - IProjectedSteepestEdgeRule *createProjectedSteepestEdgeRule() - { - mockProjectedSteepestEdgeRule.mockConstructor(); - return &mockProjectedSteepestEdgeRule; - } - - void discardProjectedSteepestEdgeRule( IProjectedSteepestEdgeRule *projectedSteepestEdgeRule ) - { - TS_ASSERT_EQUALS( projectedSteepestEdgeRule, &mockProjectedSteepestEdgeRule ); - mockProjectedSteepestEdgeRule.mockDestructor(); - } + MockProjectedSteepestEdgeRule mockProjectedSteepestEdgeRule; + + ~MockProjectedSteepestEdgeRuleFactory() + { + if ( mockProjectedSteepestEdgeRule.wasCreated ) + { + TS_ASSERT( mockProjectedSteepestEdgeRule.wasDiscarded ); + } + } + + IProjectedSteepestEdgeRule *createProjectedSteepestEdgeRule() + { + mockProjectedSteepestEdgeRule.mockConstructor(); + return &mockProjectedSteepestEdgeRule; + } + + void discardProjectedSteepestEdgeRule( IProjectedSteepestEdgeRule *projectedSteepestEdgeRule ) + { + TS_ASSERT_EQUALS( projectedSteepestEdgeRule, &mockProjectedSteepestEdgeRule ); + mockProjectedSteepestEdgeRule.mockDestructor(); + } }; #endif // __MockProjectedSteepestEdgeFactory_h__ diff --git a/src/engine/tests/MockRowBoundTightener.h b/src/engine/tests/MockRowBoundTightener.h index c29cc99e5b..56d7c761a4 100644 --- a/src/engine/tests/MockRowBoundTightener.h +++ b/src/engine/tests/MockRowBoundTightener.h @@ -21,10 +21,10 @@ class MockRowBoundTightener : public IRowBoundTightener { public: - MockRowBoundTightener() - { - wasCreated = false; - wasDiscarded = false; + MockRowBoundTightener() + { + wasCreated = false; + wasDiscarded = false; setDimensionsWasCalled = false; } @@ -33,23 +33,23 @@ class MockRowBoundTightener : public IRowBoundTightener { } - bool wasCreated; - bool wasDiscarded; + bool wasCreated; + bool wasDiscarded; const ITableau *lastTableau; - void mockConstructor( const ITableau &tableau ) - { - TS_ASSERT( !wasCreated ); - wasCreated = true; + void mockConstructor( const ITableau &tableau ) + { + TS_ASSERT( !wasCreated ); + wasCreated = true; lastTableau = &tableau; - } + } - void mockDestructor() - { - TS_ASSERT( wasCreated ); - TS_ASSERT( !wasDiscarded ); - wasDiscarded = true; - } + void mockDestructor() + { + TS_ASSERT( wasCreated ); + TS_ASSERT( !wasDiscarded ); + wasDiscarded = true; + } bool setDimensionsWasCalled; void setDimensions() @@ -61,16 +61,36 @@ class MockRowBoundTightener : public IRowBoundTightener { } - void clear() {} - void notifyLowerBound( unsigned /* variable */, double /* bound */ ) {} - void notifyUpperBound( unsigned /* variable */, double /* bound */ ) {} - void examineInvertedBasisMatrix( bool /* untilSaturation */ ) {} - void examineConstraintMatrix( bool /* untilSaturation */ ) {} - void examinePivotRow() {} - void getRowTightenings( List &/* tightenings */ ) const {} - void setStatistics( Statistics */* statistics */ ) {} - void examineImplicitInvertedBasisMatrix( bool /* untilSaturation */ ) {} - void setBoundsPointers( const double */* lower */, const double */* upper */ ) {} + void clear() + { + } + void notifyLowerBound( unsigned /* variable */, double /* bound */ ) + { + } + void notifyUpperBound( unsigned /* variable */, double /* bound */ ) + { + } + void examineInvertedBasisMatrix( bool /* untilSaturation */ ) + { + } + void examineConstraintMatrix( bool /* untilSaturation */ ) + { + } + void examinePivotRow() + { + } + void getRowTightenings( List & /* tightenings */ ) const + { + } + void setStatistics( Statistics * /* statistics */ ) + { + } + void examineImplicitInvertedBasisMatrix( bool /* untilSaturation */ ) + { + } + void setBoundsPointers( const double * /* lower */, const double * /* upper */ ) + { + } }; #endif // __MockRowBoundTightener_h__ diff --git a/src/engine/tests/MockRowBoundTightenerFactory.h b/src/engine/tests/MockRowBoundTightenerFactory.h index 116d2f7fa0..0ff4b3f370 100644 --- a/src/engine/tests/MockRowBoundTightenerFactory.h +++ b/src/engine/tests/MockRowBoundTightenerFactory.h @@ -19,32 +19,32 @@ #include "MockRowBoundTightener.h" #include "T/RowBoundTightenerFactory.h" -class MockRowBoundTightenerFactory : - public T::Base_createRowBoundTightener, - public T::Base_discardRowBoundTightener +class MockRowBoundTightenerFactory + : public T::Base_createRowBoundTightener + , public T::Base_discardRowBoundTightener { public: - MockRowBoundTightener mockRowBoundTightener; - - ~MockRowBoundTightenerFactory() - { - if ( mockRowBoundTightener.wasCreated ) - { - TS_ASSERT( mockRowBoundTightener.wasDiscarded ); - } - } - - IRowBoundTightener *createRowBoundTightener( const ITableau &tableau ) - { - mockRowBoundTightener.mockConstructor( tableau ); - return &mockRowBoundTightener; - } - - void discardRowBoundTightener( IRowBoundTightener *rowBoundTightener ) - { - TS_ASSERT_EQUALS( rowBoundTightener, &mockRowBoundTightener ); - mockRowBoundTightener.mockDestructor(); - } + MockRowBoundTightener mockRowBoundTightener; + + ~MockRowBoundTightenerFactory() + { + if ( mockRowBoundTightener.wasCreated ) + { + TS_ASSERT( mockRowBoundTightener.wasDiscarded ); + } + } + + IRowBoundTightener *createRowBoundTightener( const ITableau &tableau ) + { + mockRowBoundTightener.mockConstructor( tableau ); + return &mockRowBoundTightener; + } + + void discardRowBoundTightener( IRowBoundTightener *rowBoundTightener ) + { + TS_ASSERT_EQUALS( rowBoundTightener, &mockRowBoundTightener ); + mockRowBoundTightener.mockDestructor(); + } }; #endif // __MockRowBoundTightenerFactory_h__ diff --git a/src/engine/tests/MockTableau.h b/src/engine/tests/MockTableau.h index 4d696c79c8..a3c2fa82f4 100644 --- a/src/engine/tests/MockTableau.h +++ b/src/engine/tests/MockTableau.h @@ -16,23 +16,23 @@ #ifndef __MockTableau_h__ #define __MockTableau_h__ -#include "MockBoundManager.h" -#include "context/context.h" #include "FloatUtils.h" #include "ITableau.h" #include "Map.h" +#include "MockBoundManager.h" #include "SparseUnsortedList.h" #include "TableauRow.h" +#include "context/context.h" #include class MockTableau : public ITableau { public: - MockTableau() - { - wasCreated = false; - wasDiscarded = false; + MockTableau() + { + wasCreated = false; + wasDiscarded = false; setDimensionsCalled = false; lastRightHandSide = NULL; @@ -128,7 +128,7 @@ class MockTableau : public ITableau lastRightHandSide = new double[m]; lastM = m; lastN = n; - lastEntries = new double[m*n]; + lastEntries = new double[m * n]; std::fill( lastEntries, lastEntries + ( n * m ), 0.0 ); nextCostFunction = new double[n - m]; @@ -149,15 +149,15 @@ class MockTableau : public ITableau void setConstraintMatrix( const double *A ) { TS_ASSERT( setDimensionsCalled ); - memcpy( lastEntries, A, sizeof(double) * lastM * lastN ); + memcpy( lastEntries, A, sizeof( double ) * lastM * lastN ); } double *lastRightHandSide; - void setRightHandSide( const double * b ) + void setRightHandSide( const double *b ) { TS_ASSERT( setDimensionsCalled ); TS_ASSERT( !initializeTableauCalled ); - memcpy( lastRightHandSide, b, sizeof(double) * lastM ); + memcpy( lastRightHandSide, b, sizeof( double ) * lastM ); } void setRightHandSide( unsigned index, double value ) @@ -205,7 +205,7 @@ class MockTableau : public ITableau Map lowerBounds; double getLowerBound( unsigned variable ) const { - //return _boundManager->getLowerBound( variable ); + // return _boundManager->getLowerBound( variable ); return lowerBounds[variable]; } @@ -218,7 +218,7 @@ class MockTableau : public ITableau Map upperBounds; double getUpperBound( unsigned variable ) const { - //return _boundManager->getLowerBound( variable ); + // return _boundManager->getLowerBound( variable ); return upperBounds[variable]; } @@ -242,21 +242,36 @@ class MockTableau : public ITableau { for ( auto it : lowerBounds.keys() ) { - if ( lowerBounds.exists(it) && - !FloatUtils::lte( lowerBounds[it], upperBounds[it] ) ) - return false; + if ( lowerBounds.exists( it ) && !FloatUtils::lte( lowerBounds[it], upperBounds[it] ) ) + return false; } return true; } - unsigned getBasicStatus( unsigned /* basic */ ) { return 0; } - unsigned getBasicStatusByIndex( unsigned /* basicIndex */ ) { return 0; } + unsigned getBasicStatus( unsigned /* basic */ ) + { + return 0; + } + unsigned getBasicStatusByIndex( unsigned /* basicIndex */ ) + { + return 0; + } - bool existsBasicOutOfBounds() const { return false; } - void computeBasicStatus() {} - void computeBasicStatus( unsigned /* basic */ ) {} - bool pickEnteringVariable( EntrySelectionStrategy */* strategy */ ) { return false; } - bool eligibleForEntry( unsigned nonBasic, const double */* costFunction */ ) const + bool existsBasicOutOfBounds() const + { + return false; + } + void computeBasicStatus() + { + } + void computeBasicStatus( unsigned /* basic */ ) + { + } + bool pickEnteringVariable( EntrySelectionStrategy * /* strategy */ ) + { + return false; + } + bool eligibleForEntry( unsigned nonBasic, const double * /* costFunction */ ) const { return mockCandidates.exists( nonBasic ); } @@ -273,8 +288,10 @@ class MockTableau : public ITableau return nextEnteringVariableIndex; } - void pickLeavingVariable() {}; - void pickLeavingVariable( double */* d */ ) {} + void pickLeavingVariable(){}; + void pickLeavingVariable( double * /* d */ ) + { + } unsigned mockLeavingVariable; void setLeavingVariableIndex( unsigned basic ) @@ -297,16 +314,28 @@ class MockTableau : public ITableau return mockLeavingVariable; } - double getChangeRatio() const { return 0; } - void setChangeRatio( double /* changeRatio */ ) {} + double getChangeRatio() const + { + return 0; + } + void setChangeRatio( double /* changeRatio */ ) + { + } - void performPivot() {} + void performPivot() + { + } bool performingFakePivot() const { return false; } - double ratioConstraintPerBasic( unsigned /* basicIndex */, double /* coefficient */, bool /* decrease */ ) { return 0;} + double ratioConstraintPerBasic( unsigned /* basicIndex */, + double /* coefficient */, + bool /* decrease */ ) + { + return 0; + } Set nextIsBasic; bool isBasic( unsigned variable ) const @@ -314,9 +343,16 @@ class MockTableau : public ITableau return nextIsBasic.exists( variable ); } - void setNonBasicAssignment( unsigned /* variable */, double /* value */, bool /* updateBasics */ ) {} - void computeCostFunction() {} - void computeReducedCost (unsigned /* variable */) {} + void + setNonBasicAssignment( unsigned /* variable */, double /* value */, bool /* updateBasics */ ) + { + } + void computeCostFunction() + { + } + void computeReducedCost( unsigned /* variable */ ) + { + } double *nextCostFunction; const double *getCostFunction() const @@ -359,7 +395,9 @@ class MockTableau : public ITableau return nextBasicTooLow.exists( basic ); } - void computeChangeColumn() {} + void computeChangeColumn() + { + } double *nextChangeColumn; const double *getChangeColumn() const @@ -382,13 +420,23 @@ class MockTableau : public ITableau return nextPivotRow; } - void computeAssignment() {} - bool checkValueWithinBounds( unsigned variable, double value ){ - return FloatUtils::gte( value, getLowerBound( variable ) ) && FloatUtils::lte( value, getUpperBound( variable ) ); + void computeAssignment() + { + } + bool checkValueWithinBounds( unsigned variable, double value ) + { + return FloatUtils::gte( value, getLowerBound( variable ) ) && + FloatUtils::lte( value, getUpperBound( variable ) ); + } + void dump() const + { + } + void dumpAssignment() + { + } + void dumpEquations() + { } - void dump() const {} - void dumpAssignment() {} - void dumpEquations() {} Map nextNonBasicIndexToVariable; unsigned nonBasicIndexToVariable( unsigned index ) const @@ -412,7 +460,7 @@ class MockTableau : public ITableau } unsigned nextAuxVar; - unsigned addEquation( const Equation &/* equation */ ) + unsigned addEquation( const Equation & /* equation */ ) { return nextAuxVar; } @@ -478,7 +526,7 @@ class MockTableau : public ITableau for ( unsigned i = 0; i < lastN; ++i ) { - temp[i] = A[row*lastN + i]; + temp[i] = A[row * lastN + i]; } result->initialize( temp, lastN ); @@ -497,13 +545,11 @@ class MockTableau : public ITableau { } - void storeState( TableauState &/* state */, - TableauStateStorageLevel /*level*/ ) const + void storeState( TableauState & /* state */, TableauStateStorageLevel /*level*/ ) const { } - void restoreState( const TableauState &/* state */, - TableauStateStorageLevel /*level*/ ) + void restoreState( const TableauState & /* state */, TableauStateStorageLevel /*level*/ ) { } @@ -519,15 +565,15 @@ class MockTableau : public ITableau tightenedUpperBounds[variable] = value; } - void setBoundsPointers( const double */*lower*/, const double */*upper*/ ) + void setBoundsPointers( const double * /*lower*/, const double * /*upper*/ ) { } - void applySplit( const PiecewiseLinearCaseSplit &/* split */) + void applySplit( const PiecewiseLinearCaseSplit & /* split */ ) { } - void registerToWatchAllVariables( VariableWatcher */* watcher */ ) + void registerToWatchAllVariables( VariableWatcher * /* watcher */ ) { } @@ -560,11 +606,11 @@ class MockTableau : public ITableau { } - void setGurobi( GurobiWrapper */* gurobi */ ) + void setGurobi( GurobiWrapper * /* gurobi */ ) { } - void setStatistics( Statistics */* statistics */ ) + void setStatistics( Statistics * /* statistics */ ) { } @@ -574,14 +620,16 @@ class MockTableau : public ITableau return b; } - void forwardTransformation( const double *, double * ) const {} + void forwardTransformation( const double *, double * ) const + { + } mutable double *lastBtranInput; double *nextBtranOutput; void backwardTransformation( const double *input, double *output ) const { - memcpy( lastBtranInput, input, lastM * sizeof(double) ); - memcpy( output, nextBtranOutput, lastM * sizeof(double) ); + memcpy( lastBtranInput, input, lastM * sizeof( double ) ); + memcpy( output, nextBtranOutput, lastM * sizeof( double ) ); } double getSumOfInfeasibilities() const @@ -624,7 +672,6 @@ class MockTableau : public ITableau double &coefficient, double &inverseCoefficient ) { - lastLinearlyDependentX1 = x1; lastLinearlyDependentX2 = x2; @@ -639,7 +686,9 @@ class MockTableau : public ITableau return 0; } - void postContextPopHook() {} + void postContextPopHook() + { + } IBoundManager *_boundManager; IBoundManager &getBoundManager() const diff --git a/src/engine/tests/MockTableauFactory.h b/src/engine/tests/MockTableauFactory.h index bcf04dd383..347dc4018c 100644 --- a/src/engine/tests/MockTableauFactory.h +++ b/src/engine/tests/MockTableauFactory.h @@ -17,36 +17,35 @@ #define __MockTableauFactory_h__ #include "BoundManager.h" - #include "MockTableau.h" #include "T/TableauFactory.h" -class MockTableauFactory : - public T::Base_createTableau, - public T::Base_discardTableau +class MockTableauFactory + : public T::Base_createTableau + , public T::Base_discardTableau { public: - MockTableau mockTableau; - - ~MockTableauFactory() - { - if ( mockTableau.wasCreated ) - { - TS_ASSERT( mockTableau.wasDiscarded ); - } - } - - ITableau *createTableau( IBoundManager &/*boundManager*/ ) - { - mockTableau.mockConstructor(); - return &mockTableau; - } - - void discardTableau( ITableau *tableau ) - { - TS_ASSERT_EQUALS( tableau, &mockTableau ); - mockTableau.mockDestructor(); - } + MockTableau mockTableau; + + ~MockTableauFactory() + { + if ( mockTableau.wasCreated ) + { + TS_ASSERT( mockTableau.wasDiscarded ); + } + } + + ITableau *createTableau( IBoundManager & /*boundManager*/ ) + { + mockTableau.mockConstructor(); + return &mockTableau; + } + + void discardTableau( ITableau *tableau ) + { + TS_ASSERT_EQUALS( tableau, &mockTableau ); + mockTableau.mockDestructor(); + } }; #endif // __MockTableauFactory_h__ diff --git a/src/engine/tests/Test_AbsoluteValueConstraint.h b/src/engine/tests/Test_AbsoluteValueConstraint.h index 59b502aa56..2b169e51e6 100644 --- a/src/engine/tests/Test_AbsoluteValueConstraint.h +++ b/src/engine/tests/Test_AbsoluteValueConstraint.h @@ -13,14 +13,14 @@ **/ -#include - #include "AbsoluteValueConstraint.h" #include "InputQuery.h" #include "MarabouError.h" #include "MockErrno.h" #include "MockTableau.h" #include "PiecewiseLinearCaseSplit.h" + +#include #include #include @@ -37,7 +37,8 @@ class TestAbsConstraint : public AbsoluteValueConstraint public: TestAbsConstraint( unsigned b, unsigned f ) : AbsoluteValueConstraint( b, f ) - {} + { + } using AbsoluteValueConstraint::getPhaseStatus; }; @@ -364,7 +365,7 @@ class AbsoluteValueConstraintTestSuite : public CxxTest::TestSuite assert_lower_upper_bound( f, b, 5, 3, 6, 5, entailedTightenings ); } - { // With BoundManager + { // With BoundManager unsigned b = 1; unsigned f = 4; @@ -442,7 +443,7 @@ class AbsoluteValueConstraintTestSuite : public CxxTest::TestSuite assert_lower_upper_bound( f, b, 8, 48, 18, 64, entailedTightenings ); } - { //With BoundManage + { // With BoundManage unsigned b = 1; unsigned f = 4; @@ -483,7 +484,7 @@ class AbsoluteValueConstraintTestSuite : public CxxTest::TestSuite assert_lower_upper_bound( f, b, 3, 1, 4, 2, entailedTightenings ); } - { // With Bound Manager + { // With Bound Manager unsigned b = 1; unsigned f = 4; @@ -555,7 +556,7 @@ class AbsoluteValueConstraintTestSuite : public CxxTest::TestSuite assert_lower_upper_bound( f, b, 3, 0, 5, 2, entailedTightenings ); } - { // With Bound Manager + { // With Bound Manager unsigned b = 1; unsigned f = 4; @@ -631,7 +632,7 @@ class AbsoluteValueConstraintTestSuite : public CxxTest::TestSuite assert_lower_upper_bound( f, b, 4, 3, 6, 5, entailedTightenings ); } - { // With Bound Manager + { // With Bound Manager unsigned b = 1; unsigned f = 4; @@ -685,7 +686,7 @@ class AbsoluteValueConstraintTestSuite : public CxxTest::TestSuite } ) ); } - { // With Bound Manager + { // With Bound Manager unsigned b = 1; unsigned f = 4; @@ -852,7 +853,7 @@ class AbsoluteValueConstraintTestSuite : public CxxTest::TestSuite void test_abs_entailed_tightenings_phase_not_fixed_f_non_negative() { - { + { unsigned b = 1; unsigned f = 4; @@ -978,67 +979,67 @@ class AbsoluteValueConstraintTestSuite : public CxxTest::TestSuite void test_abs_entailed_tightenings_negative_phase() { - unsigned b = 1; - unsigned f = 4; + unsigned b = 1; + unsigned f = 4; - AbsoluteValueConstraint abs( b, f ); - List entailedTightenings; - List::iterator it; + AbsoluteValueConstraint abs( b, f ); + List entailedTightenings; + List::iterator it; - abs.notifyLowerBound( b, -20 ); - abs.notifyUpperBound( b, -2 ); - abs.notifyLowerBound( f, 0 ); - abs.notifyUpperBound( f, 15 ); + abs.notifyLowerBound( b, -20 ); + abs.notifyUpperBound( b, -2 ); + abs.notifyLowerBound( f, 0 ); + abs.notifyUpperBound( f, 15 ); - // -20 < x_b < -2 ,0 < x_f < 15 - abs.getEntailedTightenings( entailedTightenings ); - assert_tightenings_match( entailedTightenings, - List( { - Tightening( b, -15, Tightening::LB ), - Tightening( b, 0, Tightening::UB ), - Tightening( f, 2, Tightening::LB ), - Tightening( f, 20, Tightening::UB ), - } ) ); + // -20 < x_b < -2 ,0 < x_f < 15 + abs.getEntailedTightenings( entailedTightenings ); + assert_tightenings_match( entailedTightenings, + List( { + Tightening( b, -15, Tightening::LB ), + Tightening( b, 0, Tightening::UB ), + Tightening( f, 2, Tightening::LB ), + Tightening( f, 20, Tightening::UB ), + } ) ); - entailedTightenings.clear(); + entailedTightenings.clear(); - // -20 < x_b < -2 ,7 < x_f < 15 - abs.notifyLowerBound( f, 7 ); - abs.getEntailedTightenings( entailedTightenings ); - assert_tightenings_match( entailedTightenings, - List( { - Tightening( b, -15, Tightening::LB ), - Tightening( b, -7, Tightening::UB ), - Tightening( f, 2, Tightening::LB ), - Tightening( f, 20, Tightening::UB ), - } ) ); + // -20 < x_b < -2 ,7 < x_f < 15 + abs.notifyLowerBound( f, 7 ); + abs.getEntailedTightenings( entailedTightenings ); + assert_tightenings_match( entailedTightenings, + List( { + Tightening( b, -15, Tightening::LB ), + Tightening( b, -7, Tightening::UB ), + Tightening( f, 2, Tightening::LB ), + Tightening( f, 20, Tightening::UB ), + } ) ); - entailedTightenings.clear(); + entailedTightenings.clear(); - // -12 < x_b < -2 ,7 < x_f < 15 - abs.notifyLowerBound( b, -12 ); - abs.getEntailedTightenings( entailedTightenings ); - assert_tightenings_match( entailedTightenings, - List( { - Tightening( b, -15, Tightening::LB ), - Tightening( b, -7, Tightening::UB ), - Tightening( f, 2, Tightening::LB ), - Tightening( f, 12, Tightening::UB ), - } ) ); + // -12 < x_b < -2 ,7 < x_f < 15 + abs.notifyLowerBound( b, -12 ); + abs.getEntailedTightenings( entailedTightenings ); + assert_tightenings_match( entailedTightenings, + List( { + Tightening( b, -15, Tightening::LB ), + Tightening( b, -7, Tightening::UB ), + Tightening( f, 2, Tightening::LB ), + Tightening( f, 12, Tightening::UB ), + } ) ); - entailedTightenings.clear(); + entailedTightenings.clear(); - // -12 < x_b < -8 ,7 < x_f < 15 - abs.notifyUpperBound( b, -8 ); - abs.getEntailedTightenings( entailedTightenings ); - assert_tightenings_match( entailedTightenings, - List( { - Tightening( b, -15, Tightening::LB ), - Tightening( b, -7, Tightening::UB ), - Tightening( f, 8, Tightening::LB ), - Tightening( f, 12, Tightening::UB ), - } ) ); + // -12 < x_b < -8 ,7 < x_f < 15 + abs.notifyUpperBound( b, -8 ); + abs.getEntailedTightenings( entailedTightenings ); + assert_tightenings_match( entailedTightenings, + List( { + Tightening( b, -15, Tightening::LB ), + Tightening( b, -7, Tightening::UB ), + Tightening( f, 8, Tightening::LB ), + Tightening( f, 12, Tightening::UB ), + } ) ); } void test_abs_entailed_tightenings_negative_phase_2() @@ -1067,7 +1068,7 @@ class AbsoluteValueConstraintTestSuite : public CxxTest::TestSuite } ) ); } - { // With Bound Manager + { // With Bound Manager unsigned b = 1; unsigned f = 4; @@ -1360,17 +1361,18 @@ class AbsoluteValueConstraintTestSuite : public CxxTest::TestSuite Tightening f_upper( f, fUpper, Tightening::UB ); Tightening b_lower( b, bLower, Tightening::LB ); Tightening b_upper( b, bUpper, Tightening::UB ); - for ( const auto &t : { f_lower, f_upper, b_lower, b_upper} ) + for ( const auto &t : { f_lower, f_upper, b_lower, b_upper } ) { TS_ASSERT( entailedTightenings.exists( t ) ); - if ( !entailedTightenings.exists(t) ) + if ( !entailedTightenings.exists( t ) ) { - std::cout << " Cannot find tightening ("<< fLower << bLower << fUpper << bUpper << ") : " << std::endl; - t.dump(); + std::cout << " Cannot find tightening (" << fLower << bLower << fUpper << bUpper + << ") : " << std::endl; + t.dump(); - std::cout << "Entailed tightenings: " << std::endl; - for ( auto ent : entailedTightenings) - ent.dump(); + std::cout << "Entailed tightenings: " << std::endl; + for ( auto ent : entailedTightenings ) + ent.dump(); } } } @@ -1384,7 +1386,7 @@ class AbsoluteValueConstraintTestSuite : public CxxTest::TestSuite TS_ASSERT( b.exists( it ) ); if ( !b.exists( it ) ) { - std::cout << " Cannot find tightening "<< std::endl; + std::cout << " Cannot find tightening " << std::endl; it.dump(); std::cout << "Entailed tightenings: " << std::endl; @@ -1393,7 +1395,7 @@ class AbsoluteValueConstraintTestSuite : public CxxTest::TestSuite std::cout << "Expected tightenings: " << std::endl; for ( auto ent : b ) - ent.dump(); + ent.dump(); } } } @@ -1411,8 +1413,7 @@ class AbsoluteValueConstraintTestSuite : public CxxTest::TestSuite String originalSerialized = originalAbs.serializeToString(); AbsoluteValueConstraint recoveredAbs( originalSerialized ); - TS_ASSERT_EQUALS( originalAbs.serializeToString(), - recoveredAbs.serializeToString() ); + TS_ASSERT_EQUALS( originalAbs.serializeToString(), recoveredAbs.serializeToString() ); TS_ASSERT_EQUALS( originalSerialized, "absoluteValue,7,42" ); } @@ -1438,8 +1439,7 @@ class AbsoluteValueConstraintTestSuite : public CxxTest::TestSuite TS_ASSERT( !abs.participatingVariable( posAux ) ); TS_ASSERT( !abs.participatingVariable( negAux ) ); - TS_ASSERT_THROWS_NOTHING( abs.transformToUseAuxVariables - ( ipq ) ); + TS_ASSERT_THROWS_NOTHING( abs.transformToUseAuxVariables( ipq ) ); TS_ASSERT_EQUALS( abs.getParticipatingVariables(), List( { b, f, posAux, negAux } ) ); @@ -1490,7 +1490,7 @@ class AbsoluteValueConstraintTestSuite : public CxxTest::TestSuite Tightening( posAux, 0, Tightening::UB ) ); } - { // With Bound Manager + { // With Bound Manager unsigned b = 1; unsigned f = 4; @@ -1570,15 +1570,17 @@ class AbsoluteValueConstraintTestSuite : public CxxTest::TestSuite Context context; AbsoluteValueConstraint *abs1 = new AbsoluteValueConstraint( 4, 6 ); - TS_ASSERT_EQUALS( abs1->getContext(), static_cast( nullptr ) ); - TS_ASSERT_EQUALS( abs1->getActiveStatusCDO(), static_cast*>( nullptr ) ); - TS_ASSERT_EQUALS( abs1->getPhaseStatusCDO(), static_cast*>( nullptr ) ); - TS_ASSERT_EQUALS( abs1->getInfeasibleCasesCDList(), static_cast*>( nullptr ) ); + TS_ASSERT_EQUALS( abs1->getContext(), static_cast( nullptr ) ); + TS_ASSERT_EQUALS( abs1->getActiveStatusCDO(), static_cast *>( nullptr ) ); + TS_ASSERT_EQUALS( abs1->getPhaseStatusCDO(), static_cast *>( nullptr ) ); + TS_ASSERT_EQUALS( abs1->getInfeasibleCasesCDList(), + static_cast *>( nullptr ) ); TS_ASSERT_THROWS_NOTHING( abs1->initializeCDOs( &context ) ); TS_ASSERT_EQUALS( abs1->getContext(), &context ); - TS_ASSERT_DIFFERS( abs1->getActiveStatusCDO(), static_cast*>( nullptr ) ); - TS_ASSERT_DIFFERS( abs1->getPhaseStatusCDO(), static_cast*>( nullptr ) ); - TS_ASSERT_DIFFERS( abs1->getInfeasibleCasesCDList(), static_cast*>( nullptr ) ); + TS_ASSERT_DIFFERS( abs1->getActiveStatusCDO(), static_cast *>( nullptr ) ); + TS_ASSERT_DIFFERS( abs1->getPhaseStatusCDO(), static_cast *>( nullptr ) ); + TS_ASSERT_DIFFERS( abs1->getInfeasibleCasesCDList(), + static_cast *>( nullptr ) ); bool active = false; TS_ASSERT_THROWS_NOTHING( active = abs1->isActive() ); @@ -1745,12 +1747,9 @@ class AbsoluteValueConstraintTestSuite : public CxxTest::TestSuite Map assignment; assignment[0] = -1; - TS_ASSERT_EQUALS( abs.getPhaseStatusInAssignment( assignment ), - ABS_PHASE_NEGATIVE ); + TS_ASSERT_EQUALS( abs.getPhaseStatusInAssignment( assignment ), ABS_PHASE_NEGATIVE ); assignment[0] = 15; - TS_ASSERT_EQUALS( abs.getPhaseStatusInAssignment( assignment ), - ABS_PHASE_POSITIVE ); + TS_ASSERT_EQUALS( abs.getPhaseStatusInAssignment( assignment ), ABS_PHASE_POSITIVE ); } - }; diff --git a/src/engine/tests/Test_BlandsRule.h b/src/engine/tests/Test_BlandsRule.h index c96f7b4f3c..39ee7c595e 100644 --- a/src/engine/tests/Test_BlandsRule.h +++ b/src/engine/tests/Test_BlandsRule.h @@ -13,12 +13,11 @@ **/ -#include - #include "BlandsRule.h" -#include "MockTableau.h" #include "MarabouError.h" +#include "MockTableau.h" +#include #include class MockForBlandsRule diff --git a/src/engine/tests/Test_BoundManager.h b/src/engine/tests/Test_BoundManager.h index 87e0a4aee8..6c4a8fdbbb 100644 --- a/src/engine/tests/Test_BoundManager.h +++ b/src/engine/tests/Test_BoundManager.h @@ -13,24 +13,23 @@ **/ -#include - #include "BoundManager.h" -#include "context/cdlist.h" -#include "context/context.h" #include "FloatUtils.h" #include "InfeasibleQueryException.h" #include "MockEngine.h" #include "Tightening.h" #include "Vector.h" +#include "context/cdlist.h" +#include "context/context.h" + +#include using CVC4::context::Context; class BoundManagerTestSuite : public CxxTest::TestSuite { public: - - Context * context; + Context *context; void setUp() { @@ -57,8 +56,8 @@ class BoundManagerTestSuite : public CxxTest::TestSuite { TS_ASSERT( FloatUtils::areEqual( boundManager.getLowerBound( i ), FloatUtils::negativeInfinity() ) ); - TS_ASSERT( FloatUtils::areEqual( boundManager.getUpperBound( i ), - FloatUtils::infinity() ) ); + TS_ASSERT( + FloatUtils::areEqual( boundManager.getUpperBound( i ), FloatUtils::infinity() ) ); } } @@ -77,15 +76,15 @@ class BoundManagerTestSuite : public CxxTest::TestSuite TS_ASSERT_EQUALS( boundManager.getNumberOfVariables(), 5u ); TS_ASSERT( FloatUtils::areEqual( boundManager.getLowerBound( 4 ), FloatUtils::negativeInfinity() ) ); - TS_ASSERT( FloatUtils::areEqual( boundManager.getUpperBound( 4 ), - FloatUtils::infinity() ) ); + TS_ASSERT( + FloatUtils::areEqual( boundManager.getUpperBound( 4 ), FloatUtils::infinity() ) ); TS_ASSERT_THROWS_NOTHING( boundManager.registerNewVariable() ); TS_ASSERT_THROWS_NOTHING( boundManager.registerNewVariable() ); TS_ASSERT_EQUALS( boundManager.getNumberOfVariables(), 7u ); TS_ASSERT( FloatUtils::areEqual( boundManager.getLowerBound( 6 ), FloatUtils::negativeInfinity() ) ); - TS_ASSERT( FloatUtils::areEqual( boundManager.getUpperBound( 6 ), - FloatUtils::infinity() ) ); + TS_ASSERT( + FloatUtils::areEqual( boundManager.getUpperBound( 6 ), FloatUtils::infinity() ) ); } /* @@ -123,7 +122,7 @@ class BoundManagerTestSuite : public CxxTest::TestSuite TS_ASSERT_THROWS_NOTHING( boundManager.initialize( numberOfVariables ) ); List tightenings; - TS_ASSERT_THROWS_NOTHING( boundManager.getTightenings( tightenings )); + TS_ASSERT_THROWS_NOTHING( boundManager.getTightenings( tightenings ) ); TS_ASSERT( tightenings.empty() ); TS_ASSERT_THROWS_NOTHING( boundManager.setLowerBound( 0, 1 ) ); @@ -153,103 +152,103 @@ class BoundManagerTestSuite : public CxxTest::TestSuite */ void test_bound_manager_context_interaction() { - BoundManager boundManager( *context ); + BoundManager boundManager( *context ); - unsigned numberOfVariables = 5u; + unsigned numberOfVariables = 5u; - TS_ASSERT_THROWS_NOTHING( boundManager.initialize( numberOfVariables ) ); + TS_ASSERT_THROWS_NOTHING( boundManager.initialize( numberOfVariables ) ); - double level0Lower[] = { -12.357682, 0.230001234, -333.78091231, 100.00, -9.000002354 }; - double level0Upper[] = { 15.387692, 20.301878234, 45.79159213, 120.03559, 89.53402 }; - double level1Lower[] = { -2.357682, 5.230001234, -222.87012913, 103.5682, -5.002300054 }; - double level1Upper[] = { 5.387692, 15.308798432, 26.79159213, 119.5559, 77.500002 }; - double level2Lower[] = { 2.523786, 8.231234000, -122.01291387, 111.5392, 10.002300054 }; - double level2Upper[] = { 3.738962, 8.308432000, 16.79211593, 115.9003, 57.5459822 }; + double level0Lower[] = { -12.357682, 0.230001234, -333.78091231, 100.00, -9.000002354 }; + double level0Upper[] = { 15.387692, 20.301878234, 45.79159213, 120.03559, 89.53402 }; + double level1Lower[] = { -2.357682, 5.230001234, -222.87012913, 103.5682, -5.002300054 }; + double level1Upper[] = { 5.387692, 15.308798432, 26.79159213, 119.5559, 77.500002 }; + double level2Lower[] = { 2.523786, 8.231234000, -122.01291387, 111.5392, 10.002300054 }; + double level2Upper[] = { 3.738962, 8.308432000, 16.79211593, 115.9003, 57.5459822 }; - TS_ASSERT_THROWS_NOTHING( boundManager.storeLocalBounds() ); - TS_ASSERT_THROWS_NOTHING( context->push() ); + TS_ASSERT_THROWS_NOTHING( boundManager.storeLocalBounds() ); + TS_ASSERT_THROWS_NOTHING( context->push() ); - for ( unsigned v = 0; v < numberOfVariables; ++v ) - { - TS_ASSERT_THROWS_NOTHING( boundManager.setLowerBound( v, level0Lower[v] ) ); - TS_ASSERT_THROWS_NOTHING( boundManager.setUpperBound( v, level0Upper[v] ) ); + for ( unsigned v = 0; v < numberOfVariables; ++v ) + { + TS_ASSERT_THROWS_NOTHING( boundManager.setLowerBound( v, level0Lower[v] ) ); + TS_ASSERT_THROWS_NOTHING( boundManager.setUpperBound( v, level0Upper[v] ) ); - TS_ASSERT_EQUALS( boundManager.getLowerBound( v ), level0Lower[v] ); - TS_ASSERT_EQUALS( boundManager.getUpperBound( v ), level0Upper[v] ); - } + TS_ASSERT_EQUALS( boundManager.getLowerBound( v ), level0Lower[v] ); + TS_ASSERT_EQUALS( boundManager.getUpperBound( v ), level0Upper[v] ); + } - TS_ASSERT_THROWS_NOTHING( boundManager.storeLocalBounds() ); - TS_ASSERT_THROWS_NOTHING( context->push() ); + TS_ASSERT_THROWS_NOTHING( boundManager.storeLocalBounds() ); + TS_ASSERT_THROWS_NOTHING( context->push() ); - for ( unsigned v = 0; v < numberOfVariables; ++v ) - { - TS_ASSERT_THROWS_NOTHING( boundManager.setLowerBound( v, level1Lower[v] ) ); - TS_ASSERT_THROWS_NOTHING( boundManager.setUpperBound( v, level1Upper[v] ) ); + for ( unsigned v = 0; v < numberOfVariables; ++v ) + { + TS_ASSERT_THROWS_NOTHING( boundManager.setLowerBound( v, level1Lower[v] ) ); + TS_ASSERT_THROWS_NOTHING( boundManager.setUpperBound( v, level1Upper[v] ) ); - TS_ASSERT_EQUALS( boundManager.getLowerBound( v ), level1Lower[v] ); - TS_ASSERT_EQUALS( boundManager.getUpperBound( v ), level1Upper[v] ); - } + TS_ASSERT_EQUALS( boundManager.getLowerBound( v ), level1Lower[v] ); + TS_ASSERT_EQUALS( boundManager.getUpperBound( v ), level1Upper[v] ); + } - TS_ASSERT_THROWS_NOTHING( boundManager.storeLocalBounds() ); - TS_ASSERT_THROWS_NOTHING( context->push() ); + TS_ASSERT_THROWS_NOTHING( boundManager.storeLocalBounds() ); + TS_ASSERT_THROWS_NOTHING( context->push() ); - for ( unsigned v = 0; v < numberOfVariables; ++v ) - { - TS_ASSERT_THROWS_NOTHING( boundManager.setLowerBound( v, level2Lower[v] ) ); - TS_ASSERT_THROWS_NOTHING( boundManager.setUpperBound( v, level2Upper[v] ) ); + for ( unsigned v = 0; v < numberOfVariables; ++v ) + { + TS_ASSERT_THROWS_NOTHING( boundManager.setLowerBound( v, level2Lower[v] ) ); + TS_ASSERT_THROWS_NOTHING( boundManager.setUpperBound( v, level2Upper[v] ) ); - TS_ASSERT_EQUALS( boundManager.getLowerBound( v ), level2Lower[v] ); - TS_ASSERT_EQUALS( boundManager.getUpperBound( v ), level2Upper[v] ); - } + TS_ASSERT_EQUALS( boundManager.getLowerBound( v ), level2Lower[v] ); + TS_ASSERT_EQUALS( boundManager.getUpperBound( v ), level2Upper[v] ); + } - TS_ASSERT_THROWS_NOTHING( context->pop() ); - TS_ASSERT_THROWS_NOTHING( boundManager.restoreLocalBounds() ); + TS_ASSERT_THROWS_NOTHING( context->pop() ); + TS_ASSERT_THROWS_NOTHING( boundManager.restoreLocalBounds() ); - for ( unsigned v = 0; v < numberOfVariables; ++v ) - { - TS_ASSERT_EQUALS( boundManager.getLowerBound( v ), level1Lower[v] ); - TS_ASSERT_EQUALS( boundManager.getUpperBound( v ), level1Upper[v] ); - } + for ( unsigned v = 0; v < numberOfVariables; ++v ) + { + TS_ASSERT_EQUALS( boundManager.getLowerBound( v ), level1Lower[v] ); + TS_ASSERT_EQUALS( boundManager.getUpperBound( v ), level1Upper[v] ); + } - TS_ASSERT_THROWS_NOTHING( context->pop() ); - TS_ASSERT_THROWS_NOTHING( boundManager.restoreLocalBounds() ); + TS_ASSERT_THROWS_NOTHING( context->pop() ); + TS_ASSERT_THROWS_NOTHING( boundManager.restoreLocalBounds() ); - for ( unsigned v = 0; v < numberOfVariables; ++v ) - { - TS_ASSERT_EQUALS( boundManager.getLowerBound( v ), level0Lower[v] ); - TS_ASSERT_EQUALS( boundManager.getUpperBound( v ), level0Upper[v] ); - } + for ( unsigned v = 0; v < numberOfVariables; ++v ) + { + TS_ASSERT_EQUALS( boundManager.getLowerBound( v ), level0Lower[v] ); + TS_ASSERT_EQUALS( boundManager.getUpperBound( v ), level0Upper[v] ); + } - for ( unsigned v = 0; v < numberOfVariables; ++v ) - { - TS_ASSERT_THROWS_NOTHING( boundManager.setLowerBound( v, level1Lower[v] ) ); - TS_ASSERT_THROWS_NOTHING( boundManager.setUpperBound( v, level1Upper[v] ) ); + for ( unsigned v = 0; v < numberOfVariables; ++v ) + { + TS_ASSERT_THROWS_NOTHING( boundManager.setLowerBound( v, level1Lower[v] ) ); + TS_ASSERT_THROWS_NOTHING( boundManager.setUpperBound( v, level1Upper[v] ) ); - TS_ASSERT_EQUALS( boundManager.getLowerBound( v ), level1Lower[v] ); - TS_ASSERT_EQUALS( boundManager.getUpperBound( v ), level1Upper[v] ); - } + TS_ASSERT_EQUALS( boundManager.getLowerBound( v ), level1Lower[v] ); + TS_ASSERT_EQUALS( boundManager.getUpperBound( v ), level1Upper[v] ); + } - for ( unsigned v = 0; v < numberOfVariables; ++v ) + for ( unsigned v = 0; v < numberOfVariables; ++v ) { - TS_ASSERT_THROWS_NOTHING( boundManager.setLowerBound( v, level2Lower[v] ) ); - TS_ASSERT_THROWS_NOTHING( boundManager.setUpperBound( v, level2Upper[v] ) ); + TS_ASSERT_THROWS_NOTHING( boundManager.setLowerBound( v, level2Lower[v] ) ); + TS_ASSERT_THROWS_NOTHING( boundManager.setUpperBound( v, level2Upper[v] ) ); - TS_ASSERT_EQUALS( boundManager.getLowerBound( v ), level2Lower[v] ); - TS_ASSERT_EQUALS( boundManager.getUpperBound( v ), level2Upper[v] ); + TS_ASSERT_EQUALS( boundManager.getLowerBound( v ), level2Lower[v] ); + TS_ASSERT_EQUALS( boundManager.getUpperBound( v ), level2Upper[v] ); } - TS_ASSERT_THROWS_NOTHING( context->pop() ); - TS_ASSERT_THROWS_NOTHING( boundManager.restoreLocalBounds() ); + TS_ASSERT_THROWS_NOTHING( context->pop() ); + TS_ASSERT_THROWS_NOTHING( boundManager.restoreLocalBounds() ); - for ( unsigned v = 0; v < numberOfVariables; ++v ) + for ( unsigned v = 0; v < numberOfVariables; ++v ) { - TS_ASSERT_EQUALS( boundManager.getLowerBound( v ), FloatUtils::negativeInfinity() ); - TS_ASSERT_EQUALS( boundManager.getUpperBound( v ), FloatUtils::infinity() ); + TS_ASSERT_EQUALS( boundManager.getLowerBound( v ), FloatUtils::negativeInfinity() ); + TS_ASSERT_EQUALS( boundManager.getUpperBound( v ), FloatUtils::infinity() ); } } @@ -265,7 +264,8 @@ class BoundManagerTestSuite : public CxxTest::TestSuite unsigned numberOfRows = 3u; TS_ASSERT_THROWS_NOTHING( boundManager.initialize( numberOfVariables ) ); - TS_ASSERT_THROWS_NOTHING( boundManager.initializeBoundExplainer( numberOfVariables, numberOfRows ) ); + TS_ASSERT_THROWS_NOTHING( + boundManager.initializeBoundExplainer( numberOfVariables, numberOfRows ) ); for ( unsigned i = 0; i < numberOfVariables; ++i ) { @@ -280,7 +280,7 @@ class BoundManagerTestSuite : public CxxTest::TestSuite } // Test explanation getting and setting - Vector explVec ( numberOfRows, 1 ); + Vector explVec( numberOfRows, 1 ); SparseUnsortedList expl = SparseUnsortedList( explVec.data(), explVec.size() ); SparseUnsortedList explained = SparseUnsortedList(); @@ -292,7 +292,7 @@ class BoundManagerTestSuite : public CxxTest::TestSuite TS_ASSERT( explained.getSize() == expl.getSize() ); for ( const auto &entry : expl ) - TS_ASSERT( explained.get( entry._index) == entry._value ); + TS_ASSERT( explained.get( entry._index ) == entry._value ); // Test explanation resetting boundManager.resetExplanation( 0, true ); @@ -307,7 +307,7 @@ class BoundManagerTestSuite : public CxxTest::TestSuite // Compute sparse and tableau row bounds, according to the bounds stored in boundManager double rowArr[5] = { 0, 0, 1, 2, -1 }; - SparseUnsortedList sparseRow ( rowArr, numberOfVariables ); + SparseUnsortedList sparseRow( rowArr, numberOfVariables ); TS_ASSERT( boundManager.computeSparseRowBound( sparseRow, true, 4 ) == 3 ); TableauRow tableauRow( numberOfVariables ); @@ -328,4 +328,3 @@ class BoundManagerTestSuite : public CxxTest::TestSuite // tags-file-name: "../../../TAGS" // c-basic-offset: 4 // End: - diff --git a/src/engine/tests/Test_ConstraintMatrixAnalyzer.h b/src/engine/tests/Test_ConstraintMatrixAnalyzer.h index 7edb2df211..ef35c254b6 100644 --- a/src/engine/tests/Test_ConstraintMatrixAnalyzer.h +++ b/src/engine/tests/Test_ConstraintMatrixAnalyzer.h @@ -14,12 +14,11 @@ ** [[ Add lengthier description here ]] **/ -#include - #include "ConstraintMatrixAnalyzer.h" -#include #include +#include +#include class MockForConstraintMatrixAnalyzer { @@ -29,17 +28,17 @@ class MockForConstraintMatrixAnalyzer class ConstraintMatrixAnalyzerTestSuite : public CxxTest::TestSuite { public: - MockForConstraintMatrixAnalyzer *mock; + MockForConstraintMatrixAnalyzer *mock; - void setUp() - { - TS_ASSERT( mock = new MockForConstraintMatrixAnalyzer ); - } + void setUp() + { + TS_ASSERT( mock = new MockForConstraintMatrixAnalyzer ); + } - void tearDown() - { - TS_ASSERT_THROWS_NOTHING( delete mock ); - } + void tearDown() + { + TS_ASSERT_THROWS_NOTHING( delete mock ); + } bool sameColumns( List a, Set b ) { @@ -59,9 +58,7 @@ class ConstraintMatrixAnalyzerTestSuite : public CxxTest::TestSuite { double A1[] = { - 1, 0, 0, 0, 0, - 0, 0, 1, 0, 0, - 0, 0, 0, 1, 0, + 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, }; TS_ASSERT_THROWS_NOTHING( analyzer.analyze( A1, 3, 5 ) ); @@ -73,9 +70,7 @@ class ConstraintMatrixAnalyzerTestSuite : public CxxTest::TestSuite { double A1[] = { - 1, 0, 0, 0, 0, - 0, 0, 1, 0, 0, - 0, 1, 0, 1, 0, + 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, }; TS_ASSERT_THROWS_NOTHING( analyzer.analyze( A1, 3, 5 ) ); @@ -84,17 +79,13 @@ class ConstraintMatrixAnalyzerTestSuite : public CxxTest::TestSuite Set expectedColumns1( { 0, 1, 2 } ); Set expectedColumns2( { 0, 2, 3 } ); - TS_ASSERT( sameColumns( analyzer.getIndependentColumns(), expectedColumns1 ) - || - sameColumns( analyzer.getIndependentColumns(), expectedColumns2 ) - ); + TS_ASSERT( sameColumns( analyzer.getIndependentColumns(), expectedColumns1 ) || + sameColumns( analyzer.getIndependentColumns(), expectedColumns2 ) ); } { double A1[] = { - 1, 0, 0, 0, 0, - 1, 0, 0, 0, 0, - 0, 1, 0, 2, 0, + 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 2, 0, }; TS_ASSERT_THROWS_NOTHING( analyzer.analyze( A1, 3, 5 ) ); @@ -104,17 +95,13 @@ class ConstraintMatrixAnalyzerTestSuite : public CxxTest::TestSuite Set expectedColumns1( { 0, 1 } ); Set expectedColumns2( { 0, 3 } ); - TS_ASSERT( sameColumns( analyzer.getIndependentColumns(), expectedColumns1 ) - || - sameColumns( analyzer.getIndependentColumns(), expectedColumns2 ) - ); + TS_ASSERT( sameColumns( analyzer.getIndependentColumns(), expectedColumns1 ) || + sameColumns( analyzer.getIndependentColumns(), expectedColumns2 ) ); } { double A1[] = { - 1, 1, 0, 1, 0, - 0, 0, 3, 0, 0, - 2, 2, 0, 0, 0, + 1, 1, 0, 1, 0, 0, 0, 3, 0, 0, 2, 2, 0, 0, 0, }; TS_ASSERT_THROWS_NOTHING( analyzer.analyze( A1, 3, 5 ) ); @@ -123,17 +110,13 @@ class ConstraintMatrixAnalyzerTestSuite : public CxxTest::TestSuite Set expectedColumns1( { 0, 2, 3 } ); Set expectedColumns2( { 1, 2, 3 } ); - TS_ASSERT( sameColumns( analyzer.getIndependentColumns(), expectedColumns1 ) - || - sameColumns( analyzer.getIndependentColumns(), expectedColumns2 ) - ); + TS_ASSERT( sameColumns( analyzer.getIndependentColumns(), expectedColumns1 ) || + sameColumns( analyzer.getIndependentColumns(), expectedColumns2 ) ); } { double A1[] = { - 15, 3, 0, 1, 0, - 0 , 0, -1, 1, 4, - 15, 3, -1, 2, 4, + 15, 3, 0, 1, 0, 0, 0, -1, 1, 4, 15, 3, -1, 2, 4, }; TS_ASSERT_THROWS_NOTHING( analyzer.analyze( A1, 3, 5 ) ); @@ -152,9 +135,7 @@ class ConstraintMatrixAnalyzerTestSuite : public CxxTest::TestSuite { double A1[] = { - 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; TS_ASSERT_THROWS_NOTHING( analyzer.analyze( A1, 3, 5 ) ); @@ -166,15 +147,12 @@ class ConstraintMatrixAnalyzerTestSuite : public CxxTest::TestSuite { double A1[] = { - 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, - 0, 2, 3, 14, 1, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 14, 1, }; TS_ASSERT_THROWS_NOTHING( analyzer.analyze( A1, 3, 5 ) ); - TS_ASSERT_EQUALS( analyzer.getRedundantRows(), - Set( { 0, 1 } ) ); + TS_ASSERT_EQUALS( analyzer.getRedundantRows(), Set( { 0, 1 } ) ); List columns = analyzer.getIndependentColumns(); TS_ASSERT_EQUALS( columns.size(), 1U ); diff --git a/src/engine/tests/Test_CostFunctionManager.h b/src/engine/tests/Test_CostFunctionManager.h index b2767cdc5a..b22bdb4515 100644 --- a/src/engine/tests/Test_CostFunctionManager.h +++ b/src/engine/tests/Test_CostFunctionManager.h @@ -14,13 +14,12 @@ ** [[ Add lengthier description here ]] **/ -#include - #include "CostFunctionManager.h" +#include "MarabouError.h" #include "MockErrno.h" #include "MockTableau.h" -#include "MarabouError.h" +#include #include class MockForCostFunctionManager @@ -70,7 +69,7 @@ class CostFunctionManagerTestSuite : public CxxTest::TestSuite // Prepare the intermediate information needed for cost function computation: // 1. The multipliers double multipliers[3] = { 0, 2, -3 }; - memcpy( tableau.nextBtranOutput, multipliers, sizeof(double) * 3 ); + memcpy( tableau.nextBtranOutput, multipliers, sizeof( double ) * 3 ); // 2. Mapping from non-basic indices to original variables tableau.nextNonBasicIndexToVariable[0] = 2; tableau.nextNonBasicIndexToVariable[1] = 0; @@ -93,7 +92,7 @@ class CostFunctionManagerTestSuite : public CxxTest::TestSuite tableau.lowerBounds[7] = 0; tableau.upperBounds[7] = 1; - tableau.nextValues[5] = 10; // Too high + tableau.nextValues[5] = 10; // Too high tableau.nextValues[6] = -10; // Too low tableau.nextValues[7] = 0.5; // Okay @@ -101,7 +100,7 @@ class CostFunctionManagerTestSuite : public CxxTest::TestSuite // Basic costs should be [ 1, -1, 0 ], and this should have been sent to BTRAN. double expectedBTranInput[] = { 1, -1, 0 }; - TS_ASSERT_SAME_DATA( tableau.lastBtranInput, expectedBTranInput, sizeof(double) * m ); + TS_ASSERT_SAME_DATA( tableau.lastBtranInput, expectedBTranInput, sizeof( double ) * m ); // Each entry of the cost function is a negated dot product of the multiplier vector // and the appropriate column from the constraint matrix @@ -130,7 +129,7 @@ class CostFunctionManagerTestSuite : public CxxTest::TestSuite // Prepare the intermediate information needed for cost function computation: // 1. The multipliers double multipliers[3] = { 0, 2, -3 }; - memcpy( tableau.nextBtranOutput, multipliers, sizeof(double) * 3 ); + memcpy( tableau.nextBtranOutput, multipliers, sizeof( double ) * 3 ); // 2. Mapping from non-basic indices to original variables tableau.nextNonBasicIndexToVariable[0] = 2; tableau.nextNonBasicIndexToVariable[1] = 0; @@ -152,7 +151,7 @@ class CostFunctionManagerTestSuite : public CxxTest::TestSuite tableau.lowerBounds[7] = 0; tableau.upperBounds[7] = 1; - tableau.nextValues[5] = 10; // Too high + tableau.nextValues[5] = 10; // Too high tableau.nextValues[6] = -10; // Too low tableau.nextValues[7] = 0.5; // Okay @@ -170,7 +169,7 @@ class CostFunctionManagerTestSuite : public CxxTest::TestSuite // Basic costs should be [ 2, -1, 0 ], and this should have been sent to BTRAN. double expectedBTranInput[] = { 2, -1, 0 }; - TS_ASSERT_SAME_DATA( tableau.lastBtranInput, expectedBTranInput, sizeof(double) * m ); + TS_ASSERT_SAME_DATA( tableau.lastBtranInput, expectedBTranInput, sizeof( double ) * m ); // Each entry of the cost function is a negated dot product of the multiplier vector // and the appropriate column from the constraint matrix @@ -199,7 +198,7 @@ class CostFunctionManagerTestSuite : public CxxTest::TestSuite // Prepare the intermediate information needed for cost function computation: // 1. The multipliers double multipliers[3] = { 0, 2, -3 }; - memcpy( tableau.nextBtranOutput, multipliers, sizeof(double) * 3 ); + memcpy( tableau.nextBtranOutput, multipliers, sizeof( double ) * 3 ); // 2. Mapping from non-basic indices to original variables tableau.nextNonBasicIndexToVariable[0] = 2; tableau.nextNonBasicIndexToVariable[1] = 0; @@ -233,7 +232,7 @@ class CostFunctionManagerTestSuite : public CxxTest::TestSuite // Basic costs should be [ 0, 0, 0 ], and this should have been sent to BTRAN. double expectedBTranInput[] = { 0, 0, 0 }; - TS_ASSERT_SAME_DATA( tableau.lastBtranInput, expectedBTranInput, sizeof(double) * m ); + TS_ASSERT_SAME_DATA( tableau.lastBtranInput, expectedBTranInput, sizeof( double ) * m ); // Variable 2 is basic #0 tableau.nextVariableToIndex[2] = 0; @@ -255,8 +254,7 @@ class CostFunctionManagerTestSuite : public CxxTest::TestSuite // Entry 1: multipliers * columnZero + heuristic cost TS_ASSERT_EQUALS( costFucntion[1], -( 0 - 2 - 6 ) + 4 ); - TS_ASSERT_EQUALS( manager->computeGivenCostFunctionDirectly( heuristicCost ), - 8.5 ); + TS_ASSERT_EQUALS( manager->computeGivenCostFunctionDirectly( heuristicCost ), 8.5 ); TS_ASSERT_THROWS_NOTHING( delete manager ); } diff --git a/src/engine/tests/Test_DantzigsRule.h b/src/engine/tests/Test_DantzigsRule.h index 3f3dba12b4..de52619382 100644 --- a/src/engine/tests/Test_DantzigsRule.h +++ b/src/engine/tests/Test_DantzigsRule.h @@ -13,12 +13,11 @@ **/ -#include - #include "DantzigsRule.h" -#include "MockTableau.h" #include "MarabouError.h" +#include "MockTableau.h" +#include #include class MockForDantzigsRule @@ -36,7 +35,6 @@ class DantzigsRuleTestSuite : public CxxTest::TestSuite { TS_ASSERT( mock = new MockForDantzigsRule ); TS_ASSERT( tableau = new MockTableau ); - } void tearDown() diff --git a/src/engine/tests/Test_DegradationChecker.h b/src/engine/tests/Test_DegradationChecker.h index aae28cdcb4..8ab9a8e628 100644 --- a/src/engine/tests/Test_DegradationChecker.h +++ b/src/engine/tests/Test_DegradationChecker.h @@ -14,12 +14,12 @@ ** [[ Add lengthier description here ]] **/ -#include - -#include "InputQuery.h" #include "DegradationChecker.h" +#include "InputQuery.h" #include "MockTableau.h" +#include + class MockForDegradationChecker { public: @@ -28,20 +28,20 @@ class MockForDegradationChecker class DegradationCheckerTestSuite : public CxxTest::TestSuite { public: - MockForDegradationChecker *mock; + MockForDegradationChecker *mock; MockTableau *tableau; - void setUp() - { - TS_ASSERT( mock = new MockForDegradationChecker ); + void setUp() + { + TS_ASSERT( mock = new MockForDegradationChecker ); TS_ASSERT( tableau = new MockTableau ); - } + } - void tearDown() - { - TS_ASSERT_THROWS_NOTHING( delete tableau ); - TS_ASSERT_THROWS_NOTHING( delete mock ); - } + void tearDown() + { + TS_ASSERT_THROWS_NOTHING( delete tableau ); + TS_ASSERT_THROWS_NOTHING( delete mock ); + } void test_single_equation() { diff --git a/src/engine/tests/Test_DisjunctionConstraint.h b/src/engine/tests/Test_DisjunctionConstraint.h index 3a05c4256b..e3429b6eda 100644 --- a/src/engine/tests/Test_DisjunctionConstraint.h +++ b/src/engine/tests/Test_DisjunctionConstraint.h @@ -13,16 +13,15 @@ **/ -#include - #include "DisjunctionConstraint.h" +#include "InputQuery.h" #include "MarabouError.h" #include "MockErrno.h" #include "MockTableau.h" -#include "InputQuery.h" -class MockForDisjunctionConstraint - : public MockErrno +#include + +class MockForDisjunctionConstraint : public MockErrno { public: }; @@ -35,7 +34,8 @@ class TestDisjunctionConstraint : public DisjunctionConstraint public: TestDisjunctionConstraint( const List elements ) : DisjunctionConstraint( elements ) - {} + { + } using DisjunctionConstraint::getPhaseStatus; }; @@ -322,15 +322,19 @@ class DisjunctionConstraintTestSuite : public CxxTest::TestSuite DisjunctionConstraint disjunction( caseSplits ); - TS_ASSERT_EQUALS( disjunction.getContext(), static_cast( nullptr ) ); - TS_ASSERT_EQUALS( disjunction.getActiveStatusCDO(), static_cast*>( nullptr ) ); - TS_ASSERT_EQUALS( disjunction.getPhaseStatusCDO(), static_cast*>( nullptr ) ); - TS_ASSERT_EQUALS( disjunction.getInfeasibleCasesCDList(), static_cast*>( nullptr ) ); + TS_ASSERT_EQUALS( disjunction.getContext(), static_cast( nullptr ) ); + TS_ASSERT_EQUALS( disjunction.getActiveStatusCDO(), static_cast *>( nullptr ) ); + TS_ASSERT_EQUALS( disjunction.getPhaseStatusCDO(), + static_cast *>( nullptr ) ); + TS_ASSERT_EQUALS( disjunction.getInfeasibleCasesCDList(), + static_cast *>( nullptr ) ); TS_ASSERT_THROWS_NOTHING( disjunction.initializeCDOs( &context ) ); TS_ASSERT_EQUALS( disjunction.getContext(), &context ); - TS_ASSERT_DIFFERS( disjunction.getActiveStatusCDO(), static_cast*>( nullptr ) ); - TS_ASSERT_DIFFERS( disjunction.getPhaseStatusCDO(), static_cast*>( nullptr ) ); - TS_ASSERT_DIFFERS( disjunction.getInfeasibleCasesCDList(), static_cast*>( nullptr ) ); + TS_ASSERT_DIFFERS( disjunction.getActiveStatusCDO(), static_cast *>( nullptr ) ); + TS_ASSERT_DIFFERS( disjunction.getPhaseStatusCDO(), + static_cast *>( nullptr ) ); + TS_ASSERT_DIFFERS( disjunction.getInfeasibleCasesCDList(), + static_cast *>( nullptr ) ); bool active = false; TS_ASSERT_THROWS_NOTHING( active = disjunction.isActive() ); @@ -485,8 +489,7 @@ class DisjunctionConstraintTestSuite : public CxxTest::TestSuite List casesBefore = disj->getAllCases(); List splitsBefore = disj->getCaseSplits(); - TS_ASSERT_THROWS_NOTHING( disj->transformToUseAuxVariables - ( inputQuery ) ); + TS_ASSERT_THROWS_NOTHING( disj->transformToUseAuxVariables( inputQuery ) ); List casesAfter = disj->getAllCases(); List splitsAfter = disj->getCaseSplits(); @@ -514,7 +517,7 @@ class DisjunctionConstraintTestSuite : public CxxTest::TestSuite Tightening t2( 0, 5, Tightening::UB ); Tightening t3( 3, 0, Tightening::UB ); // First aux introduced here. Tightening t4( 4, 0, Tightening::LB ); // Second aux introduced here. - for ( const auto &t : {t1, t2, t3, t4} ) + for ( const auto &t : { t1, t2, t3, t4 } ) TS_ASSERT( split->getBoundTightenings().exists( t ) ); } ++split; @@ -525,7 +528,7 @@ class DisjunctionConstraintTestSuite : public CxxTest::TestSuite Tightening t1( 0, 5, Tightening::LB ); Tightening t2( 5, 0, Tightening::UB ); // Third aux introduced here. Tightening t3( 6, 0, Tightening::LB ); // Fourth aux - for ( const auto &t : {t1, t2, t3} ) + for ( const auto &t : { t1, t2, t3 } ) TS_ASSERT( split->getBoundTightenings().exists( t ) ); } ++split; @@ -535,7 +538,7 @@ class DisjunctionConstraintTestSuite : public CxxTest::TestSuite TS_ASSERT( split->getEquations().empty() ); Tightening t1( 7, 0, Tightening::LB ); // 5th aux Tightening t2( 8, 0, Tightening::UB ); // 6th aux - for ( const auto &t : {t1, t2} ) + for ( const auto &t : { t1, t2 } ) TS_ASSERT( split->getBoundTightenings().exists( t ) ); } @@ -611,15 +614,13 @@ class DisjunctionConstraintTestSuite : public CxxTest::TestSuite String originalSerialized = disj.serializeToString(); DisjunctionConstraint recoveredDisj( originalSerialized ); - TS_ASSERT_EQUALS( disj.serializeToString(), - recoveredDisj.serializeToString() ); + TS_ASSERT_EQUALS( disj.serializeToString(), recoveredDisj.serializeToString() ); - List recoveredCaseSplits = - recoveredDisj.getCaseSplits(); + List recoveredCaseSplits = recoveredDisj.getCaseSplits(); auto split = recoveredCaseSplits.begin(); - TS_ASSERT_EQUALS( *split++, *cs1); - TS_ASSERT_EQUALS( *split++, *cs2); - TS_ASSERT_EQUALS( *split, *cs3); + TS_ASSERT_EQUALS( *split++, *cs1 ); + TS_ASSERT_EQUALS( *split++, *cs2 ); + TS_ASSERT_EQUALS( *split, *cs3 ); } void test_get_entailed_tightenings() @@ -652,9 +653,7 @@ class DisjunctionConstraintTestSuite : public CxxTest::TestSuite DisjunctionConstraint disj = DisjunctionConstraint( caseSplits ); - List expectedBounds = { - Tightening( 0, -1, Tightening::LB ) - }; + List expectedBounds = { Tightening( 0, -1, Tightening::LB ) }; List bounds; TS_ASSERT_THROWS_NOTHING( disj.getEntailedTightenings( bounds ) ); @@ -678,9 +677,7 @@ class DisjunctionConstraintTestSuite : public CxxTest::TestSuite DisjunctionConstraint disj = DisjunctionConstraint( caseSplits ); - List expectedBounds = { - Tightening( 0, 5, Tightening::UB ) - }; + List expectedBounds = { Tightening( 0, 5, Tightening::UB ) }; List bounds; TS_ASSERT_THROWS_NOTHING( disj.getEntailedTightenings( bounds ) ); @@ -706,10 +703,8 @@ class DisjunctionConstraintTestSuite : public CxxTest::TestSuite DisjunctionConstraint disj = DisjunctionConstraint( caseSplits ); - List expectedBounds = { - Tightening( 0, -1, Tightening::LB ), - Tightening( 0, 5, Tightening::UB ) - }; + List expectedBounds = { Tightening( 0, -1, Tightening::LB ), + Tightening( 0, 5, Tightening::UB ) }; List bounds; TS_ASSERT_THROWS_NOTHING( disj.getEntailedTightenings( bounds ) ); diff --git a/src/engine/tests/Test_DnCWorker.h b/src/engine/tests/Test_DnCWorker.h index c51ea35d10..48c3336e9f 100644 --- a/src/engine/tests/Test_DnCWorker.h +++ b/src/engine/tests/Test_DnCWorker.h @@ -13,17 +13,15 @@ **/ -#include - #include "DnCWorker.h" #include "MockEngine.h" +#include #include class DnCWorkerTestSuite : public CxxTest::TestSuite { public: - WorkerQueue *_workload; std::shared_ptr _engine; @@ -79,8 +77,7 @@ class DnCWorkerTestSuite : public CxxTest::TestSuite SubQuery *subQuery = new SubQuery; - auto split = std::unique_ptr - ( new PiecewiseLinearCaseSplit ); + auto split = std::unique_ptr( new PiecewiseLinearCaseSplit ); Tightening bound1( 1, -2.0, Tightening::LB ); Tightening bound2( 1, 2.0, Tightening::UB ); Tightening bound3( 2, 3.0, Tightening::LB ); @@ -125,9 +122,16 @@ class DnCWorkerTestSuite : public CxxTest::TestSuite SnCDivideStrategy divideStrategy = SnCDivideStrategy::LargestInterval; unsigned verbosity = 0; bool portfolio = false; - DnCWorker dncWorker( _workload, _engine, numUnsolvedSubQueries, - shouldQuitSolving, threadId, onlineDivides, - timeoutFactor, divideStrategy, verbosity, portfolio ); + DnCWorker dncWorker( _workload, + _engine, + numUnsolvedSubQueries, + shouldQuitSolving, + threadId, + onlineDivides, + timeoutFactor, + divideStrategy, + verbosity, + portfolio ); dncWorker.popOneSubQueryAndSolve(); TS_ASSERT( _engine->getExitCode() == IEngine::TIMEOUT ); @@ -147,12 +151,18 @@ class DnCWorkerTestSuite : public CxxTest::TestSuite createPlaceHolderSubQuery(); createPlaceHolderSubQuery(); _engine->setExitCode( IEngine::UNSAT ); - numUnsolvedSubQueries= 2; - shouldQuitSolving= false; - dncWorker = DnCWorker( _workload, _engine, numUnsolvedSubQueries, - shouldQuitSolving, threadId, onlineDivides, - timeoutFactor, divideStrategy, verbosity, - portfolio ); + numUnsolvedSubQueries = 2; + shouldQuitSolving = false; + dncWorker = DnCWorker( _workload, + _engine, + numUnsolvedSubQueries, + shouldQuitSolving, + threadId, + onlineDivides, + timeoutFactor, + divideStrategy, + verbosity, + portfolio ); dncWorker.popOneSubQueryAndSolve(); TS_ASSERT( _engine->getExitCode() == IEngine::UNSAT ); @@ -173,12 +183,18 @@ class DnCWorkerTestSuite : public CxxTest::TestSuite createPlaceHolderSubQuery(); _engine->setExitCode( IEngine::UNSAT ); - numUnsolvedSubQueries= 1; - shouldQuitSolving= false; + numUnsolvedSubQueries = 1; + shouldQuitSolving = false; - dncWorker = DnCWorker( _workload, _engine, numUnsolvedSubQueries, - shouldQuitSolving, threadId, onlineDivides, - timeoutFactor, divideStrategy, verbosity, + dncWorker = DnCWorker( _workload, + _engine, + numUnsolvedSubQueries, + shouldQuitSolving, + threadId, + onlineDivides, + timeoutFactor, + divideStrategy, + verbosity, portfolio ); dncWorker.popOneSubQueryAndSolve(); @@ -199,12 +215,18 @@ class DnCWorkerTestSuite : public CxxTest::TestSuite createPlaceHolderSubQuery(); _engine->setExitCode( IEngine::SAT ); - numUnsolvedSubQueries=( 1 ); - shouldQuitSolving=( false ); - dncWorker = DnCWorker( _workload, _engine, numUnsolvedSubQueries, - shouldQuitSolving, threadId, onlineDivides, - timeoutFactor, divideStrategy, verbosity, - portfolio); + numUnsolvedSubQueries = ( 1 ); + shouldQuitSolving = ( false ); + dncWorker = DnCWorker( _workload, + _engine, + numUnsolvedSubQueries, + shouldQuitSolving, + threadId, + onlineDivides, + timeoutFactor, + divideStrategy, + verbosity, + portfolio ); dncWorker.popOneSubQueryAndSolve(); TS_ASSERT( _engine->getExitCode() == IEngine::SAT ); @@ -223,12 +245,18 @@ class DnCWorkerTestSuite : public CxxTest::TestSuite createPlaceHolderSubQuery(); _engine->setExitCode( IEngine::QUIT_REQUESTED ); - numUnsolvedSubQueries= 1; - shouldQuitSolving = true; - dncWorker = DnCWorker( _workload, _engine, numUnsolvedSubQueries, - shouldQuitSolving, threadId, onlineDivides, - timeoutFactor, divideStrategy, verbosity, - portfolio ); + numUnsolvedSubQueries = 1; + shouldQuitSolving = true; + dncWorker = DnCWorker( _workload, + _engine, + numUnsolvedSubQueries, + shouldQuitSolving, + threadId, + onlineDivides, + timeoutFactor, + divideStrategy, + verbosity, + portfolio ); dncWorker.popOneSubQueryAndSolve(); TS_ASSERT( _engine->getExitCode() == IEngine::QUIT_REQUESTED ); TS_ASSERT( numUnsolvedSubQueries.load() == 1 ); @@ -245,13 +273,19 @@ class DnCWorkerTestSuite : public CxxTest::TestSuite createPlaceHolderSubQuery(); _engine->setExitCode( IEngine::ERROR ); - numUnsolvedSubQueries= 1; + numUnsolvedSubQueries = 1; shouldQuitSolving = false; - dncWorker = DnCWorker( _workload, _engine, numUnsolvedSubQueries, - shouldQuitSolving, threadId, onlineDivides, - timeoutFactor, divideStrategy, verbosity, - portfolio ); + dncWorker = DnCWorker( _workload, + _engine, + numUnsolvedSubQueries, + shouldQuitSolving, + threadId, + onlineDivides, + timeoutFactor, + divideStrategy, + verbosity, + portfolio ); dncWorker.popOneSubQueryAndSolve(); TS_ASSERT( _engine->getExitCode() == IEngine::ERROR ); diff --git a/src/engine/tests/Test_Engine.h b/src/engine/tests/Test_Engine.h index c54a038b22..80d6309845 100644 --- a/src/engine/tests/Test_Engine.h +++ b/src/engine/tests/Test_Engine.h @@ -13,8 +13,6 @@ **/ -#include - #include "Engine.h" #include "InputQuery.h" #include "MockConstraintMatrixAnalyzerFactory.h" @@ -27,14 +25,15 @@ #include "PiecewiseLinearCaseSplit.h" #include "ReluConstraint.h" +#include #include -class MockForEngine : - public MockTableauFactory, - public MockProjectedSteepestEdgeRuleFactory, - public MockRowBoundTightenerFactory, - public MockCostFunctionManagerFactory, - public MockConstraintMatrixAnalyzerFactory +class MockForEngine + : public MockTableauFactory + , public MockProjectedSteepestEdgeRuleFactory + , public MockRowBoundTightenerFactory + , public MockCostFunctionManagerFactory + , public MockConstraintMatrixAnalyzerFactory { public: }; @@ -141,7 +140,7 @@ class EngineTestSuite : public CxxTest::TestSuite TS_ASSERT( costFunctionManager->initializeWasCalled ); TS_ASSERT( rowTightener->setDimensionsWasCalled ); - TS_ASSERT_EQUALS( tableau->lastResizeWatchers.size(), 1U); + TS_ASSERT_EQUALS( tableau->lastResizeWatchers.size(), 1U ); TS_ASSERT_EQUALS( *( tableau->lastResizeWatchers.begin() ), rowTightener ); TS_ASSERT_EQUALS( tableau->lastCostFunctionManager, costFunctionManager ); @@ -158,21 +157,21 @@ class EngineTestSuite : public CxxTest::TestSuite TS_ASSERT_EQUALS( tableau->lastRightHandSide[1], 0 ); // Tableau entries - TS_ASSERT_EQUALS( tableau->lastEntries[(0*7) + 0], 1 ); - TS_ASSERT_EQUALS( tableau->lastEntries[(0*7) + 1], 2 ); - TS_ASSERT_EQUALS( tableau->lastEntries[(0*7) + 2], -1 ); - TS_ASSERT_EQUALS( tableau->lastEntries[(0*7) + 3], 1 ); - TS_ASSERT_EQUALS( tableau->lastEntries[(0*7) + 4], 0 ); - TS_ASSERT_EQUALS( tableau->lastEntries[(0*7) + 5], -1 ); - TS_ASSERT_EQUALS( tableau->lastEntries[(0*7) + 6], 0 ); - - TS_ASSERT_EQUALS( tableau->lastEntries[(1*7) + 0], -3 ); - TS_ASSERT_EQUALS( tableau->lastEntries[(1*7) + 1], 3 ); - TS_ASSERT_EQUALS( tableau->lastEntries[(1*7) + 2], 0 ); - TS_ASSERT_EQUALS( tableau->lastEntries[(1*7) + 3], 0 ); - TS_ASSERT_EQUALS( tableau->lastEntries[(1*7) + 4], 1 ); - TS_ASSERT_EQUALS( tableau->lastEntries[(1*7) + 5], 0 ); - TS_ASSERT_EQUALS( tableau->lastEntries[(1*7) + 6], -1 ); + TS_ASSERT_EQUALS( tableau->lastEntries[( 0 * 7 ) + 0], 1 ); + TS_ASSERT_EQUALS( tableau->lastEntries[( 0 * 7 ) + 1], 2 ); + TS_ASSERT_EQUALS( tableau->lastEntries[( 0 * 7 ) + 2], -1 ); + TS_ASSERT_EQUALS( tableau->lastEntries[( 0 * 7 ) + 3], 1 ); + TS_ASSERT_EQUALS( tableau->lastEntries[( 0 * 7 ) + 4], 0 ); + TS_ASSERT_EQUALS( tableau->lastEntries[( 0 * 7 ) + 5], -1 ); + TS_ASSERT_EQUALS( tableau->lastEntries[( 0 * 7 ) + 6], 0 ); + + TS_ASSERT_EQUALS( tableau->lastEntries[( 1 * 7 ) + 0], -3 ); + TS_ASSERT_EQUALS( tableau->lastEntries[( 1 * 7 ) + 1], 3 ); + TS_ASSERT_EQUALS( tableau->lastEntries[( 1 * 7 ) + 2], 0 ); + TS_ASSERT_EQUALS( tableau->lastEntries[( 1 * 7 ) + 3], 0 ); + TS_ASSERT_EQUALS( tableau->lastEntries[( 1 * 7 ) + 4], 1 ); + TS_ASSERT_EQUALS( tableau->lastEntries[( 1 * 7 ) + 5], 0 ); + TS_ASSERT_EQUALS( tableau->lastEntries[( 1 * 7 ) + 6], -1 ); // Lower and upper bounds TS_ASSERT( tableau->lowerBounds.exists( 0 ) ); @@ -224,33 +223,33 @@ class EngineTestSuite : public CxxTest::TestSuite TS_ASSERT_EQUALS( tableau->lastRegisteredVariableToWatcher[1].size(), 1U ); auto it = tableau->lastRegisteredVariableToWatcher[1].begin(); - auto watcher1 = ( ( ReluConstraint * ) ( * it ) )->getParticipatingVariables(); - TS_ASSERT( watcher1 == relu1->getParticipatingVariables() ); + auto watcher1 = ( (ReluConstraint *)( *it ) )->getParticipatingVariables(); + TS_ASSERT( watcher1 == relu1->getParticipatingVariables() ); TS_ASSERT_EQUALS( tableau->lastRegisteredVariableToWatcher[2].size(), 2U ); it = tableau->lastRegisteredVariableToWatcher[2].begin(); - auto watcher2 = ( ( ReluConstraint * ) ( * it ) )->getParticipatingVariables(); - it++; - auto watcher3 = ( ( ReluConstraint * ) ( * it ) )->getParticipatingVariables(); - - if ( watcher2 == relu1->getParticipatingVariables() ) - { - TS_ASSERT( watcher3 == relu2->getParticipatingVariables() ); - } - else if ( watcher2 == relu2->getParticipatingVariables() ) - { - TS_ASSERT( watcher3 == relu1->getParticipatingVariables() ); - } - else - { - TS_ASSERT( false ); - } + auto watcher2 = ( (ReluConstraint *)( *it ) )->getParticipatingVariables(); + it++; + auto watcher3 = ( (ReluConstraint *)( *it ) )->getParticipatingVariables(); + + if ( watcher2 == relu1->getParticipatingVariables() ) + { + TS_ASSERT( watcher3 == relu2->getParticipatingVariables() ); + } + else if ( watcher2 == relu2->getParticipatingVariables() ) + { + TS_ASSERT( watcher3 == relu1->getParticipatingVariables() ); + } + else + { + TS_ASSERT( false ); + } TS_ASSERT_EQUALS( tableau->lastRegisteredVariableToWatcher[4].size(), 1U ); it = tableau->lastRegisteredVariableToWatcher[4].begin(); - auto watcher4 = ( ( ReluConstraint * ) ( * it ) )->getParticipatingVariables(); + auto watcher4 = ( (ReluConstraint *)( *it ) )->getParticipatingVariables(); - TS_ASSERT( watcher4 == relu2->getParticipatingVariables() ); + TS_ASSERT( watcher4 == relu2->getParticipatingVariables() ); } void test_pick_split_pl_constraint_polarity() @@ -339,21 +338,22 @@ class EngineTestSuite : public CxxTest::TestSuite engine.processInputQuery( inputQuery, false ); PiecewiseLinearConstraint *constraintToSplit; PiecewiseLinearConstraint *constraintToSplitSnC; - constraintToSplit = engine.pickSplitPLConstraint(DivideStrategy::Polarity ); + constraintToSplit = engine.pickSplitPLConstraint( DivideStrategy::Polarity ); constraintToSplitSnC = engine.pickSplitPLConstraintSnC( SnCDivideStrategy::Polarity ); TS_ASSERT_EQUALS( constraintToSplitSnC, constraintToSplit ); TS_ASSERT( constraintToSplit ); TS_ASSERT( !constraintToSplit->phaseFixed() ); TS_ASSERT( constraintToSplit->isActive() ); - for ( const auto &constraint : engine.getInputQuery()-> - getNetworkLevelReasoner()->getConstraintsInTopologicalOrder() ) + for ( const auto &constraint : engine.getInputQuery() + ->getNetworkLevelReasoner() + ->getConstraintsInTopologicalOrder() ) { - TS_ASSERT( std::abs( ( ( ReluConstraint * ) constraintToSplit )->computePolarity() ) <= - std::abs( ( ( ReluConstraint * ) constraint )->computePolarity() ) ); + TS_ASSERT( std::abs( ( (ReluConstraint *)constraintToSplit )->computePolarity() ) <= + std::abs( ( (ReluConstraint *)constraint )->computePolarity() ) ); } - TS_ASSERT_EQUALS( 0, ( ( ReluConstraint * ) constraintToSplit )->computePolarity() ); + TS_ASSERT_EQUALS( 0, ( (ReluConstraint *)constraintToSplit )->computePolarity() ); } void test_pick_split_pl_constraint_earliest_relu() @@ -445,9 +445,10 @@ class EngineTestSuite : public CxxTest::TestSuite TS_ASSERT_EQUALS( constraintToSplitSnC, constraintToSplit ); PiecewiseLinearConstraint *firstConstraintInTopologicalOrder; - firstConstraintInTopologicalOrder = *(engine.getInputQuery()-> - getNetworkLevelReasoner()-> - getConstraintsInTopologicalOrder().begin()); + firstConstraintInTopologicalOrder = *( engine.getInputQuery() + ->getNetworkLevelReasoner() + ->getConstraintsInTopologicalOrder() + .begin() ); TS_ASSERT( firstConstraintInTopologicalOrder ); TS_ASSERT( !firstConstraintInTopologicalOrder->phaseFixed() ); @@ -534,8 +535,7 @@ class EngineTestSuite : public CxxTest::TestSuite inputQuery.setLowerBound( 9, 0 ); inputQuery.setUpperBound( 9, 5 ); - Options::get()->setString( Options::SPLITTING_STRATEGY, - "largest-interval" ); + Options::get()->setString( Options::SPLITTING_STRATEGY, "largest-interval" ); Engine engine; TS_ASSERT( inputQuery.constructNetworkLevelReasoner() ); engine.processInputQuery( inputQuery, false ); @@ -629,14 +629,15 @@ class EngineTestSuite : public CxxTest::TestSuite TS_ASSERT_EQUALS( inputQuery.getLowerBounds()[6], 2.0 ); TS_ASSERT_EQUALS( inputQuery.getUpperBounds()[6], 6.0 ); TS_ASSERT_EQUALS( inputQuery.getLowerBounds()[7], -3.0 ); - TS_ASSERT_EQUALS( inputQuery.getUpperBounds()[7], -1.0 ); + TS_ASSERT_EQUALS( inputQuery.getUpperBounds()[7], -1.0 ); TS_ASSERT_EQUALS( inputQuery.getLowerBounds()[8], 1.0 ); - TS_ASSERT_EQUALS( inputQuery.getUpperBounds()[8], 3.0 ); + TS_ASSERT_EQUALS( inputQuery.getUpperBounds()[8], 3.0 ); } void test_todo() { - TS_TRACE( "Future work: Guarantee correct behavior even when some variable is unbounded\n" ); + TS_TRACE( + "Future work: Guarantee correct behavior even when some variable is unbounded\n" ); } }; diff --git a/src/engine/tests/Test_Equation.h b/src/engine/tests/Test_Equation.h index 6b6da1fcbe..b30d3f8d0b 100644 --- a/src/engine/tests/Test_Equation.h +++ b/src/engine/tests/Test_Equation.h @@ -13,26 +13,25 @@ **/ -#include - #include "Equation.h" +#include + class EquationTestSuite : public CxxTest::TestSuite { public: - void test_remove_redundant_addends() { Equation eq; - eq.addAddend(1.5, 1); - eq.addAddend(1.5, 1); - eq.addAddend(-1, 2); - eq.addAddend(1, 2); - eq.addAddend(-0.5, 1); - eq.addAddend(0, 1); - eq.addAddend(0, 4); - eq.addAddend(3.5, 5); - eq.setScalar(1); + eq.addAddend( 1.5, 1 ); + eq.addAddend( 1.5, 1 ); + eq.addAddend( -1, 2 ); + eq.addAddend( 1, 2 ); + eq.addAddend( -0.5, 1 ); + eq.addAddend( 0, 1 ); + eq.addAddend( 0, 4 ); + eq.addAddend( 3.5, 5 ); + eq.setScalar( 1 ); TS_ASSERT_EQUALS( eq._addends.size(), 8u ); TS_ASSERT( eq.containsRedundantAddends() ); diff --git a/src/engine/tests/Test_InputQuery.h b/src/engine/tests/Test_InputQuery.h index a05aac8ba1..5a75c62588 100644 --- a/src/engine/tests/Test_InputQuery.h +++ b/src/engine/tests/Test_InputQuery.h @@ -13,18 +13,17 @@ **/ -#include - #include "Engine.h" #include "FloatUtils.h" #include "InputQuery.h" -#include "MockErrno.h" -#include "MockFileFactory.h" #include "LeakyReluConstraint.h" -#include "ReluConstraint.h" #include "MarabouError.h" +#include "MockErrno.h" +#include "MockFileFactory.h" #include "NetworkLevelReasoner.h" +#include "ReluConstraint.h" +#include #include class MockForInputQuery @@ -261,27 +260,27 @@ class InputQueryTestSuite : public CxxTest::TestSuite InputQuery *inputQuery = new InputQuery; inputQuery->setNumberOfVariables( 7 ); Equation eq1; - eq1.addAddend(1, 0); - eq1.addAddend(1, 1); - eq1.addAddend(-1, 2); - inputQuery->addEquation(eq1); + eq1.addAddend( 1, 0 ); + eq1.addAddend( 1, 1 ); + eq1.addAddend( -1, 2 ); + inputQuery->addEquation( eq1 ); Equation eq2; - eq2.addAddend(1, 0); - eq2.addAddend(-1, 1); - eq2.addAddend(-1, 3); - inputQuery->addEquation(eq2); - LeakyReluConstraint *r1 = new LeakyReluConstraint(2,4, 0.1); - LeakyReluConstraint *r2 = new LeakyReluConstraint(3,5, 0.1); - inputQuery->addPiecewiseLinearConstraint(r1); - inputQuery->addPiecewiseLinearConstraint(r2); + eq2.addAddend( 1, 0 ); + eq2.addAddend( -1, 1 ); + eq2.addAddend( -1, 3 ); + inputQuery->addEquation( eq2 ); + LeakyReluConstraint *r1 = new LeakyReluConstraint( 2, 4, 0.1 ); + LeakyReluConstraint *r2 = new LeakyReluConstraint( 3, 5, 0.1 ); + inputQuery->addPiecewiseLinearConstraint( r1 ); + inputQuery->addPiecewiseLinearConstraint( r2 ); Equation eq3; - eq3.addAddend(1, 2); - eq3.addAddend(1, 3); - eq3.addAddend(1, 4); - eq3.addAddend(-1, 6); - inputQuery->addEquation(eq3); - inputQuery->markInputVariable(0, 0); - inputQuery->markInputVariable(1, 1); + eq3.addAddend( 1, 2 ); + eq3.addAddend( 1, 3 ); + eq3.addAddend( 1, 4 ); + eq3.addAddend( -1, 6 ); + inputQuery->addEquation( eq3 ); + inputQuery->markInputVariable( 0, 0 ); + inputQuery->markInputVariable( 1, 1 ); TS_ASSERT( inputQuery->constructNetworkLevelReasoner() ); NLR::NetworkLevelReasoner *nlr = inputQuery->getNetworkLevelReasoner(); TS_ASSERT( nlr->getNumberOfLayers() == 4 ); @@ -297,7 +296,7 @@ class InputQueryTestSuite : public CxxTest::TestSuite input[0] = 2; input[1] = -3; double result = 2 - 3 + 2 + 3 - 0.1; - nlr->evaluate(input, output); + nlr->evaluate( input, output ); TS_ASSERT_EQUALS( output[0], result ); delete inputQuery; } diff --git a/src/engine/tests/Test_LargestIntervalDivider.h b/src/engine/tests/Test_LargestIntervalDivider.h index 8c5e408ae2..ea0515da13 100644 --- a/src/engine/tests/Test_LargestIntervalDivider.h +++ b/src/engine/tests/Test_LargestIntervalDivider.h @@ -13,18 +13,17 @@ **/ -#include - #include "LargestIntervalDivider.h" #include "List.h" #include "MStringf.h" #include "SubQuery.h" #include "Vector.h" +#include + class LargestIntervalDividerTestSuite : public CxxTest::TestSuite { public: - std::unique_ptr queryDivider; List inputVariables; double timeoutFactor; @@ -38,8 +37,8 @@ class LargestIntervalDividerTestSuite : public CxxTest::TestSuite timeoutFactor = 1.5; // Initiate the divider - queryDivider = std::unique_ptr - ( new LargestIntervalDivider( inputVariables ) ); + queryDivider = + std::unique_ptr( new LargestIntervalDivider( inputVariables ) ); } void tearDown() @@ -98,8 +97,8 @@ class LargestIntervalDividerTestSuite : public CxxTest::TestSuite String queryId = "mock"; unsigned timeoutInSeconds = 5; - auto previousSplit = std::unique_ptr - ( new PiecewiseLinearCaseSplit ); + auto previousSplit = + std::unique_ptr( new PiecewiseLinearCaseSplit ); Tightening bound1( 1, -2.0, Tightening::LB ); Tightening bound2( 1, 2.0, Tightening::UB ); Tightening bound3( 2, 3.0, Tightening::LB ); @@ -116,9 +115,11 @@ class LargestIntervalDividerTestSuite : public CxxTest::TestSuite // Divide the previousSplit SubQueries subQueries; - queryDivider->createSubQueries( numNewSubQueries, queryId, 0, - *previousSplit, (unsigned) - timeoutInSeconds * timeoutFactor, + queryDivider->createSubQueries( numNewSubQueries, + queryId, + 0, + *previousSplit, + (unsigned)timeoutInSeconds * timeoutFactor, subQueries ); // The following four splits should be created by the queryDivider @@ -189,15 +190,13 @@ class LargestIntervalDividerTestSuite : public CxxTest::TestSuite newSplits.append( newSplit4 ); TS_ASSERT( subQueries.size() == 4 ); - unsigned correctTimeoutInSeconds = (unsigned) ( timeoutInSeconds * - timeoutFactor ); + unsigned correctTimeoutInSeconds = (unsigned)( timeoutInSeconds * timeoutFactor ); unsigned index = 0; for ( const auto &subQuery : subQueries ) { - TS_ASSERT( subQuery->_queryId == queryId + - Stringf( "-%u", index + 1 ) ); + TS_ASSERT( subQuery->_queryId == queryId + Stringf( "-%u", index + 1 ) ); TS_ASSERT( subQuery->_depth == 1 ); - TS_ASSERT( *(subQuery->_split) == newSplits[index] ); + TS_ASSERT( *( subQuery->_split ) == newSplits[index] ); TS_ASSERT( subQuery->_timeoutInSeconds == correctTimeoutInSeconds ); ++index; diff --git a/src/engine/tests/Test_LeakyReluConstraint.h b/src/engine/tests/Test_LeakyReluConstraint.h index c585380302..132ed5af0a 100644 --- a/src/engine/tests/Test_LeakyReluConstraint.h +++ b/src/engine/tests/Test_LeakyReluConstraint.h @@ -13,8 +13,6 @@ **/ -#include - #include "InputQuery.h" #include "LeakyReluConstraint.h" #include "LinearExpression.h" @@ -24,10 +22,10 @@ #include "PiecewiseLinearCaseSplit.h" #include "context/context.h" +#include #include -class MockForLeakyReluConstraint - : public MockErrno +class MockForLeakyReluConstraint : public MockErrno { public: }; @@ -40,7 +38,8 @@ class TestLeakyReluConstraint : public LeakyReluConstraint public: TestLeakyReluConstraint( unsigned b, unsigned f, double slope ) : LeakyReluConstraint( b, f, slope ) - {} + { + } using LeakyReluConstraint::getPhaseStatus; }; @@ -353,8 +352,10 @@ class LeakyReluConstraintTestSuite : public CxxTest::TestSuite isInactiveSplitWithAux( b, f, auxVarInactive, split2 ) ); } - bool isActiveSplitWithAux( unsigned b, unsigned f, - unsigned activeAux, List::iterator &split ) + bool isActiveSplitWithAux( unsigned b, + unsigned f, + unsigned activeAux, + List::iterator &split ) { List bounds = split->getBoundTightenings(); @@ -394,8 +395,10 @@ class LeakyReluConstraintTestSuite : public CxxTest::TestSuite return true; } - bool isInactiveSplitWithAux( unsigned b, unsigned f, - unsigned inactiveAux, List::iterator &split ) + bool isInactiveSplitWithAux( unsigned b, + unsigned f, + unsigned inactiveAux, + List::iterator &split ) { List bounds = split->getBoundTightenings(); @@ -635,8 +638,7 @@ class LeakyReluConstraintTestSuite : public CxxTest::TestSuite String originalSerialized = originalLRelu.serializeToString(); LeakyReluConstraint recoveredLRelu( originalSerialized ); - TS_ASSERT_EQUALS( originalLRelu.serializeToString(), - recoveredLRelu.serializeToString() ); + TS_ASSERT_EQUALS( originalLRelu.serializeToString(), recoveredLRelu.serializeToString() ); TS_ASSERT( !originalLRelu.auxVariablesInUse() ); TS_ASSERT( !recoveredLRelu.auxVariablesInUse() ); @@ -651,16 +653,15 @@ class LeakyReluConstraintTestSuite : public CxxTest::TestSuite originalSerialized = originalLRelu.serializeToString(); LeakyReluConstraint recoveredLRelu2( originalSerialized ); - TS_ASSERT_EQUALS( originalLRelu.serializeToString(), - recoveredLRelu2.serializeToString() ); + TS_ASSERT_EQUALS( originalLRelu.serializeToString(), recoveredLRelu2.serializeToString() ); TS_ASSERT( recoveredLRelu2.auxVariablesInUse() ); TS_ASSERT_EQUALS( originalLRelu.getActiveAux(), recoveredLRelu2.getActiveAux() ); TS_ASSERT_EQUALS( originalLRelu.getInactiveAux(), recoveredLRelu2.getInactiveAux() ); } - LeakyReluConstraint prepareLeakyRelu( unsigned b, unsigned f, unsigned activeAux, - BoundManager *boundManager ) + LeakyReluConstraint + prepareLeakyRelu( unsigned b, unsigned f, unsigned activeAux, BoundManager *boundManager ) { LeakyReluConstraint lrelu( b, f, slope ); boundManager->initialize( activeAux + 2 ); @@ -706,7 +707,7 @@ class LeakyReluConstraintTestSuite : public CxxTest::TestSuite boundManager.getTightenings( tightenings ); TS_ASSERT( tightenings.empty() ); - lrelu.notifyLowerBound( f, -20 * slope); + lrelu.notifyLowerBound( f, -20 * slope ); boundManager.getTightenings( tightenings ); TS_ASSERT( tightenings.empty() ); for ( const auto &t : tightenings ) @@ -854,8 +855,8 @@ class LeakyReluConstraintTestSuite : public CxxTest::TestSuite List splits = lrelu.getCaseSplits(); TS_ASSERT_EQUALS( splits.size(), 2u ); - TS_ASSERT_EQUALS( splits.front(), lrelu.getCaseSplit( RELU_PHASE_INACTIVE ) ) ; - TS_ASSERT_EQUALS( splits.back(), lrelu.getCaseSplit( RELU_PHASE_ACTIVE ) ) ; + TS_ASSERT_EQUALS( splits.front(), lrelu.getCaseSplit( RELU_PHASE_INACTIVE ) ); + TS_ASSERT_EQUALS( splits.back(), lrelu.getCaseSplit( RELU_PHASE_ACTIVE ) ); } /* @@ -872,7 +873,6 @@ class LeakyReluConstraintTestSuite : public CxxTest::TestSuite lrelu.initializeCDOs( &context ); - TS_ASSERT_EQUALS( lrelu.getPhaseStatus(), PHASE_NOT_FIXED ); context.push(); @@ -899,16 +899,20 @@ class LeakyReluConstraintTestSuite : public CxxTest::TestSuite Context context; LeakyReluConstraint *lrelu1 = new LeakyReluConstraint( 4, 6, slope ); - TS_ASSERT_EQUALS( lrelu1->getContext(), static_cast( static_cast( nullptr ) ) ); + TS_ASSERT_EQUALS( lrelu1->getContext(), + static_cast( static_cast( nullptr ) ) ); - TS_ASSERT_EQUALS( lrelu1->getActiveStatusCDO(), static_cast*>( nullptr ) ); - TS_ASSERT_EQUALS( lrelu1->getPhaseStatusCDO(), static_cast*>( nullptr ) ); - TS_ASSERT_EQUALS( lrelu1->getInfeasibleCasesCDList(), static_cast*>( nullptr ) ); + TS_ASSERT_EQUALS( lrelu1->getActiveStatusCDO(), static_cast *>( nullptr ) ); + TS_ASSERT_EQUALS( lrelu1->getPhaseStatusCDO(), static_cast *>( nullptr ) ); + TS_ASSERT_EQUALS( lrelu1->getInfeasibleCasesCDList(), + static_cast *>( nullptr ) ); TS_ASSERT_THROWS_NOTHING( lrelu1->initializeCDOs( &context ) ); TS_ASSERT_EQUALS( lrelu1->getContext(), &context ); - TS_ASSERT_DIFFERS( lrelu1->getActiveStatusCDO(), static_cast*>( nullptr ) ); - TS_ASSERT_DIFFERS( lrelu1->getPhaseStatusCDO(), static_cast*>( nullptr ) ); - TS_ASSERT_DIFFERS( lrelu1->getInfeasibleCasesCDList(), static_cast*>( nullptr ) ); + TS_ASSERT_DIFFERS( lrelu1->getActiveStatusCDO(), static_cast *>( nullptr ) ); + TS_ASSERT_DIFFERS( lrelu1->getPhaseStatusCDO(), + static_cast *>( nullptr ) ); + TS_ASSERT_DIFFERS( lrelu1->getInfeasibleCasesCDList(), + static_cast *>( nullptr ) ); bool active = false; TS_ASSERT_THROWS_NOTHING( active = lrelu1->isActive() ); @@ -974,5 +978,4 @@ class LeakyReluConstraintTestSuite : public CxxTest::TestSuite TS_ASSERT_THROWS_NOTHING( delete lrelu1 ); } - }; diff --git a/src/engine/tests/Test_MILPEncoder.h b/src/engine/tests/Test_MILPEncoder.h index 046b339d32..81bb7eb12e 100644 --- a/src/engine/tests/Test_MILPEncoder.h +++ b/src/engine/tests/Test_MILPEncoder.h @@ -13,8 +13,8 @@ **/ -#include "GlobalConfiguration.h" #include "FloatUtils.h" +#include "GlobalConfiguration.h" #include "InputQuery.h" #include "MILPEncoder.h" #include "MarabouError.h" @@ -365,7 +365,7 @@ class MILPEncoderTestSuite : public CxxTest::TestSuite #else TS_ASSERT( true ); #endif // ENABLE_GUROBI - } + } void test_eoncode_leaky_relu_constraint() { @@ -416,9 +416,9 @@ class MILPEncoderTestSuite : public CxxTest::TestSuite tableau1.setUpperBound( 4, 1 ); Equation eq; - eq.addAddend(1, 2); - eq.addAddend(1, 3); - eq.addAddend(-1, 4); + eq.addAddend( 1, 2 ); + eq.addAddend( 1, 3 ); + eq.addAddend( -1, 4 ); inputQuery1.addEquation( eq ); double slope = 0.2; @@ -435,8 +435,8 @@ class MILPEncoderTestSuite : public CxxTest::TestSuite InputQuery inputQuery2 = inputQuery1; Equation eq1; - eq1.addAddend(1, 4); - eq1.setScalar(slope * -1 + 1); + eq1.addAddend( 1, 4 ); + eq1.setScalar( slope * -1 + 1 ); inputQuery2.addEquation( eq1 ); GurobiWrapper gurobi2; @@ -446,13 +446,13 @@ class MILPEncoderTestSuite : public CxxTest::TestSuite TS_ASSERT( gurobi2.haveFeasibleSolution() ); Map values; double dontcare; - TS_ASSERT_THROWS_NOTHING( gurobi2.extractSolution(values, dontcare ) ); - TS_ASSERT( FloatUtils::areEqual( values[Stringf("x%u", 0)], 1 ) ); - TS_ASSERT( FloatUtils::areEqual( values[Stringf("x%u", 1)], -1 ) ); + TS_ASSERT_THROWS_NOTHING( gurobi2.extractSolution( values, dontcare ) ); + TS_ASSERT( FloatUtils::areEqual( values[Stringf( "x%u", 0 )], 1 ) ); + TS_ASSERT( FloatUtils::areEqual( values[Stringf( "x%u", 1 )], -1 ) ); #else TS_ASSERT( true ); #endif // ENABLE_GUROBI - } + } void test_eoncode_leaky_relu_constraint_relax() { @@ -503,9 +503,9 @@ class MILPEncoderTestSuite : public CxxTest::TestSuite tableau1.setUpperBound( 4, 1 ); Equation eq; - eq.addAddend(1, 2); - eq.addAddend(1, 3); - eq.addAddend(-1, 4); + eq.addAddend( 1, 2 ); + eq.addAddend( 1, 3 ); + eq.addAddend( -1, 4 ); inputQuery1.addEquation( eq ); double slope = 0.2; @@ -522,8 +522,8 @@ class MILPEncoderTestSuite : public CxxTest::TestSuite InputQuery inputQuery2 = inputQuery1; Equation eq1; - eq1.addAddend(1, 4); - eq1.setScalar(slope * -1 + 1); + eq1.addAddend( 1, 4 ); + eq1.setScalar( slope * -1 + 1 ); inputQuery2.addEquation( eq1 ); GurobiWrapper gurobi2; @@ -534,7 +534,7 @@ class MILPEncoderTestSuite : public CxxTest::TestSuite #else TS_ASSERT( true ); #endif // ENABLE_GUROBI - } + } void test_encode_sigmoid_constraint_sat() { @@ -1193,7 +1193,7 @@ class MILPEncoderTestSuite : public CxxTest::TestSuite InputQuery inputQuery = InputQuery(); inputQuery.setNumberOfVariables( 4 ); - SoftmaxConstraint *softmax = new SoftmaxConstraint( {0, 1}, {2, 3} ); + SoftmaxConstraint *softmax = new SoftmaxConstraint( { 0, 1 }, { 2, 3 } ); softmax->notifyLowerBound( 0, 1.5 ); softmax->notifyUpperBound( 0, 2 ); softmax->notifyLowerBound( 1, 0 ); @@ -1758,7 +1758,7 @@ class MILPEncoderTestSuite : public CxxTest::TestSuite Map solution; double costValue; - // NOTE: the encoding for Round is sound but incomplete. + // NOTE: the encoding for Round is sound but incomplete. TS_ASSERT_THROWS_NOTHING( gurobi.extractSolution( solution, costValue ) ); TS_ASSERT( FloatUtils::areEqual( solution["x1"], 1 ) || FloatUtils::areEqual( solution["x1"], 2 ) || diff --git a/src/engine/tests/Test_MaxConstraint.h b/src/engine/tests/Test_MaxConstraint.h index 761669ddab..f088fe73a0 100644 --- a/src/engine/tests/Test_MaxConstraint.h +++ b/src/engine/tests/Test_MaxConstraint.h @@ -13,15 +13,14 @@ **/ -#include - -#include "InputQuery.h" #include "FloatUtils.h" +#include "InputQuery.h" #include "MarabouError.h" #include "MaxConstraint.h" #include "MockTableau.h" #include "PiecewiseLinearCaseSplit.h" +#include #include class MockForMaxConstraint @@ -35,9 +34,10 @@ class MockForMaxConstraint class TestMaxConstraint : public MaxConstraint { public: - TestMaxConstraint( unsigned f, const Set elements ) + TestMaxConstraint( unsigned f, const Set elements ) : MaxConstraint( f, elements ) - {} + { + } using MaxConstraint::getPhaseStatus; }; @@ -222,8 +222,7 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite ipq.setNumberOfVariables( 10 ); TS_ASSERT_EQUALS( ipq.getNumberOfVariables(), 10u ); TS_ASSERT_EQUALS( ipq.getEquations().size(), 0u ); - TS_ASSERT_THROWS_NOTHING( max.transformToUseAuxVariables - ( ipq ) ); + TS_ASSERT_THROWS_NOTHING( max.transformToUseAuxVariables( ipq ) ); TS_ASSERT_EQUALS( ipq.getNumberOfVariables(), 18u ); TS_ASSERT_EQUALS( ipq.getEquations().size(), 8u ); // f >= x2...x9 @@ -234,8 +233,8 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite { Equation eq; eq.addAddend( 1, 1 ); - eq.addAddend( -1, i + 2); // max input - eq.addAddend( -1, 10 + i); // aux + eq.addAddend( -1, i + 2 ); // max input + eq.addAddend( -1, 10 + i ); // aux eq._scalar = 0; TS_ASSERT_EQUALS( eq, *equation ); TS_ASSERT_EQUALS( ipq.getLowerBound( 10 + i ), 0 ); @@ -258,8 +257,7 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite InputQuery ipq; ipq.setNumberOfVariables( 10 ); - TS_ASSERT_THROWS_NOTHING( max.transformToUseAuxVariables - ( ipq ) ); + TS_ASSERT_THROWS_NOTHING( max.transformToUseAuxVariables( ipq ) ); TS_ASSERT_EQUALS( ipq.getNumberOfVariables(), 18u ); @@ -279,8 +277,7 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite // Since no upper bounds known for any of the variables, no bounds TS_ASSERT_EQUALS( bounds.size(), 1U ); - TS_ASSERT_EQUALS( *bounds.begin(), - Tightening( aux, 0, Tightening::UB ) ); + TS_ASSERT_EQUALS( *bounds.begin(), Tightening( aux, 0, Tightening::UB ) ); auto equations = split->getEquations(); TS_ASSERT_EQUALS( equations.size(), 0U ); @@ -299,8 +296,7 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite InputQuery ipq; ipq.setNumberOfVariables( 10 ); - TS_ASSERT_THROWS_NOTHING( max.transformToUseAuxVariables - ( ipq ) ); + TS_ASSERT_THROWS_NOTHING( max.transformToUseAuxVariables( ipq ) ); TS_ASSERT_EQUALS( ipq.getNumberOfVariables(), 18u ); @@ -315,7 +311,7 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite // set x_2 to be at least 6, others to be at most 5 max.notifyLowerBound( 2, 6 ); - for( unsigned i = 3; i < 10; i++ ) + for ( unsigned i = 3; i < 10; i++ ) max.notifyUpperBound( i, 5 ); // now, phase should be fixed to x_2; all other variables should be removed @@ -344,8 +340,7 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite MaxConstraint max( f, elements ); InputQuery ipq; ipq.setNumberOfVariables( 4 ); - TS_ASSERT_THROWS_NOTHING( max.transformToUseAuxVariables - ( ipq ) ); + TS_ASSERT_THROWS_NOTHING( max.transformToUseAuxVariables( ipq ) ); max.notifyUpperBound( 2, 8 ); max.notifyLowerBound( 2, 1 ); @@ -377,8 +372,7 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite MaxConstraint max( f, elements ); InputQuery ipq; ipq.setNumberOfVariables( 4 ); - TS_ASSERT_THROWS_NOTHING( max.transformToUseAuxVariables - ( ipq ) ); + TS_ASSERT_THROWS_NOTHING( max.transformToUseAuxVariables( ipq ) ); max.notifyLowerBound( 2, 1 ); max.notifyUpperBound( 2, 8 ); @@ -466,8 +460,7 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite MaxConstraint max3( f, elements ); InputQuery ipq; ipq.setNumberOfVariables( 10 ); - TS_ASSERT_THROWS_NOTHING( max3.transformToUseAuxVariables - ( ipq ) ); + TS_ASSERT_THROWS_NOTHING( max3.transformToUseAuxVariables( ipq ) ); TS_ASSERT( max3.constraintObsolete() ); } @@ -553,8 +546,7 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite String originalSerialized = originalMax.serializeToString(); MaxConstraint recoveredMax( originalSerialized ); - TS_ASSERT_EQUALS( originalMax.serializeToString(), - recoveredMax.serializeToString() ); + TS_ASSERT_EQUALS( originalMax.serializeToString(), recoveredMax.serializeToString() ); } void test_serialize_and_unserialize_2() @@ -575,8 +567,7 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite MaxConstraint recoveredMax( originalSerialized ); - TS_ASSERT_EQUALS( originalMax.serializeToString(), - recoveredMax.serializeToString() ); + TS_ASSERT_EQUALS( originalMax.serializeToString(), recoveredMax.serializeToString() ); } void test_phase_fixed_with_variable_elimination() @@ -591,8 +582,7 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite MaxConstraint max( f, elements ); InputQuery ipq; ipq.setNumberOfVariables( 5 ); - TS_ASSERT_THROWS_NOTHING( max.transformToUseAuxVariables - ( ipq ) ); + TS_ASSERT_THROWS_NOTHING( max.transformToUseAuxVariables( ipq ) ); TS_ASSERT_EQUALS( ipq.getNumberOfVariables(), 9u ); TS_ASSERT( !max.getAllCases().exists( MAX_PHASE_ELIMINATED ) ); @@ -619,8 +609,7 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite MaxConstraint max2( f2, elements2 ); InputQuery ipq2; ipq2.setNumberOfVariables( 45 ); - TS_ASSERT_THROWS_NOTHING( max2.transformToUseAuxVariables - ( ipq2 ) ); + TS_ASSERT_THROWS_NOTHING( max2.transformToUseAuxVariables( ipq2 ) ); TS_ASSERT_EQUALS( ipq2.getNumberOfVariables(), 49u ); TS_ASSERT( !max2.getAllCases().exists( MAX_PHASE_ELIMINATED ) ); @@ -651,8 +640,7 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite MaxConstraint max( f, elements ); InputQuery ipq; ipq.setNumberOfVariables( 5 ); - TS_ASSERT_THROWS_NOTHING( max.transformToUseAuxVariables - ( ipq ) ); + TS_ASSERT_THROWS_NOTHING( max.transformToUseAuxVariables( ipq ) ); TS_ASSERT_EQUALS( ipq.getNumberOfVariables(), 9u ); Context context; @@ -684,8 +672,7 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite MaxConstraint max2( f2, elements2 ); InputQuery ipq2; ipq2.setNumberOfVariables( 45 ); - TS_ASSERT_THROWS_NOTHING( max2.transformToUseAuxVariables - ( ipq2 ) ); + TS_ASSERT_THROWS_NOTHING( max2.transformToUseAuxVariables( ipq2 ) ); TS_ASSERT_EQUALS( ipq2.getNumberOfVariables(), 49u ); Context context2; @@ -720,8 +707,7 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite MaxConstraint max( f, elements ); InputQuery ipq; ipq.setNumberOfVariables( 6 ); - TS_ASSERT_THROWS_NOTHING( max.transformToUseAuxVariables - ( ipq ) ); + TS_ASSERT_THROWS_NOTHING( max.transformToUseAuxVariables( ipq ) ); TS_ASSERT_EQUALS( ipq.getNumberOfVariables(), 10u ); // f = max(x_2 ... x_5) @@ -743,34 +729,29 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite { List bounds = split->getBoundTightenings(); TS_ASSERT_EQUALS( bounds.size(), 1U ); - TS_ASSERT_EQUALS( *bounds.begin(), - Tightening( 6, 0 ,Tightening::UB ) ); + TS_ASSERT_EQUALS( *bounds.begin(), Tightening( 6, 0, Tightening::UB ) ); TS_ASSERT_EQUALS( split->getEquations().size(), 0U ); } ++split; { List bounds = split->getBoundTightenings(); TS_ASSERT_EQUALS( bounds.size(), 1U ); - TS_ASSERT_EQUALS( *bounds.begin(), - Tightening( 7, 0 ,Tightening::UB ) ); + TS_ASSERT_EQUALS( *bounds.begin(), Tightening( 7, 0, Tightening::UB ) ); TS_ASSERT_EQUALS( split->getEquations().size(), 0U ); } ++split; { List bounds = split->getBoundTightenings(); TS_ASSERT_EQUALS( bounds.size(), 1U ); - TS_ASSERT_EQUALS( *bounds.begin(), - Tightening( 8, 0 ,Tightening::UB ) ); + TS_ASSERT_EQUALS( *bounds.begin(), Tightening( 8, 0, Tightening::UB ) ); TS_ASSERT_EQUALS( split->getEquations().size(), 0U ); } ++split; { List bounds = split->getBoundTightenings(); TS_ASSERT_EQUALS( bounds.size(), 2U ); - TS_ASSERT_EQUALS( *bounds.begin(), - Tightening( f, 5 ,Tightening::LB ) ); - TS_ASSERT_EQUALS( *(++bounds.begin()), - Tightening( f, 5 ,Tightening::UB ) ); + TS_ASSERT_EQUALS( *bounds.begin(), Tightening( f, 5, Tightening::LB ) ); + TS_ASSERT_EQUALS( *( ++bounds.begin() ), Tightening( f, 5, Tightening::UB ) ); TS_ASSERT_EQUALS( split->getEquations().size(), 0U ); } } @@ -790,8 +771,7 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite MaxConstraint max( f, elements ); InputQuery ipq; ipq.setNumberOfVariables( 6 ); - TS_ASSERT_THROWS_NOTHING( max.transformToUseAuxVariables - ( ipq ) ); + TS_ASSERT_THROWS_NOTHING( max.transformToUseAuxVariables( ipq ) ); TS_ASSERT_EQUALS( ipq.getNumberOfVariables(), 10u ); // All input variables initially between 1 and 10 @@ -846,8 +826,7 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite MaxConstraint max2( f2, elements2 ); InputQuery ipq2; ipq2.setNumberOfVariables( 6 ); - TS_ASSERT_THROWS_NOTHING( max2.transformToUseAuxVariables - ( ipq2 ) ); + TS_ASSERT_THROWS_NOTHING( max2.transformToUseAuxVariables( ipq2 ) ); TS_ASSERT_EQUALS( ipq2.getNumberOfVariables(), 10u ); // All input variables initially between 1 and 10 @@ -919,8 +898,7 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite MaxConstraint max3( f3, elements3 ); InputQuery ipq3; ipq3.setNumberOfVariables( 6 ); - TS_ASSERT_THROWS_NOTHING( max3.transformToUseAuxVariables - ( ipq3 ) ); + TS_ASSERT_THROWS_NOTHING( max3.transformToUseAuxVariables( ipq3 ) ); TS_ASSERT_EQUALS( ipq3.getNumberOfVariables(), 10u ); // All input variables initially between 1 and 10 @@ -963,8 +941,7 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite MaxConstraint max( f, elements ); InputQuery ipq; ipq.setNumberOfVariables( 5 ); - TS_ASSERT_THROWS_NOTHING( max.transformToUseAuxVariables - ( ipq ) ); + TS_ASSERT_THROWS_NOTHING( max.transformToUseAuxVariables( ipq ) ); TS_ASSERT_EQUALS( ipq.getNumberOfVariables(), 8u ); // Eliminate variable x_4 = 2.5 @@ -1010,8 +987,7 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite max.registerTableau( &tableau ); InputQuery ipq; ipq.setNumberOfVariables( 10 ); - TS_ASSERT_THROWS_NOTHING( max.transformToUseAuxVariables - ( ipq ) ); + TS_ASSERT_THROWS_NOTHING( max.transformToUseAuxVariables( ipq ) ); TS_ASSERT_EQUALS( ipq.getNumberOfVariables(), 18u ); List participatingVariables; @@ -1054,18 +1030,19 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite MaxConstraint max( f, elements ); InputQuery ipq; ipq.setNumberOfVariables( 10 ); - TS_ASSERT_THROWS_NOTHING( max.transformToUseAuxVariables - ( ipq ) ); + TS_ASSERT_THROWS_NOTHING( max.transformToUseAuxVariables( ipq ) ); - TS_ASSERT_EQUALS( max.getContext(), static_cast( nullptr ) ); - TS_ASSERT_EQUALS( max.getActiveStatusCDO(), static_cast*>( nullptr ) ); - TS_ASSERT_EQUALS( max.getPhaseStatusCDO(), static_cast*>( nullptr ) ); - TS_ASSERT_EQUALS( max.getInfeasibleCasesCDList(), static_cast*>( nullptr ) ); + TS_ASSERT_EQUALS( max.getContext(), static_cast( nullptr ) ); + TS_ASSERT_EQUALS( max.getActiveStatusCDO(), static_cast *>( nullptr ) ); + TS_ASSERT_EQUALS( max.getPhaseStatusCDO(), static_cast *>( nullptr ) ); + TS_ASSERT_EQUALS( max.getInfeasibleCasesCDList(), + static_cast *>( nullptr ) ); TS_ASSERT_THROWS_NOTHING( max.initializeCDOs( &context ) ); TS_ASSERT_EQUALS( max.getContext(), &context ); - TS_ASSERT_DIFFERS( max.getActiveStatusCDO(), static_cast*>( nullptr ) ); - TS_ASSERT_DIFFERS( max.getPhaseStatusCDO(), static_cast*>( nullptr ) ); - TS_ASSERT_DIFFERS( max.getInfeasibleCasesCDList(), static_cast*>( nullptr ) ); + TS_ASSERT_DIFFERS( max.getActiveStatusCDO(), static_cast *>( nullptr ) ); + TS_ASSERT_DIFFERS( max.getPhaseStatusCDO(), static_cast *>( nullptr ) ); + TS_ASSERT_DIFFERS( max.getInfeasibleCasesCDList(), + static_cast *>( nullptr ) ); bool active = false; TS_ASSERT_THROWS_NOTHING( active = max.isActive() ); @@ -1093,8 +1070,7 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite MaxConstraint max( f, elements ); InputQuery ipq; ipq.setNumberOfVariables( 10 ); - TS_ASSERT_THROWS_NOTHING( max.transformToUseAuxVariables - ( ipq ) ); + TS_ASSERT_THROWS_NOTHING( max.transformToUseAuxVariables( ipq ) ); List cases = max.getAllCases(); @@ -1130,8 +1106,7 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite InputQuery ipq; ipq.setNumberOfVariables( 5 ); - TS_ASSERT_THROWS_NOTHING( max.transformToUseAuxVariables - ( ipq ) ); + TS_ASSERT_THROWS_NOTHING( max.transformToUseAuxVariables( ipq ) ); // In search phase, we initialize context-dependent structures @@ -1146,7 +1121,7 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite TS_ASSERT_EQUALS( max.numFeasibleCases(), 2u ); - context.push(); // L1 + context.push(); // L1 max.notifyUpperBound( 3, 6 ); // This should eliminate variable 3; TS_ASSERT( max.isImplication() ); @@ -1190,8 +1165,7 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite TestMaxConstraint max( f, elements ); InputQuery ipq; ipq.setNumberOfVariables( 6 ); - TS_ASSERT_THROWS_NOTHING( max.transformToUseAuxVariables - ( ipq ) ); + TS_ASSERT_THROWS_NOTHING( max.transformToUseAuxVariables( ipq ) ); TS_ASSERT_EQUALS( ipq.getNumberOfVariables(), 10u ); BoundManager bm( context ); @@ -1214,7 +1188,7 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite TS_ASSERT_EQUALS( max.numFeasibleCases(), 3u ); bm.storeLocalBounds(); - context.push(); // L1 + context.push(); // L1 max.notifyUpperBound( 3, 5 ); // This should eliminate variable 3; TS_ASSERT_EQUALS( max.numFeasibleCases(), 2u ); @@ -1260,8 +1234,7 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite InputQuery ipq; ipq.setNumberOfVariables( 5 ); - TS_ASSERT_THROWS_NOTHING( max1.transformToUseAuxVariables - ( ipq ) ); + TS_ASSERT_THROWS_NOTHING( max1.transformToUseAuxVariables( ipq ) ); TS_ASSERT_EQUALS( ipq.getNumberOfVariables(), 8u ); // element to aux: 2: 5, 3: 6, 4: 7. @@ -1293,16 +1266,14 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite // Phase fixed, should not add any cost terms. TS_ASSERT( max1.phaseFixed() ); LinearExpression cost1; - TS_ASSERT_THROWS_NOTHING( max1.getCostFunctionComponent - ( cost1, MAX_PHASE_ELIMINATED ) ); + TS_ASSERT_THROWS_NOTHING( max1.getCostFunctionComponent( cost1, MAX_PHASE_ELIMINATED ) ); TS_ASSERT_EQUALS( cost1._addends.size(), 0u ); TS_ASSERT_EQUALS( cost1._constant, 0 ); MaxConstraint max2( f, elements ); max2.registerTableau( &tableau ); - TS_ASSERT_THROWS_NOTHING( max2.transformToUseAuxVariables - ( ipq ) ); + TS_ASSERT_THROWS_NOTHING( max2.transformToUseAuxVariables( ipq ) ); TS_ASSERT_EQUALS( ipq.getNumberOfVariables(), 11u ); // element to aux: 2: 8, 3: 9, 4: 10. @@ -1332,14 +1303,12 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite // Phase not fixed, can add cost terms to eligible phases. TS_ASSERT( !max2.phaseFixed() ); LinearExpression cost2; - TS_ASSERT_THROWS_NOTHING( max2.getCostFunctionComponent - ( cost2, MAX_PHASE_ELIMINATED ) ); + TS_ASSERT_THROWS_NOTHING( max2.getCostFunctionComponent( cost2, MAX_PHASE_ELIMINATED ) ); TS_ASSERT_EQUALS( cost2._addends.size(), 1u ); TS_ASSERT_EQUALS( cost2._addends[1], 1 ); TS_ASSERT_EQUALS( cost2._constant, -1 ); - TS_ASSERT_THROWS_NOTHING( max2.getCostFunctionComponent - ( cost2, MAX_PHASE_ELIMINATED ) ); + TS_ASSERT_THROWS_NOTHING( max2.getCostFunctionComponent( cost2, MAX_PHASE_ELIMINATED ) ); TS_ASSERT_EQUALS( cost2._addends.size(), 1u ); TS_ASSERT_EQUALS( cost2._addends[1], 2 ); TS_ASSERT_EQUALS( cost2._constant, -2 ); @@ -1347,8 +1316,7 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite LinearExpression cost3; List phases; TS_ASSERT_THROWS_NOTHING( phases = max2.getAllCases() ); - TS_ASSERT_THROWS_NOTHING( max2.getCostFunctionComponent - ( cost3, *(phases.begin()) ) ); + TS_ASSERT_THROWS_NOTHING( max2.getCostFunctionComponent( cost3, *( phases.begin() ) ) ); TS_ASSERT_EQUALS( cost3._addends.size(), 1u ); // The first case is eliminate, the aux var to the second case is 9 TS_ASSERT_EQUALS( cost3._addends[9], 1 ); @@ -1357,8 +1325,7 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite // Each case returned by getAllCases() should be eligible as a term in // the SoI. for ( const auto &phase : phases ) - TS_ASSERT_THROWS_NOTHING( max2.getCostFunctionComponent - ( cost3, phase ) ); + TS_ASSERT_THROWS_NOTHING( max2.getCostFunctionComponent( cost3, phase ) ); } void test_get_phase_in_assignment() @@ -1385,14 +1352,12 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite assignment[4] = 1; List phases; TS_ASSERT_THROWS_NOTHING( phases = max.getAllCases() ); - TS_ASSERT_EQUALS( max.getPhaseStatusInAssignment( assignment ), - *phases.begin() ); + TS_ASSERT_EQUALS( max.getPhaseStatusInAssignment( assignment ), *phases.begin() ); assignment[1] = 1; assignment[3] = 0.9; assignment[4] = 0.8; - TS_ASSERT_EQUALS( max.getPhaseStatusInAssignment( assignment ), - MAX_PHASE_ELIMINATED ); + TS_ASSERT_EQUALS( max.getPhaseStatusInAssignment( assignment ), MAX_PHASE_ELIMINATED ); } void test_get_all_cases() @@ -1434,8 +1399,7 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite MaxConstraint max( f, elements ); InputQuery ipq; ipq.setNumberOfVariables( 5 ); - TS_ASSERT_THROWS_NOTHING( max.transformToUseAuxVariables - ( ipq ) ); + TS_ASSERT_THROWS_NOTHING( max.transformToUseAuxVariables( ipq ) ); TS_ASSERT_EQUALS( ipq.getNumberOfVariables(), 8u ); for ( unsigned i = 2; i < 5; ++i ) @@ -1448,8 +1412,7 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite max.getEntailedTightenings( tightenings ); double lowerBound = FloatUtils::negativeInfinity(); for ( const auto &t : tightenings ) - if ( t._variable == f && t._type == Tightening::LB && - t._value > lowerBound ) + if ( t._variable == f && t._type == Tightening::LB && t._value > lowerBound ) lowerBound = t._value; TS_ASSERT_EQUALS( lowerBound, 1 ); @@ -1460,8 +1423,7 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite lowerBound = FloatUtils::negativeInfinity(); for ( const auto &t : tightenings ) - if ( t._variable == f && t._type == Tightening::LB && - t._value > lowerBound ) + if ( t._variable == f && t._type == Tightening::LB && t._value > lowerBound ) lowerBound = t._value; TS_ASSERT_EQUALS( lowerBound, 1.5 ); } @@ -1479,8 +1441,7 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite MaxConstraint max( f, elements ); InputQuery ipq; ipq.setNumberOfVariables( 5 ); - TS_ASSERT_THROWS_NOTHING( max.transformToUseAuxVariables - ( ipq ) ); + TS_ASSERT_THROWS_NOTHING( max.transformToUseAuxVariables( ipq ) ); TS_ASSERT_EQUALS( ipq.getNumberOfVariables(), 8u ); for ( unsigned i = 2; i < 5; ++i ) @@ -1493,8 +1454,7 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite max.getEntailedTightenings( tightenings ); double upperBound = FloatUtils::infinity(); for ( const auto &t : tightenings ) - if ( t._variable == f && t._type == Tightening::UB && - t._value < upperBound ) + if ( t._variable == f && t._type == Tightening::UB && t._value < upperBound ) upperBound = t._value; TS_ASSERT_EQUALS( upperBound, 2 ); @@ -1504,8 +1464,7 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite max.getEntailedTightenings( tightenings ); for ( const auto &t : tightenings ) - if ( t._variable == f && t._type == Tightening::UB && - t._value < upperBound ) + if ( t._variable == f && t._type == Tightening::UB && t._value < upperBound ) upperBound = t._value; TS_ASSERT_EQUALS( upperBound, 2 ); } diff --git a/src/engine/tests/Test_NetworkLevelReasoner.h b/src/engine/tests/Test_NetworkLevelReasoner.h index 55684fe49e..8185531afb 100644 --- a/src/engine/tests/Test_NetworkLevelReasoner.h +++ b/src/engine/tests/Test_NetworkLevelReasoner.h @@ -13,13 +13,13 @@ **/ -#include - #include "FloatUtils.h" #include "MockTableau.h" #include "NetworkLevelReasoner.h" #include "Tightening.h" +#include + class MockForNetworkLevelReasoner { public: @@ -244,18 +244,30 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite tableau.setUpperBound( 1, 1 ); double large = 1000; - tableau.setLowerBound( 2, -large ); tableau.setUpperBound( 2, large ); - tableau.setLowerBound( 3, -large ); tableau.setUpperBound( 3, large ); - tableau.setLowerBound( 4, -large ); tableau.setUpperBound( 4, large ); - tableau.setLowerBound( 5, -large ); tableau.setUpperBound( 5, large ); - tableau.setLowerBound( 6, -large ); tableau.setUpperBound( 6, large ); - tableau.setLowerBound( 7, -large ); tableau.setUpperBound( 7, large ); - tableau.setLowerBound( 8, -large ); tableau.setUpperBound( 8, large ); - tableau.setLowerBound( 9, -large ); tableau.setUpperBound( 9, large ); - tableau.setLowerBound( 10, -large ); tableau.setUpperBound( 10, large ); - tableau.setLowerBound( 11, -large ); tableau.setUpperBound( 11, large ); - tableau.setLowerBound( 12, -large ); tableau.setUpperBound( 12, large ); - tableau.setLowerBound( 13, -large ); tableau.setUpperBound( 13, large ); + tableau.setLowerBound( 2, -large ); + tableau.setUpperBound( 2, large ); + tableau.setLowerBound( 3, -large ); + tableau.setUpperBound( 3, large ); + tableau.setLowerBound( 4, -large ); + tableau.setUpperBound( 4, large ); + tableau.setLowerBound( 5, -large ); + tableau.setUpperBound( 5, large ); + tableau.setLowerBound( 6, -large ); + tableau.setUpperBound( 6, large ); + tableau.setLowerBound( 7, -large ); + tableau.setUpperBound( 7, large ); + tableau.setLowerBound( 8, -large ); + tableau.setUpperBound( 8, large ); + tableau.setLowerBound( 9, -large ); + tableau.setUpperBound( 9, large ); + tableau.setLowerBound( 10, -large ); + tableau.setUpperBound( 10, large ); + tableau.setLowerBound( 11, -large ); + tableau.setUpperBound( 11, large ); + tableau.setLowerBound( 12, -large ); + tableau.setUpperBound( 12, large ); + tableau.setLowerBound( 13, -large ); + tableau.setUpperBound( 13, large ); nlr.setTableau( &tableau ); @@ -265,37 +277,25 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite // Perform the tightening pass TS_ASSERT_THROWS_NOTHING( nlr.intervalArithmeticBoundPropagation() ); - List expectedBounds({ - Tightening( 2, 0, Tightening::LB ), - Tightening( 2, 2, Tightening::UB ), - Tightening( 3, 0, Tightening::LB ), - Tightening( 3, 2, Tightening::UB ), - - Tightening( 4, -5, Tightening::LB ), - Tightening( 4, 5, Tightening::UB ), - Tightening( 5, 0, Tightening::LB ), - Tightening( 5, 5, Tightening::UB ), - - Tightening( 6, -1, Tightening::LB ), - Tightening( 6, 1, Tightening::UB ), - Tightening( 7, 0, Tightening::LB ), - Tightening( 7, 1, Tightening::UB ), - - Tightening( 8, -1, Tightening::LB ), - Tightening( 8, 7, Tightening::UB ), - Tightening( 9, 0, Tightening::LB ), - Tightening( 9, 7, Tightening::UB ), - - Tightening( 10, -1, Tightening::LB ), - Tightening( 10, 7, Tightening::UB ), - Tightening( 11, 0, Tightening::LB ), - Tightening( 11, 7, Tightening::UB ), - - Tightening( 12, 0, Tightening::LB ), - Tightening( 12, 7, Tightening::UB ), - Tightening( 13, 0, Tightening::LB ), - Tightening( 13, 28, Tightening::UB ), - }); + List expectedBounds( { + Tightening( 2, 0, Tightening::LB ), Tightening( 2, 2, Tightening::UB ), + Tightening( 3, 0, Tightening::LB ), Tightening( 3, 2, Tightening::UB ), + + Tightening( 4, -5, Tightening::LB ), Tightening( 4, 5, Tightening::UB ), + Tightening( 5, 0, Tightening::LB ), Tightening( 5, 5, Tightening::UB ), + + Tightening( 6, -1, Tightening::LB ), Tightening( 6, 1, Tightening::UB ), + Tightening( 7, 0, Tightening::LB ), Tightening( 7, 1, Tightening::UB ), + + Tightening( 8, -1, Tightening::LB ), Tightening( 8, 7, Tightening::UB ), + Tightening( 9, 0, Tightening::LB ), Tightening( 9, 7, Tightening::UB ), + + Tightening( 10, -1, Tightening::LB ), Tightening( 10, 7, Tightening::UB ), + Tightening( 11, 0, Tightening::LB ), Tightening( 11, 7, Tightening::UB ), + + Tightening( 12, 0, Tightening::LB ), Tightening( 12, 7, Tightening::UB ), + Tightening( 13, 0, Tightening::LB ), Tightening( 13, 28, Tightening::UB ), + } ); List bounds; TS_ASSERT_THROWS_NOTHING( nlr.getConstraintTightenings( bounds ) ); @@ -307,18 +307,30 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite tableau.setLowerBound( 1, -1 ); tableau.setUpperBound( 1, 2 ); - tableau.setLowerBound( 2, -large ); tableau.setUpperBound( 2, large ); - tableau.setLowerBound( 3, -large ); tableau.setUpperBound( 3, large ); - tableau.setLowerBound( 4, -large ); tableau.setUpperBound( 4, large ); - tableau.setLowerBound( 5, -large ); tableau.setUpperBound( 5, large ); - tableau.setLowerBound( 6, -large ); tableau.setUpperBound( 6, large ); - tableau.setLowerBound( 7, -large ); tableau.setUpperBound( 7, large ); - tableau.setLowerBound( 8, -large ); tableau.setUpperBound( 8, large ); - tableau.setLowerBound( 9, -large ); tableau.setUpperBound( 9, large ); - tableau.setLowerBound( 10, -large ); tableau.setUpperBound( 10, large ); - tableau.setLowerBound( 11, -large ); tableau.setUpperBound( 11, large ); - tableau.setLowerBound( 12, -large ); tableau.setUpperBound( 12, large ); - tableau.setLowerBound( 13, -large ); tableau.setUpperBound( 13, large ); + tableau.setLowerBound( 2, -large ); + tableau.setUpperBound( 2, large ); + tableau.setLowerBound( 3, -large ); + tableau.setUpperBound( 3, large ); + tableau.setLowerBound( 4, -large ); + tableau.setUpperBound( 4, large ); + tableau.setLowerBound( 5, -large ); + tableau.setUpperBound( 5, large ); + tableau.setLowerBound( 6, -large ); + tableau.setUpperBound( 6, large ); + tableau.setLowerBound( 7, -large ); + tableau.setUpperBound( 7, large ); + tableau.setLowerBound( 8, -large ); + tableau.setUpperBound( 8, large ); + tableau.setLowerBound( 9, -large ); + tableau.setUpperBound( 9, large ); + tableau.setLowerBound( 10, -large ); + tableau.setUpperBound( 10, large ); + tableau.setLowerBound( 11, -large ); + tableau.setUpperBound( 11, large ); + tableau.setLowerBound( 12, -large ); + tableau.setUpperBound( 12, large ); + tableau.setLowerBound( 13, -large ); + tableau.setUpperBound( 13, large ); // Initialize TS_ASSERT_THROWS_NOTHING( nlr.obtainCurrentBounds() ); @@ -326,37 +338,25 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite // Perform the tightening pass TS_ASSERT_THROWS_NOTHING( nlr.intervalArithmeticBoundPropagation() ); - List expectedBounds2({ - Tightening( 2, -2, Tightening::LB ), - Tightening( 2, 2, Tightening::UB ), - Tightening( 3, 0, Tightening::LB ), - Tightening( 3, 2, Tightening::UB ), - - Tightening( 4, -12, Tightening::LB ), - Tightening( 4, 5, Tightening::UB ), - Tightening( 5, 0, Tightening::LB ), - Tightening( 5, 5, Tightening::UB ), - - Tightening( 6, -1, Tightening::LB ), - Tightening( 6, 2, Tightening::UB ), - Tightening( 7, 0, Tightening::LB ), - Tightening( 7, 2, Tightening::UB ), - - Tightening( 8, -2, Tightening::LB ), - Tightening( 8, 7, Tightening::UB ), - Tightening( 9, 0, Tightening::LB ), - Tightening( 9, 7, Tightening::UB ), - - Tightening( 10, -2, Tightening::LB ), - Tightening( 10, 7, Tightening::UB ), - Tightening( 11, 0, Tightening::LB ), - Tightening( 11, 7, Tightening::UB ), - - Tightening( 12, 0, Tightening::LB ), - Tightening( 12, 7, Tightening::UB ), - Tightening( 13, 0, Tightening::LB ), - Tightening( 13, 28, Tightening::UB ), - }); + List expectedBounds2( { + Tightening( 2, -2, Tightening::LB ), Tightening( 2, 2, Tightening::UB ), + Tightening( 3, 0, Tightening::LB ), Tightening( 3, 2, Tightening::UB ), + + Tightening( 4, -12, Tightening::LB ), Tightening( 4, 5, Tightening::UB ), + Tightening( 5, 0, Tightening::LB ), Tightening( 5, 5, Tightening::UB ), + + Tightening( 6, -1, Tightening::LB ), Tightening( 6, 2, Tightening::UB ), + Tightening( 7, 0, Tightening::LB ), Tightening( 7, 2, Tightening::UB ), + + Tightening( 8, -2, Tightening::LB ), Tightening( 8, 7, Tightening::UB ), + Tightening( 9, 0, Tightening::LB ), Tightening( 9, 7, Tightening::UB ), + + Tightening( 10, -2, Tightening::LB ), Tightening( 10, 7, Tightening::UB ), + Tightening( 11, 0, Tightening::LB ), Tightening( 11, 7, Tightening::UB ), + + Tightening( 12, 0, Tightening::LB ), Tightening( 12, 7, Tightening::UB ), + Tightening( 13, 0, Tightening::LB ), Tightening( 13, 28, Tightening::UB ), + } ); TS_ASSERT_THROWS_NOTHING( nlr.getConstraintTightenings( bounds ) ); TS_ASSERT_EQUALS( expectedBounds2, bounds ); @@ -383,18 +383,30 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite tableau.setUpperBound( 1, 2 ); double large = 1000; - tableau.setLowerBound( 2, -large ); tableau.setUpperBound( 2, large ); - tableau.setLowerBound( 3, -large ); tableau.setUpperBound( 3, large ); - tableau.setLowerBound( 4, -large ); tableau.setUpperBound( 4, large ); - tableau.setLowerBound( 5, -large ); tableau.setUpperBound( 5, large ); - tableau.setLowerBound( 6, -large ); tableau.setUpperBound( 6, large ); - tableau.setLowerBound( 7, -large ); tableau.setUpperBound( 7, large ); - tableau.setLowerBound( 8, -large ); tableau.setUpperBound( 8, large ); - tableau.setLowerBound( 9, -large ); tableau.setUpperBound( 9, large ); - tableau.setLowerBound( 10, -large ); tableau.setUpperBound( 10, large ); - tableau.setLowerBound( 11, -large ); tableau.setUpperBound( 11, large ); - tableau.setLowerBound( 12, -large ); tableau.setUpperBound( 12, large ); - tableau.setLowerBound( 13, -large ); tableau.setUpperBound( 13, large ); + tableau.setLowerBound( 2, -large ); + tableau.setUpperBound( 2, large ); + tableau.setLowerBound( 3, -large ); + tableau.setUpperBound( 3, large ); + tableau.setLowerBound( 4, -large ); + tableau.setUpperBound( 4, large ); + tableau.setLowerBound( 5, -large ); + tableau.setUpperBound( 5, large ); + tableau.setLowerBound( 6, -large ); + tableau.setUpperBound( 6, large ); + tableau.setLowerBound( 7, -large ); + tableau.setUpperBound( 7, large ); + tableau.setLowerBound( 8, -large ); + tableau.setUpperBound( 8, large ); + tableau.setLowerBound( 9, -large ); + tableau.setUpperBound( 9, large ); + tableau.setLowerBound( 10, -large ); + tableau.setUpperBound( 10, large ); + tableau.setLowerBound( 11, -large ); + tableau.setUpperBound( 11, large ); + tableau.setLowerBound( 12, -large ); + tableau.setUpperBound( 12, large ); + tableau.setLowerBound( 13, -large ); + tableau.setUpperBound( 13, large ); nlr.setTableau( &tableau ); @@ -404,37 +416,25 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite // Perform the tightening pass TS_ASSERT_THROWS_NOTHING( nlr.intervalArithmeticBoundPropagation() ); - List expectedBounds({ - Tightening( 2, 0, Tightening::LB ), - Tightening( 2, 3, Tightening::UB ), - Tightening( 3, 0, Tightening::LB ), - Tightening( 3, 3, Tightening::UB ), - - Tightening( 4, -8, Tightening::LB ), - Tightening( 4, 7, Tightening::UB ), - Tightening( 5, 0, Tightening::LB ), - Tightening( 5, 8, Tightening::UB ), - - Tightening( 6, -1, Tightening::LB ), - Tightening( 6, 2, Tightening::UB ), - Tightening( 7, 0, Tightening::LB ), - Tightening( 7, 2, Tightening::UB ), - - Tightening( 8, -2, Tightening::LB ), - Tightening( 8, 11, Tightening::UB ), - Tightening( 9, 0, Tightening::LB ), - Tightening( 9, 11, Tightening::UB ), - - Tightening( 10, -3, Tightening::LB ), - Tightening( 10, 10, Tightening::UB ), - Tightening( 11, 0, Tightening::LB ), - Tightening( 11, 10, Tightening::UB ), - - Tightening( 12, 0, Tightening::LB ), - Tightening( 12, 11, Tightening::UB ), - Tightening( 13, 0, Tightening::LB ), - Tightening( 13, 41, Tightening::UB ), - }); + List expectedBounds( { + Tightening( 2, 0, Tightening::LB ), Tightening( 2, 3, Tightening::UB ), + Tightening( 3, 0, Tightening::LB ), Tightening( 3, 3, Tightening::UB ), + + Tightening( 4, -8, Tightening::LB ), Tightening( 4, 7, Tightening::UB ), + Tightening( 5, 0, Tightening::LB ), Tightening( 5, 8, Tightening::UB ), + + Tightening( 6, -1, Tightening::LB ), Tightening( 6, 2, Tightening::UB ), + Tightening( 7, 0, Tightening::LB ), Tightening( 7, 2, Tightening::UB ), + + Tightening( 8, -2, Tightening::LB ), Tightening( 8, 11, Tightening::UB ), + Tightening( 9, 0, Tightening::LB ), Tightening( 9, 11, Tightening::UB ), + + Tightening( 10, -3, Tightening::LB ), Tightening( 10, 10, Tightening::UB ), + Tightening( 11, 0, Tightening::LB ), Tightening( 11, 10, Tightening::UB ), + + Tightening( 12, 0, Tightening::LB ), Tightening( 12, 11, Tightening::UB ), + Tightening( 13, 0, Tightening::LB ), Tightening( 13, 41, Tightening::UB ), + } ); List bounds; TS_ASSERT_THROWS_NOTHING( nlr.getConstraintTightenings( bounds ) ); @@ -446,18 +446,30 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite tableau.setLowerBound( 1, -1 ); tableau.setUpperBound( 1, 2 ); - tableau.setLowerBound( 2, -large ); tableau.setUpperBound( 2, large ); - tableau.setLowerBound( 3, -large ); tableau.setUpperBound( 3, large ); - tableau.setLowerBound( 4, -large ); tableau.setUpperBound( 4, large ); - tableau.setLowerBound( 5, -large ); tableau.setUpperBound( 5, large ); - tableau.setLowerBound( 6, -large ); tableau.setUpperBound( 6, large ); - tableau.setLowerBound( 7, -large ); tableau.setUpperBound( 7, large ); - tableau.setLowerBound( 8, -large ); tableau.setUpperBound( 8, large ); - tableau.setLowerBound( 9, -large ); tableau.setUpperBound( 9, large ); - tableau.setLowerBound( 10, -large ); tableau.setUpperBound( 10, large ); - tableau.setLowerBound( 11, -large ); tableau.setUpperBound( 11, large ); - tableau.setLowerBound( 12, -large ); tableau.setUpperBound( 12, large ); - tableau.setLowerBound( 13, -large ); tableau.setUpperBound( 13, large ); + tableau.setLowerBound( 2, -large ); + tableau.setUpperBound( 2, large ); + tableau.setLowerBound( 3, -large ); + tableau.setUpperBound( 3, large ); + tableau.setLowerBound( 4, -large ); + tableau.setUpperBound( 4, large ); + tableau.setLowerBound( 5, -large ); + tableau.setUpperBound( 5, large ); + tableau.setLowerBound( 6, -large ); + tableau.setUpperBound( 6, large ); + tableau.setLowerBound( 7, -large ); + tableau.setUpperBound( 7, large ); + tableau.setLowerBound( 8, -large ); + tableau.setUpperBound( 8, large ); + tableau.setLowerBound( 9, -large ); + tableau.setUpperBound( 9, large ); + tableau.setLowerBound( 10, -large ); + tableau.setUpperBound( 10, large ); + tableau.setLowerBound( 11, -large ); + tableau.setUpperBound( 11, large ); + tableau.setLowerBound( 12, -large ); + tableau.setUpperBound( 12, large ); + tableau.setLowerBound( 13, -large ); + tableau.setUpperBound( 13, large ); // Initialize TS_ASSERT_THROWS_NOTHING( nlr.obtainCurrentBounds() ); @@ -465,37 +477,25 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite // Perform the tightening pass TS_ASSERT_THROWS_NOTHING( nlr.intervalArithmeticBoundPropagation() ); - List expectedBounds2({ - Tightening( 2, -2, Tightening::LB ), - Tightening( 2, 2, Tightening::UB ), - Tightening( 3, 0, Tightening::LB ), - Tightening( 3, 2, Tightening::UB ), - - Tightening( 4, -12, Tightening::LB ), - Tightening( 4, 5, Tightening::UB ), - Tightening( 5, 0, Tightening::LB ), - Tightening( 5, 12, Tightening::UB ), - - Tightening( 6, -1, Tightening::LB ), - Tightening( 6, 2, Tightening::UB ), - Tightening( 7, 0, Tightening::LB ), - Tightening( 7, 2, Tightening::UB ), - - Tightening( 8, -2, Tightening::LB ), - Tightening( 8, 14, Tightening::UB ), - Tightening( 9, 0, Tightening::LB ), - Tightening( 9, 14, Tightening::UB ), - - Tightening( 10, -2, Tightening::LB ), - Tightening( 10, 14, Tightening::UB ), - Tightening( 11, 0, Tightening::LB ), - Tightening( 11, 14, Tightening::UB ), - - Tightening( 12, 0, Tightening::LB ), - Tightening( 12, 14, Tightening::UB ), - Tightening( 13, 0, Tightening::LB ), - Tightening( 13, 56, Tightening::UB ), - }); + List expectedBounds2( { + Tightening( 2, -2, Tightening::LB ), Tightening( 2, 2, Tightening::UB ), + Tightening( 3, 0, Tightening::LB ), Tightening( 3, 2, Tightening::UB ), + + Tightening( 4, -12, Tightening::LB ), Tightening( 4, 5, Tightening::UB ), + Tightening( 5, 0, Tightening::LB ), Tightening( 5, 12, Tightening::UB ), + + Tightening( 6, -1, Tightening::LB ), Tightening( 6, 2, Tightening::UB ), + Tightening( 7, 0, Tightening::LB ), Tightening( 7, 2, Tightening::UB ), + + Tightening( 8, -2, Tightening::LB ), Tightening( 8, 14, Tightening::UB ), + Tightening( 9, 0, Tightening::LB ), Tightening( 9, 14, Tightening::UB ), + + Tightening( 10, -2, Tightening::LB ), Tightening( 10, 14, Tightening::UB ), + Tightening( 11, 0, Tightening::LB ), Tightening( 11, 14, Tightening::UB ), + + Tightening( 12, 0, Tightening::LB ), Tightening( 12, 14, Tightening::UB ), + Tightening( 13, 0, Tightening::LB ), Tightening( 13, 56, Tightening::UB ), + } ); TS_ASSERT_THROWS_NOTHING( nlr.getConstraintTightenings( bounds ) ); TS_ASSERT_EQUALS( expectedBounds2, bounds ); @@ -557,11 +557,16 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite // Very loose bounds for neurons except inputs double large = 1000000; - tableau.setLowerBound( 2, -large ); tableau.setUpperBound( 2, large ); - tableau.setLowerBound( 3, -large ); tableau.setUpperBound( 3, large ); - tableau.setLowerBound( 4, -large ); tableau.setUpperBound( 4, large ); - tableau.setLowerBound( 5, -large ); tableau.setUpperBound( 5, large ); - tableau.setLowerBound( 6, -large ); tableau.setUpperBound( 6, large ); + tableau.setLowerBound( 2, -large ); + tableau.setUpperBound( 2, large ); + tableau.setLowerBound( 3, -large ); + tableau.setUpperBound( 3, large ); + tableau.setLowerBound( 4, -large ); + tableau.setUpperBound( 4, large ); + tableau.setLowerBound( 5, -large ); + tableau.setUpperBound( 5, large ); + tableau.setLowerBound( 6, -large ); + tableau.setUpperBound( 6, large ); } void test_sbt_relus_all_active() @@ -608,20 +613,20 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite x6.ub = x0 + 2x1 : [6, 16] */ - List expectedBounds({ - Tightening( 2, 11, Tightening::LB ), - Tightening( 2, 27, Tightening::UB ), - Tightening( 3, 5, Tightening::LB ), - Tightening( 3, 11, Tightening::UB ), + List expectedBounds( { + Tightening( 2, 11, Tightening::LB ), + Tightening( 2, 27, Tightening::UB ), + Tightening( 3, 5, Tightening::LB ), + Tightening( 3, 11, Tightening::UB ), - Tightening( 4, 11, Tightening::LB ), - Tightening( 4, 27, Tightening::UB ), - Tightening( 5, 5, Tightening::LB ), - Tightening( 5, 11, Tightening::UB ), + Tightening( 4, 11, Tightening::LB ), + Tightening( 4, 27, Tightening::UB ), + Tightening( 5, 5, Tightening::LB ), + Tightening( 5, 11, Tightening::UB ), - Tightening( 6, 6, Tightening::LB ), - Tightening( 6, 16, Tightening::UB ), - }); + Tightening( 6, 6, Tightening::LB ), + Tightening( 6, 16, Tightening::UB ), + } ); List bounds; TS_ASSERT_THROWS_NOTHING( nlr.getConstraintTightenings( bounds ) ); @@ -679,20 +684,20 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite x6.ub = - x0 - x1 : [-11, -5] */ - List expectedBounds({ - Tightening( 2, -19, Tightening::LB ), - Tightening( 2, -3, Tightening::UB ), - Tightening( 3, 5, Tightening::LB ), - Tightening( 3, 11, Tightening::UB ), + List expectedBounds( { + Tightening( 2, -19, Tightening::LB ), + Tightening( 2, -3, Tightening::UB ), + Tightening( 3, 5, Tightening::LB ), + Tightening( 3, 11, Tightening::UB ), - Tightening( 4, 0, Tightening::LB ), - Tightening( 4, 0, Tightening::UB ), - Tightening( 5, 5, Tightening::LB ), - Tightening( 5, 11, Tightening::UB ), + Tightening( 4, 0, Tightening::LB ), + Tightening( 4, 0, Tightening::UB ), + Tightening( 5, 5, Tightening::LB ), + Tightening( 5, 11, Tightening::UB ), - Tightening( 6, -11, Tightening::LB ), - Tightening( 6, -5, Tightening::UB ), - }); + Tightening( 6, -11, Tightening::LB ), + Tightening( 6, -5, Tightening::UB ), + } ); List bounds; TS_ASSERT_THROWS_NOTHING( nlr.getConstraintTightenings( bounds ) ); @@ -754,20 +759,20 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite x6 range: [2 + 1.25 - 11.25 = -8, 3 + 6.25 - 8.25 = 1] = [-8, 1] */ - List expectedBounds({ - Tightening( 2, -4, Tightening::LB ), - Tightening( 2, 12, Tightening::UB ), - Tightening( 3, 5, Tightening::LB ), - Tightening( 3, 11, Tightening::UB ), + List expectedBounds( { + Tightening( 2, -4, Tightening::LB ), + Tightening( 2, 12, Tightening::UB ), + Tightening( 3, 5, Tightening::LB ), + Tightening( 3, 11, Tightening::UB ), - Tightening( 4, 0, Tightening::LB ), - Tightening( 4, 12, Tightening::UB ), - Tightening( 5, 5, Tightening::LB ), - Tightening( 5, 11, Tightening::UB ), + Tightening( 4, 0, Tightening::LB ), + Tightening( 4, 12, Tightening::UB ), + Tightening( 5, 5, Tightening::LB ), + Tightening( 5, 11, Tightening::UB ), - Tightening( 6, -8, Tightening::LB ), - Tightening( 6, 1, Tightening::UB ), - }); + Tightening( 6, -8, Tightening::LB ), + Tightening( 6, 1, Tightening::UB ), + } ); List bounds; TS_ASSERT_THROWS_NOTHING( nlr.getConstraintTightenings( bounds ) ); @@ -828,20 +833,20 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite x6.ub = - x0 - x1 : [-11, -5] */ - List expectedBounds({ - // x2 does not appear, because it has been eliminated + List expectedBounds( { + // x2 does not appear, because it has been eliminated - Tightening( 3, 5, Tightening::LB ), - Tightening( 3, 11, Tightening::UB ), + Tightening( 3, 5, Tightening::LB ), + Tightening( 3, 11, Tightening::UB ), - Tightening( 4, 0, Tightening::LB ), - Tightening( 4, 0, Tightening::UB ), - Tightening( 5, 5, Tightening::LB ), - Tightening( 5, 11, Tightening::UB ), + Tightening( 4, 0, Tightening::LB ), + Tightening( 4, 0, Tightening::UB ), + Tightening( 5, 5, Tightening::LB ), + Tightening( 5, 11, Tightening::UB ), - Tightening( 6, -11, Tightening::LB ), - Tightening( 6, -5, Tightening::UB ), - }); + Tightening( 6, -11, Tightening::LB ), + Tightening( 6, -5, Tightening::UB ), + } ); List bounds; TS_ASSERT_THROWS_NOTHING( nlr.getConstraintTightenings( bounds ) ); @@ -898,20 +903,20 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite x6.ub = x0 + 2x1 : [6, 16] */ - List expectedBounds({ - Tightening( 2, 11, Tightening::LB ), - Tightening( 2, 27, Tightening::UB ), - Tightening( 3, 5, Tightening::LB ), - Tightening( 3, 11, Tightening::UB ), + List expectedBounds( { + Tightening( 2, 11, Tightening::LB ), + Tightening( 2, 27, Tightening::UB ), + Tightening( 3, 5, Tightening::LB ), + Tightening( 3, 11, Tightening::UB ), - Tightening( 4, 11, Tightening::LB ), - Tightening( 4, 27, Tightening::UB ), - Tightening( 5, 5, Tightening::LB ), - Tightening( 5, 11, Tightening::UB ), + Tightening( 4, 11, Tightening::LB ), + Tightening( 4, 27, Tightening::UB ), + Tightening( 5, 5, Tightening::LB ), + Tightening( 5, 11, Tightening::UB ), - Tightening( 6, 6, Tightening::LB ), - Tightening( 6, 16, Tightening::UB ), - }); + Tightening( 6, 6, Tightening::LB ), + Tightening( 6, 16, Tightening::UB ), + } ); List bounds; TS_ASSERT_THROWS_NOTHING( nlr.getConstraintTightenings( bounds ) ); @@ -972,20 +977,20 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite x6.ub = - 3x0 - 4x1 + 30 : [-8, 14] */ - List expectedBounds({ - Tightening( 2, -19, Tightening::LB ), - Tightening( 2, -3, Tightening::UB ), - Tightening( 3, 5, Tightening::LB ), - Tightening( 3, 11, Tightening::UB ), + List expectedBounds( { + Tightening( 2, -19, Tightening::LB ), + Tightening( 2, -3, Tightening::UB ), + Tightening( 3, 5, Tightening::LB ), + Tightening( 3, 11, Tightening::UB ), - Tightening( 4, 3, Tightening::LB ), - Tightening( 4, 19, Tightening::UB ), - Tightening( 5, 5, Tightening::LB ), - Tightening( 5, 11, Tightening::UB ), + Tightening( 4, 3, Tightening::LB ), + Tightening( 4, 19, Tightening::UB ), + Tightening( 5, 5, Tightening::LB ), + Tightening( 5, 11, Tightening::UB ), - Tightening( 6, -8, Tightening::LB ), - Tightening( 6, 14, Tightening::UB ), - }); + Tightening( 6, -8, Tightening::LB ), + Tightening( 6, 14, Tightening::UB ), + } ); List bounds; TS_ASSERT_THROWS_NOTHING( nlr.getConstraintTightenings( bounds ) ); @@ -1049,20 +1054,20 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite x6 range: [-11, 7] */ - List expectedBounds({ - Tightening( 2, -4, Tightening::LB ), - Tightening( 2, 12, Tightening::UB ), - Tightening( 3, 5, Tightening::LB ), - Tightening( 3, 11, Tightening::UB ), + List expectedBounds( { + Tightening( 2, -4, Tightening::LB ), + Tightening( 2, 12, Tightening::UB ), + Tightening( 3, 5, Tightening::LB ), + Tightening( 3, 11, Tightening::UB ), - Tightening( 4, 0, Tightening::LB ), - Tightening( 4, 12, Tightening::UB ), - Tightening( 5, 5, Tightening::LB ), - Tightening( 5, 11, Tightening::UB ), + Tightening( 4, 0, Tightening::LB ), + Tightening( 4, 12, Tightening::UB ), + Tightening( 5, 5, Tightening::LB ), + Tightening( 5, 11, Tightening::UB ), - Tightening( 6, -11, Tightening::LB ), - Tightening( 6, 7, Tightening::UB ), - }); + Tightening( 6, -11, Tightening::LB ), + Tightening( 6, 7, Tightening::UB ), + } ); List bounds; TS_ASSERT_THROWS_NOTHING( nlr.getConstraintTightenings( bounds ) ); @@ -1128,20 +1133,20 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite x6.ub = - 3x0 - 4x1 + 15 : [-23, -1] */ - List expectedBounds({ - // x2 does not appear, because it has been eliminated + List expectedBounds( { + // x2 does not appear, because it has been eliminated - Tightening( 3, 5, Tightening::LB ), - Tightening( 3, 11, Tightening::UB ), + Tightening( 3, 5, Tightening::LB ), + Tightening( 3, 11, Tightening::UB ), - Tightening( 4, 0, Tightening::LB ), - Tightening( 4, 4, Tightening::UB ), - Tightening( 5, 5, Tightening::LB ), - Tightening( 5, 11, Tightening::UB ), + Tightening( 4, 0, Tightening::LB ), + Tightening( 4, 4, Tightening::UB ), + Tightening( 5, 5, Tightening::LB ), + Tightening( 5, 11, Tightening::UB ), - Tightening( 6, -23, Tightening::LB ), - Tightening( 6, -1, Tightening::UB ), - }); + Tightening( 6, -23, Tightening::LB ), + Tightening( 6, -1, Tightening::UB ), + } ); List bounds; TS_ASSERT_THROWS_NOTHING( nlr.getConstraintTightenings( bounds ) ); diff --git a/src/engine/tests/Test_PolarityBasedDivider.h b/src/engine/tests/Test_PolarityBasedDivider.h index 2b35c43558..0d36150a7c 100644 --- a/src/engine/tests/Test_PolarityBasedDivider.h +++ b/src/engine/tests/Test_PolarityBasedDivider.h @@ -13,22 +13,21 @@ **/ -#include - -#include "MockEngine.h" #include "InputQuery.h" -#include "PiecewiseLinearConstraint.h" -#include "PolarityBasedDivider.h" #include "List.h" #include "MStringf.h" +#include "MockEngine.h" +#include "PiecewiseLinearConstraint.h" +#include "PolarityBasedDivider.h" #include "ReluConstraint.h" #include "SubQuery.h" #include "Vector.h" +#include + class PolarityBasedDividerTestSuite : public CxxTest::TestSuite { public: - std::shared_ptr engine; void setUp() { @@ -57,8 +56,8 @@ class PolarityBasedDividerTestSuite : public CxxTest::TestSuite engine->setSplitPLConstraint( relu2 ); // Initiate the divider - auto queryDivider = std::unique_ptr - ( new PolarityBasedDivider( engine ) ); + auto queryDivider = + std::unique_ptr( new PolarityBasedDivider( engine ) ); double timeoutFactor = 1.5; // Use the divider to create 4 subqueries @@ -66,14 +65,16 @@ class PolarityBasedDividerTestSuite : public CxxTest::TestSuite unsigned numNewSubQueries = 4; String queryId = "mock"; unsigned timeoutInSeconds = 5; - auto previousSplit = std::unique_ptr - ( new PiecewiseLinearCaseSplit ); + auto previousSplit = + std::unique_ptr( new PiecewiseLinearCaseSplit ); // Divide the previousSplit SubQueries subQueries; - queryDivider->createSubQueries( numNewSubQueries, queryId, 0, - *previousSplit, (unsigned) - timeoutInSeconds * timeoutFactor, + queryDivider->createSubQueries( numNewSubQueries, + queryId, + 0, + *previousSplit, + (unsigned)timeoutInSeconds * timeoutFactor, subQueries ); TS_ASSERT_EQUALS( subQueries.size(), numNewSubQueries ); @@ -89,20 +90,20 @@ class PolarityBasedDividerTestSuite : public CxxTest::TestSuite auto split2_2 = *splits2.rbegin(); PiecewiseLinearCaseSplit split_act_act; - add_to_split( split_act_act, split1_1); - add_to_split( split_act_act, split2_1); + add_to_split( split_act_act, split1_1 ); + add_to_split( split_act_act, split2_1 ); PiecewiseLinearCaseSplit split_act_inact; - add_to_split( split_act_inact, split1_1); - add_to_split( split_act_inact, split2_2); + add_to_split( split_act_inact, split1_1 ); + add_to_split( split_act_inact, split2_2 ); PiecewiseLinearCaseSplit split_inact_act; - add_to_split( split_inact_act, split1_2); - add_to_split( split_inact_act, split2_1); + add_to_split( split_inact_act, split1_2 ); + add_to_split( split_inact_act, split2_1 ); PiecewiseLinearCaseSplit split_inact_inact; - add_to_split( split_inact_inact, split1_2); - add_to_split( split_inact_inact, split2_2); + add_to_split( split_inact_inact, split1_2 ); + add_to_split( split_inact_inact, split2_2 ); // The following four splits should be created by the queryDivider Vector newSplits; @@ -111,15 +112,13 @@ class PolarityBasedDividerTestSuite : public CxxTest::TestSuite newSplits.append( split_inact_act ); newSplits.append( split_inact_inact ); - unsigned correctTimeoutInSeconds = (unsigned) ( timeoutInSeconds * - timeoutFactor ); + unsigned correctTimeoutInSeconds = (unsigned)( timeoutInSeconds * timeoutFactor ); unsigned index = 0; for ( const auto &subQuery : subQueries ) { - TS_ASSERT( subQuery->_queryId == queryId + - Stringf( "-%u", index + 1 ) ); + TS_ASSERT( subQuery->_queryId == queryId + Stringf( "-%u", index + 1 ) ); TS_ASSERT( subQuery->_depth == 1 ); - TS_ASSERT( *(subQuery->_split) == newSplits[index] ); + TS_ASSERT( *( subQuery->_split ) == newSplits[index] ); TS_ASSERT( subQuery->_timeoutInSeconds == correctTimeoutInSeconds ); ++index; diff --git a/src/engine/tests/Test_Preprocessor.h b/src/engine/tests/Test_Preprocessor.h index 2b7ef3e618..bf9e13c476 100644 --- a/src/engine/tests/Test_Preprocessor.h +++ b/src/engine/tests/Test_Preprocessor.h @@ -14,19 +14,18 @@ ** [[ Add lengthier description here ]] **/ -#include - #include "DisjunctionConstraint.h" #include "Engine.h" #include "FloatUtils.h" #include "InfeasibleQueryException.h" #include "InputQuery.h" +#include "MarabouError.h" #include "MaxConstraint.h" #include "MockErrno.h" #include "Preprocessor.h" #include "ReluConstraint.h" -#include "MarabouError.h" +#include #include class MockForPreprocessor @@ -105,7 +104,7 @@ class PreprocessorTestSuite : public CxxTest::TestSuite TS_ASSERT_EQUALS( processed.getLowerBound( 0 ), 0 ); TS_ASSERT_EQUALS( processed.getUpperBound( 0 ), 13 ); TS_ASSERT_EQUALS( processed.getLowerBound( 2 ), -10 ); - TS_ASSERT_EQUALS( processed.getUpperBound( 2 ), 3 ); + TS_ASSERT_EQUALS( processed.getUpperBound( 2 ), 3 ); inputQuery.setLowerBound( 0, FloatUtils::negativeInfinity() ); inputQuery.setUpperBound( 0, 15 ); @@ -170,10 +169,11 @@ class PreprocessorTestSuite : public CxxTest::TestSuite // x2.ub = -10 + x0.ub + x1.ub = -10 + 5 -2 = -7 // x2 = [0, -7] -> throw error - TS_ASSERT_THROWS( Preprocessor().preprocess( inputQuery ), const InfeasibleQueryException &e ); + TS_ASSERT_THROWS( Preprocessor().preprocess( inputQuery ), + const InfeasibleQueryException &e ); InputQuery inputQuery2; - inputQuery2.setNumberOfVariables( 5 ); + inputQuery2.setNumberOfVariables( 5 ); inputQuery2.setLowerBound( 1, 0 ); inputQuery2.setUpperBound( 1, 1 ); inputQuery2.setLowerBound( 2, 2 ); @@ -255,7 +255,8 @@ class PreprocessorTestSuite : public CxxTest::TestSuite TS_ASSERT( FloatUtils::areEqual( processed.getLowerBound( 1 ), 0 ) ); TS_ASSERT( FloatUtils::areEqual( processed.getUpperBound( 1 ), 10 ) ); - TS_ASSERT( FloatUtils::areEqual( processed.getLowerBound( 0 ), FloatUtils::negativeInfinity() ) ); // + TS_ASSERT( FloatUtils::areEqual( processed.getLowerBound( 0 ), + FloatUtils::negativeInfinity() ) ); // TS_ASSERT( FloatUtils::areEqual( processed.getUpperBound( 0 ), 10 ) ); // x2 = Max( x3, x4 ) @@ -270,7 +271,8 @@ class PreprocessorTestSuite : public CxxTest::TestSuite // x4.ub = 13 TS_ASSERT( FloatUtils::areEqual( processed.getLowerBound( 2 ), 5 ) ); TS_ASSERT( FloatUtils::areEqual( processed.getUpperBound( 2 ), 13 ) ); - TS_ASSERT( FloatUtils::areEqual( processed.getLowerBound( 3 ), FloatUtils::negativeInfinity() ) ); + TS_ASSERT( + FloatUtils::areEqual( processed.getLowerBound( 3 ), FloatUtils::negativeInfinity() ) ); TS_ASSERT( FloatUtils::areEqual( processed.getUpperBound( 3 ), 10 ) ); TS_ASSERT( FloatUtils::areEqual( processed.getLowerBound( 4 ), 4 ) ); TS_ASSERT( FloatUtils::areEqual( processed.getUpperBound( 4 ), 13 ) ); @@ -376,7 +378,7 @@ class PreprocessorTestSuite : public CxxTest::TestSuite inputQuery.setUpperBound( 3, 5 ); inputQuery.setLowerBound( 4, 0 ); // unused inputQuery.setUpperBound( 4, 10 ); - inputQuery.setLowerBound( 5, 0 ); // unused + inputQuery.setLowerBound( 5, 0 ); // unused inputQuery.setUpperBound( 5, 10 ); inputQuery.setLowerBound( 6, 5 ); // fxied inputQuery.setUpperBound( 6, 5 ); @@ -470,8 +472,8 @@ class PreprocessorTestSuite : public CxxTest::TestSuite equation4.setScalar( -0.341 ); inputQuery.addEquation( equation4 ); - inputQuery.addNonlinearConstraint( new SigmoidConstraint(2, 4) ); - inputQuery.addNonlinearConstraint( new SigmoidConstraint(3, 5) ); + inputQuery.addNonlinearConstraint( new SigmoidConstraint( 2, 4 ) ); + inputQuery.addNonlinearConstraint( new SigmoidConstraint( 3, 5 ) ); InputQuery processed = *( Preprocessor().preprocess( inputQuery, true ) ); @@ -539,7 +541,7 @@ class PreprocessorTestSuite : public CxxTest::TestSuite // 2x0 - 2x1 = 0 Equation equation1; - equation1.addAddend( 2, 0 ); + equation1.addAddend( 2, 0 ); equation1.addAddend( -2, 1 ); equation1.setScalar( 0 ); inputQuery.addEquation( equation1 ); @@ -582,10 +584,10 @@ class PreprocessorTestSuite : public CxxTest::TestSuite TS_ASSERT_EQUALS( addend->_variable, 1U ); TS_ASSERT_EQUALS( preprocessedEquation._scalar, 1.0 ); - for ( const auto &plConstraint: processed.getPiecewiseLinearConstraints() ) + for ( const auto &plConstraint : processed.getPiecewiseLinearConstraints() ) { - TS_ASSERT( plConstraint->participatingVariable( 0 )); - TS_ASSERT( plConstraint->participatingVariable( 2 )); + TS_ASSERT( plConstraint->participatingVariable( 0 ) ); + TS_ASSERT( plConstraint->participatingVariable( 2 ) ); } } @@ -696,37 +698,37 @@ class PreprocessorTestSuite : public CxxTest::TestSuite eq_eq = new Equation(); eq_eq->addAddend( 1, 8 ); eq_eq->setScalar( 0 ); - inputQuery.addEquation( *eq_eq); + inputQuery.addEquation( *eq_eq ); delete eq_eq; eq_eq = new Equation(); eq_eq->addAddend( 1, 16 ); eq_eq->setScalar( 0 ); - inputQuery.addEquation( *eq_eq); + inputQuery.addEquation( *eq_eq ); delete eq_eq; eq_eq = new Equation(); eq_eq->addAddend( 1, 5 ); eq_eq->setScalar( 0 ); - inputQuery.addEquation( *eq_eq); + inputQuery.addEquation( *eq_eq ); delete eq_eq; eq_eq = new Equation(); eq_eq->addAddend( 1, 9 ); eq_eq->setScalar( 0 ); - inputQuery.addEquation( *eq_eq); + inputQuery.addEquation( *eq_eq ); delete eq_eq; eq_eq = new Equation(); eq_eq->addAddend( 1, 13 ); eq_eq->setScalar( 0 ); - inputQuery.addEquation( *eq_eq); + inputQuery.addEquation( *eq_eq ); delete eq_eq; eq_eq = new Equation(); eq_eq->addAddend( 1, 17 ); eq_eq->setScalar( 0 ); - inputQuery.addEquation( *eq_eq); + inputQuery.addEquation( *eq_eq ); delete eq_eq; InputQuery processed = *( Preprocessor().preprocess( inputQuery ) ); @@ -911,8 +913,7 @@ class PreprocessorTestSuite : public CxxTest::TestSuite // x0 - x2 - aux4 = 0 will be added to the processed ipq. InputQuery processed; - TS_ASSERT_THROWS_NOTHING( processed = *( Preprocessor(). - preprocess( ipq ) ) ); + TS_ASSERT_THROWS_NOTHING( processed = *( Preprocessor().preprocess( ipq ) ) ); // Four more variables are added. TS_ASSERT_EQUALS( processed.getNumberOfVariables(), 7u ); @@ -950,13 +951,12 @@ class PreprocessorTestSuite : public CxxTest::TestSuite cs2.storeBoundTightening( Tightening( 0, -4, Tightening::LB ) ); cs2.storeBoundTightening( Tightening( 0, 2, Tightening::UB ) ); - List caseSplits = {cs1, cs2}; + List caseSplits = { cs1, cs2 }; DisjunctionConstraint *disj = new DisjunctionConstraint( caseSplits ); ipq.addPiecewiseLinearConstraint( disj ); InputQuery processed; - TS_ASSERT_THROWS_NOTHING( processed = *( Preprocessor(). - preprocess( ipq ) ) ); + TS_ASSERT_THROWS_NOTHING( processed = *( Preprocessor().preprocess( ipq ) ) ); TS_ASSERT_EQUALS( processed.getLowerBound( 0 ), -4 ) TS_ASSERT_EQUALS( processed.getUpperBound( 0 ), 3 ) @@ -964,7 +964,8 @@ class PreprocessorTestSuite : public CxxTest::TestSuite void test_todo() { - TS_TRACE( "In test_variable_elimination, test something about updated bounds and updated PL constraints" ); + TS_TRACE( "In test_variable_elimination, test something about updated bounds and updated " + "PL constraints" ); } }; diff --git a/src/engine/tests/Test_ProjectedSteepestEdge.h b/src/engine/tests/Test_ProjectedSteepestEdge.h index db66776468..74cbb89394 100644 --- a/src/engine/tests/Test_ProjectedSteepestEdge.h +++ b/src/engine/tests/Test_ProjectedSteepestEdge.h @@ -13,11 +13,11 @@ **/ -#include - #include "MockTableau.h" #include "ProjectedSteepestEdge.h" +#include + class MockForProjectedSteepestEdge { public: @@ -63,7 +63,7 @@ class ProjectedSteepestEdgeTestSuite : public CxxTest::TestSuite List candidates = { 0, 1, 2 }; double costFunction[] = { -5.0, -3.0, -7.0 }; - memcpy( tableau.nextCostFunction, costFunction, sizeof(costFunction) ); + memcpy( tableau.nextCostFunction, costFunction, sizeof( costFunction ) ); TS_ASSERT_THROWS_NOTHING( pse.select( tableau, candidates, excluded ) ); @@ -122,7 +122,7 @@ class ProjectedSteepestEdgeTestSuite : public CxxTest::TestSuite tableau.nextChangeColumn = changeColumn; double initialU[] = { 0, 0 }; double finalU[] = { 0, 0 }; - memcpy( tableau.nextBtranOutput, finalU, sizeof(double) * 2 ); + memcpy( tableau.nextBtranOutput, finalU, sizeof( double ) * 2 ); TableauRow pivotRow( 3 ); pivotRow._row[0]._coefficient = 3; @@ -146,7 +146,7 @@ class ProjectedSteepestEdgeTestSuite : public CxxTest::TestSuite TS_ASSERT( FloatUtils::areEqual( pse.getGamma( 1 ), 1.0 ) ); TS_ASSERT( FloatUtils::areEqual( pse.getGamma( 2 ), 2.0 ) ); - TS_ASSERT_SAME_DATA( tableau.lastBtranInput, initialU, sizeof(double) * 2 ); + TS_ASSERT_SAME_DATA( tableau.lastBtranInput, initialU, sizeof( double ) * 2 ); TS_ASSERT_THROWS_NOTHING( pse.postPivotHook( tableau, fakePivot ) ); TS_ASSERT( FloatUtils::areEqual( pse.getGamma( 0 ), 10.0 ) ); @@ -158,8 +158,10 @@ class ProjectedSteepestEdgeTestSuite : public CxxTest::TestSuite candidates.append( 0 ); candidates.append( 1 ); - costFunction[0] = 4.0; costFunction[1] = -2.0; costFunction[2] = -4.0; - memcpy( tableau.nextCostFunction, costFunction, sizeof(costFunction) ); + costFunction[0] = 4.0; + costFunction[1] = -2.0; + costFunction[2] = -4.0; + memcpy( tableau.nextCostFunction, costFunction, sizeof( costFunction ) ); TS_ASSERT_THROWS_NOTHING( pse.select( tableau, candidates, excluded ) ); TS_ASSERT_EQUALS( tableau.mockEnteringVariable, 1U ); @@ -175,18 +177,22 @@ class ProjectedSteepestEdgeTestSuite : public CxxTest::TestSuite tableau.nextBasicIndexToVariable[1] = 4; // Prepare the information that pse needs for updating gamme - changeColumn[0] = 1; changeColumn[1] = 2; + changeColumn[0] = 1; + changeColumn[1] = 2; tableau.nextChangeColumn = changeColumn; - initialU[0] = 1; initialU[1] = 0; - finalU[0] = -1; finalU[1] = 0; - memcpy( tableau.nextBtranOutput, finalU, sizeof(double) * 2 ); + initialU[0] = 1; + initialU[1] = 0; + finalU[0] = -1; + finalU[1] = 0; + memcpy( tableau.nextBtranOutput, finalU, sizeof( double ) * 2 ); pivotRow._row[0]._coefficient = -4; pivotRow._row[1]._coefficient = 2; pivotRow._row[2]._coefficient = 4; tableau.nextPivotRow = &pivotRow; - nextAColumn1[0] = 1; nextAColumn1[1] = 0; + nextAColumn1[0] = 1; + nextAColumn1[1] = 0; // Check that the gamma values reflect the recent (real) pivot fakePivot = false; @@ -207,7 +213,8 @@ class ProjectedSteepestEdgeTestSuite : public CxxTest::TestSuite void test_todo() { - TS_TRACE( "Move 'excluded' computation out to the Engine instead of repeating it in every invocation of PSE.select()" ); + TS_TRACE( "Move 'excluded' computation out to the Engine instead of repeating it in every " + "invocation of PSE.select()" ); } }; diff --git a/src/engine/tests/Test_PseudoImpactTracker.h b/src/engine/tests/Test_PseudoImpactTracker.h index bb5f471709..1f19627082 100644 --- a/src/engine/tests/Test_PseudoImpactTracker.h +++ b/src/engine/tests/Test_PseudoImpactTracker.h @@ -14,18 +14,17 @@ ** [[ Add lengthier description here ]] **/ -#include - -#include "context/context.h" -#include "PseudoImpactTracker.h" -#include "PiecewiseLinearConstraint.h" #include "PLConstraintScoreTracker.h" +#include "PiecewiseLinearConstraint.h" +#include "PseudoImpactTracker.h" #include "ReluConstraint.h" +#include "context/context.h" + +#include class PseudoImpactTrackerTestSuite : public CxxTest::TestSuite { public: - PLConstraintScoreTracker *_tracker; List _constraints; @@ -48,7 +47,7 @@ class PseudoImpactTrackerTestSuite : public CxxTest::TestSuite PiecewiseLinearConstraint *r2 = new ReluConstraint( 2, 3 ); PiecewiseLinearConstraint *r3 = new ReluConstraint( 4, 5 ); PiecewiseLinearConstraint *r4 = new ReluConstraint( 6, 7 ); - _constraints = {r1, r2, r3, r4}; + _constraints = { r1, r2, r3, r4 }; for ( const auto &constraint : _constraints ) constraint->initializeCDOs( &context ); @@ -61,8 +60,7 @@ class PseudoImpactTrackerTestSuite : public CxxTest::TestSuite double alpha = GlobalConfiguration::EXPONENTIAL_MOVING_AVERAGE_ALPHA; TS_ASSERT_EQUALS( _tracker->getScore( r1 ), alpha * 2 ); - TS_ASSERT_EQUALS( _tracker->getScore( r3 ), - (1 - alpha) * (alpha * 5) + alpha * 6 ); + TS_ASSERT_EQUALS( _tracker->getScore( r3 ), ( 1 - alpha ) * ( alpha * 5 ) + alpha * 6 ); r3->setActiveConstraint( false ); r1->setActiveConstraint( false ); @@ -82,7 +80,7 @@ class PseudoImpactTrackerTestSuite : public CxxTest::TestSuite PiecewiseLinearConstraint *r2 = new ReluConstraint( 2, 3 ); PiecewiseLinearConstraint *r3 = new ReluConstraint( 4, 5 ); PiecewiseLinearConstraint *r4 = new ReluConstraint( 6, 7 ); - _constraints = {r1, r2, r3, r4}; + _constraints = { r1, r2, r3, r4 }; for ( const auto &constraint : _constraints ) constraint->initializeCDOs( &context ); @@ -100,5 +98,4 @@ class PseudoImpactTrackerTestSuite : public CxxTest::TestSuite TS_ASSERT( _tracker->top() == r3 ); TS_ASSERT( _tracker->topUnfixed() == r2 ); } - }; diff --git a/src/engine/tests/Test_ReluConstraint.h b/src/engine/tests/Test_ReluConstraint.h index 4fd37923a8..311815180f 100644 --- a/src/engine/tests/Test_ReluConstraint.h +++ b/src/engine/tests/Test_ReluConstraint.h @@ -13,8 +13,6 @@ **/ -#include - #include "InputQuery.h" #include "LinearExpression.h" #include "MarabouError.h" @@ -24,12 +22,12 @@ #include "ReluConstraint.h" #include "context/context.h" +#include #include using namespace CVC4::context; -class MockForReluConstraint - : public MockErrno +class MockForReluConstraint : public MockErrno { public: }; @@ -40,9 +38,10 @@ class MockForReluConstraint class TestReluConstraint : public ReluConstraint { public: - TestReluConstraint(unsigned b, unsigned f) + TestReluConstraint( unsigned b, unsigned f ) : ReluConstraint( b, f ) - {} + { + } using ReluConstraint::getPhaseStatus; }; @@ -323,11 +322,14 @@ class ReluConstraintTestSuite : public CxxTest::TestSuite List::iterator split2 = split1; ++split2; - TS_ASSERT( isActiveSplitWithAux( b, auxVar, split1 ) || isActiveSplitWithAux( b, auxVar, split2 ) ); + TS_ASSERT( isActiveSplitWithAux( b, auxVar, split1 ) || + isActiveSplitWithAux( b, auxVar, split2 ) ); TS_ASSERT( isInactiveSplit( b, f, split1 ) || isInactiveSplit( b, f, split2 ) ); } - bool isActiveSplitWithAux( unsigned b, unsigned aux, List::iterator &split ) + bool isActiveSplitWithAux( unsigned b, + unsigned aux, + List::iterator &split ) { List bounds = split->getBoundTightenings(); @@ -799,8 +801,7 @@ class ReluConstraintTestSuite : public CxxTest::TestSuite String originalSerialized = originalRelu.serializeToString(); ReluConstraint recoveredRelu( originalSerialized ); - TS_ASSERT_EQUALS( originalRelu.serializeToString(), - recoveredRelu.serializeToString() ); + TS_ASSERT_EQUALS( originalRelu.serializeToString(), recoveredRelu.serializeToString() ); TS_ASSERT( !originalRelu.auxVariableInUse() ); TS_ASSERT( !recoveredRelu.auxVariableInUse() ); @@ -815,8 +816,7 @@ class ReluConstraintTestSuite : public CxxTest::TestSuite originalSerialized = originalRelu.serializeToString(); ReluConstraint recoveredRelu2( originalSerialized ); - TS_ASSERT_EQUALS( originalRelu.serializeToString(), - recoveredRelu2.serializeToString() ); + TS_ASSERT_EQUALS( originalRelu.serializeToString(), recoveredRelu2.serializeToString() ); TS_ASSERT( recoveredRelu2.auxVariableInUse() ); TS_ASSERT_EQUALS( originalRelu.getAux(), recoveredRelu2.getAux() ); @@ -1035,7 +1035,7 @@ class ReluConstraintTestSuite : public CxxTest::TestSuite ReluConstraint prepareRelu( unsigned b, unsigned f, unsigned aux, BoundManager *boundManager ) { ReluConstraint relu( b, f ); - boundManager->initialize( aux + 1); + boundManager->initialize( aux + 1 ); InputQuery dontCare; dontCare.setNumberOfVariables( aux ); @@ -1369,16 +1369,19 @@ class ReluConstraintTestSuite : public CxxTest::TestSuite Context context; ReluConstraint *relu1 = new ReluConstraint( 4, 6 ); - TS_ASSERT_EQUALS(relu1->getContext(), static_cast( static_cast( nullptr ) ) ); + TS_ASSERT_EQUALS( relu1->getContext(), + static_cast( static_cast( nullptr ) ) ); - TS_ASSERT_EQUALS( relu1->getActiveStatusCDO(), static_cast*>( nullptr ) ); - TS_ASSERT_EQUALS( relu1->getPhaseStatusCDO(), static_cast*>( nullptr ) ); - TS_ASSERT_EQUALS( relu1->getInfeasibleCasesCDList(), static_cast*>( nullptr ) ); + TS_ASSERT_EQUALS( relu1->getActiveStatusCDO(), static_cast *>( nullptr ) ); + TS_ASSERT_EQUALS( relu1->getPhaseStatusCDO(), static_cast *>( nullptr ) ); + TS_ASSERT_EQUALS( relu1->getInfeasibleCasesCDList(), + static_cast *>( nullptr ) ); TS_ASSERT_THROWS_NOTHING( relu1->initializeCDOs( &context ) ); TS_ASSERT_EQUALS( relu1->getContext(), &context ); - TS_ASSERT_DIFFERS( relu1->getActiveStatusCDO(), static_cast*>( nullptr ) ); - TS_ASSERT_DIFFERS( relu1->getPhaseStatusCDO(), static_cast*>( nullptr ) ); - TS_ASSERT_DIFFERS( relu1->getInfeasibleCasesCDList(), static_cast*>( nullptr ) ); + TS_ASSERT_DIFFERS( relu1->getActiveStatusCDO(), static_cast *>( nullptr ) ); + TS_ASSERT_DIFFERS( relu1->getPhaseStatusCDO(), static_cast *>( nullptr ) ); + TS_ASSERT_DIFFERS( relu1->getInfeasibleCasesCDList(), + static_cast *>( nullptr ) ); bool active = false; TS_ASSERT_THROWS_NOTHING( active = relu1->isActive() ); @@ -1540,11 +1543,9 @@ class ReluConstraintTestSuite : public CxxTest::TestSuite Map assignment; assignment[0] = -1; - TS_ASSERT_EQUALS( relu.getPhaseStatusInAssignment( assignment ), - RELU_PHASE_INACTIVE ); + TS_ASSERT_EQUALS( relu.getPhaseStatusInAssignment( assignment ), RELU_PHASE_INACTIVE ); assignment[0] = 15; - TS_ASSERT_EQUALS( relu.getPhaseStatusInAssignment( assignment ), - RELU_PHASE_ACTIVE ); + TS_ASSERT_EQUALS( relu.getPhaseStatusInAssignment( assignment ), RELU_PHASE_ACTIVE ); } }; diff --git a/src/engine/tests/Test_RoundConstraint.h b/src/engine/tests/Test_RoundConstraint.h index c3cf7d1059..b779771b31 100644 --- a/src/engine/tests/Test_RoundConstraint.h +++ b/src/engine/tests/Test_RoundConstraint.h @@ -13,12 +13,12 @@ **/ -#include - #include "InputQuery.h" #include "MarabouError.h" #include "MockTableau.h" #include "RoundConstraint.h" + +#include #include class MockForRoundConstraint @@ -67,7 +67,7 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite TS_ASSERT( !round.constraintObsolete() ); // eliminate variable b - round.eliminateVariable( b, 0 ); // 0 is dummy for the argument of fixedValue + round.eliminateVariable( b, 0 ); // 0 is dummy for the argument of fixedValue // round is obsolete now TS_ASSERT( round.constraintObsolete() ); @@ -102,7 +102,7 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite TS_ASSERT( !round2->participatingVariable( 5 ) ); // eliminate variable b - round->eliminateVariable( b, 0 ); // 0 is dummy for the argument of fixedValue + round->eliminateVariable( b, 0 ); // 0 is dummy for the argument of fixedValue // round is obsolete now TS_ASSERT( round->constraintObsolete() ); @@ -127,7 +127,11 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite return false; } - bool testBound( unsigned b, unsigned f, unsigned variable, double lb, double ub, + bool testBound( unsigned b, + unsigned f, + unsigned variable, + double lb, + double ub, const List &expectedBounds ) { RoundConstraint round( b, f ); @@ -153,111 +157,91 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite { // Case 1 - List expectedTightenings = { - Tightening( b, -10, Tightening::LB ), - Tightening( b, -10, Tightening::UB ), - Tightening( f, -10, Tightening::LB ), - Tightening( f, -10, Tightening::UB ) - }; + List expectedTightenings = { Tightening( b, -10, Tightening::LB ), + Tightening( b, -10, Tightening::UB ), + Tightening( f, -10, Tightening::LB ), + Tightening( f, -10, Tightening::UB ) }; TS_ASSERT( testBound( b, f, b, -10, -10, expectedTightenings ) ); } { // Case 2 - List expectedTightenings = { - Tightening( b, -9.9, Tightening::LB ), - Tightening( b, -9.9, Tightening::UB ), - Tightening( f, -10, Tightening::LB ), - Tightening( f, -10, Tightening::UB ) - }; + List expectedTightenings = { Tightening( b, -9.9, Tightening::LB ), + Tightening( b, -9.9, Tightening::UB ), + Tightening( f, -10, Tightening::LB ), + Tightening( f, -10, Tightening::UB ) }; TS_ASSERT( testBound( b, f, b, -9.9, -9.9, expectedTightenings ) ); } { // Case 3 - List expectedTightenings = { - Tightening( b, -9.5, Tightening::LB ), - Tightening( b, -9.5, Tightening::UB ), - Tightening( f, -10, Tightening::LB ), - Tightening( f, -10, Tightening::UB ) - }; + List expectedTightenings = { Tightening( b, -9.5, Tightening::LB ), + Tightening( b, -9.5, Tightening::UB ), + Tightening( f, -10, Tightening::LB ), + Tightening( f, -10, Tightening::UB ) }; TS_ASSERT( testBound( b, f, b, -9.5, -9.5, expectedTightenings ) ); } { // Case 4 - List expectedTightenings = { - Tightening( b, -9.3, Tightening::LB ), - Tightening( b, -9.3, Tightening::UB ), - Tightening( f, -9, Tightening::LB ), - Tightening( f, -9, Tightening::UB ) - }; + List expectedTightenings = { Tightening( b, -9.3, Tightening::LB ), + Tightening( b, -9.3, Tightening::UB ), + Tightening( f, -9, Tightening::LB ), + Tightening( f, -9, Tightening::UB ) }; TS_ASSERT( testBound( b, f, b, -9.3, -9.3, expectedTightenings ) ); } { // Case 5 - List expectedTightenings = { - Tightening( b, -8.5, Tightening::LB ), - Tightening( b, -8.5, Tightening::UB ), - Tightening( f, -8, Tightening::LB ), - Tightening( f, -8, Tightening::UB ) - }; + List expectedTightenings = { Tightening( b, -8.5, Tightening::LB ), + Tightening( b, -8.5, Tightening::UB ), + Tightening( f, -8, Tightening::LB ), + Tightening( f, -8, Tightening::UB ) }; TS_ASSERT( testBound( b, f, b, -8.5, -8.5, expectedTightenings ) ); } { // Case 6 - List expectedTightenings = { - Tightening( b, 10, Tightening::LB ), - Tightening( b, 10, Tightening::UB ), - Tightening( f, 10, Tightening::LB ), - Tightening( f, 10, Tightening::UB ) - }; + List expectedTightenings = { Tightening( b, 10, Tightening::LB ), + Tightening( b, 10, Tightening::UB ), + Tightening( f, 10, Tightening::LB ), + Tightening( f, 10, Tightening::UB ) }; TS_ASSERT( testBound( b, f, b, 10, 10, expectedTightenings ) ); } { // Case 7 - List expectedTightenings = { - Tightening( b, 9.9, Tightening::LB ), - Tightening( b, 9.9, Tightening::UB ), - Tightening( f, 10, Tightening::LB ), - Tightening( f, 10, Tightening::UB ) - }; + List expectedTightenings = { Tightening( b, 9.9, Tightening::LB ), + Tightening( b, 9.9, Tightening::UB ), + Tightening( f, 10, Tightening::LB ), + Tightening( f, 10, Tightening::UB ) }; TS_ASSERT( testBound( b, f, b, 9.9, 9.9, expectedTightenings ) ); } { // Case 8 - List expectedTightenings = { - Tightening( b, 9.5, Tightening::LB ), - Tightening( b, 9.5, Tightening::UB ), - Tightening( f, 10, Tightening::LB ), - Tightening( f, 10, Tightening::UB ) - }; + List expectedTightenings = { Tightening( b, 9.5, Tightening::LB ), + Tightening( b, 9.5, Tightening::UB ), + Tightening( f, 10, Tightening::LB ), + Tightening( f, 10, Tightening::UB ) }; TS_ASSERT( testBound( b, f, b, 9.5, 9.5, expectedTightenings ) ); } { // Case 9 - List expectedTightenings = { - Tightening( b, 9.3, Tightening::LB ), - Tightening( b, 9.3, Tightening::UB ), - Tightening( f, 9, Tightening::LB ), - Tightening( f, 9, Tightening::UB ) - }; + List expectedTightenings = { Tightening( b, 9.3, Tightening::LB ), + Tightening( b, 9.3, Tightening::UB ), + Tightening( f, 9, Tightening::LB ), + Tightening( f, 9, Tightening::UB ) }; TS_ASSERT( testBound( b, f, b, 9.3, 9.3, expectedTightenings ) ); } { // Case 10 - List expectedTightenings = { - Tightening( b, 8.5, Tightening::LB ), - Tightening( b, 8.5, Tightening::UB ), - Tightening( f, 8, Tightening::LB ), - Tightening( f, 8, Tightening::UB ) - }; + List expectedTightenings = { Tightening( b, 8.5, Tightening::LB ), + Tightening( b, 8.5, Tightening::UB ), + Tightening( f, 8, Tightening::LB ), + Tightening( f, 8, Tightening::UB ) }; TS_ASSERT( testBound( b, f, b, 8.5, 8.5, expectedTightenings ) ); } @@ -269,111 +253,91 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite unsigned f = 4; { // Case 1 - List expectedTightenings = { - Tightening( b, -10.5, Tightening::LB ), - Tightening( b, -9.5, Tightening::UB ), - Tightening( f, -10, Tightening::LB ), - Tightening( f, -10, Tightening::UB ) - }; + List expectedTightenings = { Tightening( b, -10.5, Tightening::LB ), + Tightening( b, -9.5, Tightening::UB ), + Tightening( f, -10, Tightening::LB ), + Tightening( f, -10, Tightening::UB ) }; TS_ASSERT( testBound( b, f, f, -10, -10, expectedTightenings ) ); } { // Case 2 - List expectedTightenings = { - Tightening( b, -9.5, Tightening::LB ), - Tightening( b, -9.5, Tightening::UB ), - Tightening( f, -9, Tightening::LB ), - Tightening( f, -10, Tightening::UB ) - }; + List expectedTightenings = { Tightening( b, -9.5, Tightening::LB ), + Tightening( b, -9.5, Tightening::UB ), + Tightening( f, -9, Tightening::LB ), + Tightening( f, -10, Tightening::UB ) }; TS_ASSERT( testBound( b, f, f, -9.9, -9.9, expectedTightenings ) ); } { // Case 3 - List expectedTightenings = { - Tightening( b, -9.5, Tightening::LB ), - Tightening( b, -9.5, Tightening::UB ), - Tightening( f, -9, Tightening::LB ), - Tightening( f, -10, Tightening::UB ) - }; + List expectedTightenings = { Tightening( b, -9.5, Tightening::LB ), + Tightening( b, -9.5, Tightening::UB ), + Tightening( f, -9, Tightening::LB ), + Tightening( f, -10, Tightening::UB ) }; TS_ASSERT( testBound( b, f, f, -9.5, -9.5, expectedTightenings ) ); } { // Case 4 - List expectedTightenings = { - Tightening( b, -9.5, Tightening::LB ), - Tightening( b, -9.5, Tightening::UB ), - Tightening( f, -9, Tightening::LB ), - Tightening( f, -10, Tightening::UB ) - }; + List expectedTightenings = { Tightening( b, -9.5, Tightening::LB ), + Tightening( b, -9.5, Tightening::UB ), + Tightening( f, -9, Tightening::LB ), + Tightening( f, -10, Tightening::UB ) }; TS_ASSERT( testBound( b, f, f, -9.3, -9.3, expectedTightenings ) ); } { // Case 5 - List expectedTightenings = { - Tightening( b, -8.5, Tightening::LB ), - Tightening( b, -8.5, Tightening::UB ), - Tightening( f, -8, Tightening::LB ), - Tightening( f, -9, Tightening::UB ) - }; + List expectedTightenings = { Tightening( b, -8.5, Tightening::LB ), + Tightening( b, -8.5, Tightening::UB ), + Tightening( f, -8, Tightening::LB ), + Tightening( f, -9, Tightening::UB ) }; TS_ASSERT( testBound( b, f, f, -8.5, -8.5, expectedTightenings ) ); } { // Case 6 - List expectedTightenings = { - Tightening( b, 9.5, Tightening::LB ), - Tightening( b, 10.5, Tightening::UB ), - Tightening( f, 10, Tightening::LB ), - Tightening( f, 10, Tightening::UB ) - }; + List expectedTightenings = { Tightening( b, 9.5, Tightening::LB ), + Tightening( b, 10.5, Tightening::UB ), + Tightening( f, 10, Tightening::LB ), + Tightening( f, 10, Tightening::UB ) }; TS_ASSERT( testBound( b, f, f, 10, 10, expectedTightenings ) ); } { // Case 7 - List expectedTightenings = { - Tightening( b, 9.5, Tightening::LB ), - Tightening( b, 9.5, Tightening::UB ), - Tightening( f, 10, Tightening::LB ), - Tightening( f, 9, Tightening::UB ) - }; + List expectedTightenings = { Tightening( b, 9.5, Tightening::LB ), + Tightening( b, 9.5, Tightening::UB ), + Tightening( f, 10, Tightening::LB ), + Tightening( f, 9, Tightening::UB ) }; TS_ASSERT( testBound( b, f, f, 9.9, 9.9, expectedTightenings ) ); } { // Case 8 - List expectedTightenings = { - Tightening( b, 9.5, Tightening::LB ), - Tightening( b, 9.5, Tightening::UB ), - Tightening( f, 10, Tightening::LB ), - Tightening( f, 9, Tightening::UB ) - }; + List expectedTightenings = { Tightening( b, 9.5, Tightening::LB ), + Tightening( b, 9.5, Tightening::UB ), + Tightening( f, 10, Tightening::LB ), + Tightening( f, 9, Tightening::UB ) }; TS_ASSERT( testBound( b, f, f, 9.5, 9.5, expectedTightenings ) ); } { // Case 9 - List expectedTightenings = { - Tightening( b, 9.5, Tightening::LB ), - Tightening( b, 9.5, Tightening::UB ), - Tightening( f, 10, Tightening::LB ), - Tightening( f, 9, Tightening::UB ) - }; + List expectedTightenings = { Tightening( b, 9.5, Tightening::LB ), + Tightening( b, 9.5, Tightening::UB ), + Tightening( f, 10, Tightening::LB ), + Tightening( f, 9, Tightening::UB ) }; TS_ASSERT( testBound( b, f, f, 9.3, 9.3, expectedTightenings ) ); } { // Case 10 - List expectedTightenings = { - Tightening( b, 8.5, Tightening::LB ), - Tightening( b, 8.5, Tightening::UB ), - Tightening( f, 9, Tightening::LB ), - Tightening( f, 8, Tightening::UB ) - }; + List expectedTightenings = { Tightening( b, 8.5, Tightening::LB ), + Tightening( b, 8.5, Tightening::UB ), + Tightening( f, 9, Tightening::LB ), + Tightening( f, 8, Tightening::UB ) }; TS_ASSERT( testBound( b, f, f, 8.5, 8.5, expectedTightenings ) ); } diff --git a/src/engine/tests/Test_RowBoundTightener.h b/src/engine/tests/Test_RowBoundTightener.h index 527f000fbf..ac48dfac72 100644 --- a/src/engine/tests/Test_RowBoundTightener.h +++ b/src/engine/tests/Test_RowBoundTightener.h @@ -13,12 +13,12 @@ **/ -#include - -#include "MockTableau.h" #include "GlobalConfiguration.h" +#include "MockTableau.h" #include "RowBoundTightener.h" +#include + class MockForRowBoundTightener { public: @@ -95,19 +95,25 @@ class RowBoundTightenerTestSuite : public CxxTest::TestSuite TS_ASSERT_EQUALS( tightenings.size(), 2U ); auto lower = tightenings.begin(); - while ( ( lower != tightenings.end() ) && !( ( lower->_variable == 0 ) && ( lower->_type == Tightening::LB ) ) ) + while ( ( lower != tightenings.end() ) && + !( ( lower->_variable == 0 ) && ( lower->_type == Tightening::LB ) ) ) ++lower; TS_ASSERT( lower != tightenings.end() ); auto upper = tightenings.begin(); - while ( ( upper != tightenings.end() ) && !( ( upper->_variable == 0 ) && ( upper->_type == Tightening::UB ) ) ) + while ( ( upper != tightenings.end() ) && + !( ( upper->_variable == 0 ) && ( upper->_type == Tightening::UB ) ) ) ++upper; TS_ASSERT( upper != tightenings.end() ); // LB -> 1 - 10 - 4 -100 // UB -> 1 - 5 + 6 + 100 - TS_ASSERT_EQUALS( lower->_value, -113 - GlobalConfiguration::EXPLICIT_BASIS_BOUND_TIGHTENING_ROUNDING_CONSTANT ); - TS_ASSERT_EQUALS( upper->_value, 102 + GlobalConfiguration::EXPLICIT_BASIS_BOUND_TIGHTENING_ROUNDING_CONSTANT ); + TS_ASSERT_EQUALS( + lower->_value, + -113 - GlobalConfiguration::EXPLICIT_BASIS_BOUND_TIGHTENING_ROUNDING_CONSTANT ); + TS_ASSERT_EQUALS( + upper->_value, + 102 + GlobalConfiguration::EXPLICIT_BASIS_BOUND_TIGHTENING_ROUNDING_CONSTANT ); } void test_pivot_row_just_upper_tightend() @@ -119,7 +125,6 @@ class RowBoundTightenerTestSuite : public CxxTest::TestSuite tableau->getBoundManager().getUpperBounds() ); - // Current bounds: // 0 <= x0 <= 0 // 5 <= x1 <= 10 @@ -159,7 +164,8 @@ class RowBoundTightenerTestSuite : public CxxTest::TestSuite TS_ASSERT_THROWS_NOTHING( tightener.getRowTightenings( tightenings ) ); auto upper = tightenings.begin(); - while ( ( upper != tightenings.end() ) && !( ( upper->_variable == 0 ) && ( upper->_type == Tightening::UB ) ) ) + while ( ( upper != tightenings.end() ) && + !( ( upper->_variable == 0 ) && ( upper->_type == Tightening::UB ) ) ) ++upper; TS_ASSERT( upper != tightenings.end() ); @@ -167,7 +173,9 @@ class RowBoundTightenerTestSuite : public CxxTest::TestSuite TS_ASSERT_EQUALS( upper->_type, Tightening::UB ); // Lower: 1 - 10 - 4, Upper: 1 - 5 + 6 - TS_ASSERT_EQUALS( upper->_value, 2 + GlobalConfiguration::EXPLICIT_BASIS_BOUND_TIGHTENING_ROUNDING_CONSTANT ); + TS_ASSERT_EQUALS( + upper->_value, + 2 + GlobalConfiguration::EXPLICIT_BASIS_BOUND_TIGHTENING_ROUNDING_CONSTANT ); } void test_pivot_row__just_lower_tightend() @@ -179,7 +187,6 @@ class RowBoundTightenerTestSuite : public CxxTest::TestSuite tableau->getBoundManager().getUpperBounds() ); - TS_ASSERT_THROWS_NOTHING( tableau->setLowerBound( 0, -200 ) ); TS_ASSERT_THROWS_NOTHING( tableau->setUpperBound( 0, 0 ) ); TS_ASSERT_THROWS_NOTHING( tableau->setLowerBound( 1, 5 ) ); @@ -188,7 +195,7 @@ class RowBoundTightenerTestSuite : public CxxTest::TestSuite TS_ASSERT_THROWS_NOTHING( tableau->setUpperBound( 2, 3 ) ); TS_ASSERT_THROWS_NOTHING( tableau->setLowerBound( 3, -5 ) ); TS_ASSERT_THROWS_NOTHING( tableau->setUpperBound( 3, 5 ) ); - TS_ASSERT_THROWS_NOTHING( tableau->setLowerBound( 4, 0) ); + TS_ASSERT_THROWS_NOTHING( tableau->setLowerBound( 4, 0 ) ); TS_ASSERT_THROWS_NOTHING( tableau->setUpperBound( 4, 0 ) ); TS_ASSERT_THROWS_NOTHING( tightener.setDimensions() ); @@ -220,7 +227,9 @@ class RowBoundTightenerTestSuite : public CxxTest::TestSuite TS_ASSERT_EQUALS( lower._type, Tightening::LB ); // Lower: 1 - 10 - 4, Lower: 1 - 5 + 6 - TS_ASSERT_EQUALS( lower._value, -13 - GlobalConfiguration::EXPLICIT_BASIS_BOUND_TIGHTENING_ROUNDING_CONSTANT ); + TS_ASSERT_EQUALS( + lower._value, + -13 - GlobalConfiguration::EXPLICIT_BASIS_BOUND_TIGHTENING_ROUNDING_CONSTANT ); } void test_pivot_row__nothing_tightened() @@ -272,7 +281,7 @@ class RowBoundTightenerTestSuite : public CxxTest::TestSuite tightener.setBoundsPointers( tableau->getBoundManager().getLowerBounds(), tableau->getBoundManager().getUpperBounds() ); - TS_ASSERT_THROWS_NOTHING( tableau->setLowerBound( 0, 0) ); + TS_ASSERT_THROWS_NOTHING( tableau->setLowerBound( 0, 0 ) ); TS_ASSERT_THROWS_NOTHING( tableau->setUpperBound( 0, 3 ) ); TS_ASSERT_THROWS_NOTHING( tableau->setLowerBound( 1, -1 ) ); TS_ASSERT_THROWS_NOTHING( tableau->setUpperBound( 1, 2 ) ); @@ -319,8 +328,14 @@ class RowBoundTightenerTestSuite : public CxxTest::TestSuite TS_ASSERT_THROWS_NOTHING( tightener.getRowTightenings( tightenings ) ); TS_ASSERT_EQUALS( tightenings.size(), 2U ); - TS_ASSERT_DIFFERS( std::find( tightenings.begin(), tightenings.end(), Tightening( 0U, 1.0, Tightening::UB ) ), tightenings.end()); - TS_ASSERT_DIFFERS( std::find( tightenings.begin(), tightenings.end(), Tightening( 1U, 1.5, Tightening::LB ) ), tightenings.end()); + TS_ASSERT_DIFFERS( std::find( tightenings.begin(), + tightenings.end(), + Tightening( 0U, 1.0, Tightening::UB ) ), + tightenings.end() ); + TS_ASSERT_DIFFERS( std::find( tightenings.begin(), + tightenings.end(), + Tightening( 1U, 1.5, Tightening::LB ) ), + tightenings.end() ); } void test_examine_constraint_matrix_multiple_equations() @@ -367,8 +382,7 @@ class RowBoundTightenerTestSuite : public CxxTest::TestSuite */ double A[] = { - 1, -2, 0, 1, 2, - 0, -2, 1, 0, 0, + 1, -2, 0, 1, 2, 0, -2, 1, 0, 0, }; double b[] = { 1, -2 }; @@ -386,10 +400,21 @@ class RowBoundTightenerTestSuite : public CxxTest::TestSuite TS_ASSERT_THROWS_NOTHING( tightener.getRowTightenings( tightenings ) ); TS_ASSERT_EQUALS( tightenings.size(), 4U ); - TS_ASSERT_DIFFERS( std::find( tightenings.begin(), tightenings.end(), Tightening( 0U, 1.0, Tightening::UB ) ), tightenings.end()); - TS_ASSERT_DIFFERS( std::find( tightenings.begin(), tightenings.end(), Tightening( 1U, 1.5, Tightening::LB ) ), tightenings.end()); - TS_ASSERT_DIFFERS( std::find( tightenings.begin(), tightenings.end(), Tightening( 2U, 1.0, Tightening::LB ) ), tightenings.end()); - TS_ASSERT_DIFFERS( std::find( tightenings.begin(), tightenings.end(), Tightening( 2U, 2.0, Tightening::UB ) ), tightenings.end()); - + TS_ASSERT_DIFFERS( std::find( tightenings.begin(), + tightenings.end(), + Tightening( 0U, 1.0, Tightening::UB ) ), + tightenings.end() ); + TS_ASSERT_DIFFERS( std::find( tightenings.begin(), + tightenings.end(), + Tightening( 1U, 1.5, Tightening::LB ) ), + tightenings.end() ); + TS_ASSERT_DIFFERS( std::find( tightenings.begin(), + tightenings.end(), + Tightening( 2U, 1.0, Tightening::LB ) ), + tightenings.end() ); + TS_ASSERT_DIFFERS( std::find( tightenings.begin(), + tightenings.end(), + Tightening( 2U, 2.0, Tightening::UB ) ), + tightenings.end() ); } }; diff --git a/src/engine/tests/Test_SigmoidConstraint.h b/src/engine/tests/Test_SigmoidConstraint.h index a4eb7a6d87..ee1f1b9d37 100644 --- a/src/engine/tests/Test_SigmoidConstraint.h +++ b/src/engine/tests/Test_SigmoidConstraint.h @@ -13,12 +13,12 @@ **/ -#include - #include "InputQuery.h" #include "MarabouError.h" -#include "SigmoidConstraint.h" #include "MockTableau.h" +#include "SigmoidConstraint.h" + +#include #include class MockForSigmoidConstraint @@ -32,9 +32,10 @@ class MockForSigmoidConstraint class TestSigmoidConstraint : public SigmoidConstraint { public: - TestSigmoidConstraint( unsigned b, unsigned f ) + TestSigmoidConstraint( unsigned b, unsigned f ) : SigmoidConstraint( b, f ) - {} + { + } }; class MaxConstraintTestSuite : public CxxTest::TestSuite @@ -78,7 +79,7 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite TS_ASSERT( !sigmoid.constraintObsolete() ); // eliminate variable b - sigmoid.eliminateVariable( b, 0 ); // 0 is dummy for the argument of fixedValue + sigmoid.eliminateVariable( b, 0 ); // 0 is dummy for the argument of fixedValue // sigmoid is obsolete now TS_ASSERT( sigmoid.constraintObsolete() ); @@ -98,7 +99,8 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite TS_ASSERT( !sigmoid->constraintObsolete() ); // duplicate constraint - SigmoidConstraint *sigmoid2 = dynamic_cast( sigmoid->duplicateConstraint() ); + SigmoidConstraint *sigmoid2 = + dynamic_cast( sigmoid->duplicateConstraint() ); TS_ASSERT_THROWS_NOTHING( participatingVariables = sigmoid2->getParticipatingVariables() ); TS_ASSERT_EQUALS( participatingVariables.size(), 2U ); auto it = participatingVariables.begin(); @@ -113,7 +115,7 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite TS_ASSERT( !sigmoid2->participatingVariable( 5 ) ); // eliminate variable b - sigmoid->eliminateVariable( b, 0 ); // 0 is dummy for the argument of fixedValue + sigmoid->eliminateVariable( b, 0 ); // 0 is dummy for the argument of fixedValue // sigmoid is obsolete now TS_ASSERT( sigmoid->constraintObsolete() ); @@ -185,7 +187,7 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite ++it; TS_ASSERT_EQUALS( it->_type, Tightening::UB ); TS_ASSERT_EQUALS( it->_variable, f ); - TS_ASSERT( FloatUtils::areEqual( it->_value, 1- 0.26894142, 0.001 ) ); + TS_ASSERT( FloatUtils::areEqual( it->_value, 1 - 0.26894142, 0.001 ) ); } void test_sigmoid_notify_bounds_f() @@ -219,7 +221,7 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite ++it; TS_ASSERT_EQUALS( it->_type, Tightening::UB ); TS_ASSERT_EQUALS( it->_variable, f ); - TS_ASSERT( FloatUtils::areEqual( it->_value, 1- 0.26894142, 0.001 ) ); + TS_ASSERT( FloatUtils::areEqual( it->_value, 1 - 0.26894142, 0.001 ) ); } void test_sigmoid_update_variable_index() @@ -281,7 +283,7 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite ++it; TS_ASSERT_EQUALS( it->_type, Tightening::UB ); TS_ASSERT_EQUALS( it->_variable, new_f ); - TS_ASSERT( FloatUtils::areEqual( it->_value, 1- 0.26894142, 0.001 ) ); + TS_ASSERT( FloatUtils::areEqual( it->_value, 1 - 0.26894142, 0.001 ) ); } } @@ -366,6 +368,5 @@ class MaxConstraintTestSuite : public CxxTest::TestSuite tableau.setValue( b1, 1 ); tableau.setValue( f1, 0.73105857863 ); TS_ASSERT( sigmoid.satisfied() ); - } }; diff --git a/src/engine/tests/Test_SignConstraint.h b/src/engine/tests/Test_SignConstraint.h index 285791abeb..2839585f1c 100644 --- a/src/engine/tests/Test_SignConstraint.h +++ b/src/engine/tests/Test_SignConstraint.h @@ -13,8 +13,6 @@ **/ -#include - #include "InputQuery.h" #include "MarabouError.h" #include "MockErrno.h" @@ -22,10 +20,10 @@ #include "PiecewiseLinearCaseSplit.h" #include "SignConstraint.h" +#include #include -class MockForSignConstraint - : public MockErrno +class MockForSignConstraint : public MockErrno { public: }; @@ -38,7 +36,8 @@ class TestSignConstraint : public SignConstraint public: TestSignConstraint( unsigned b, unsigned f ) : SignConstraint( b, f ) - {} + { + } using PiecewiseLinearConstraint::getPhaseStatus; }; @@ -239,16 +238,14 @@ class SignConstraintTestSuite : public CxxTest::TestSuite } // Return true only if the 2 bounds match and there are no equations - bool isPositiveSplit( unsigned b, unsigned f, - List::iterator &split ) + bool isPositiveSplit( unsigned b, unsigned f, List::iterator &split ) { List bounds = split->getBoundTightenings(); auto bound = bounds.begin(); Tightening bound1 = *bound; - if ( ( bound1._variable != b ) || - ( bound1._value != 0.0 ) || + if ( ( bound1._variable != b ) || ( bound1._value != 0.0 ) || ( bound1._type != Tightening::LB ) ) return false; @@ -258,8 +255,7 @@ class SignConstraintTestSuite : public CxxTest::TestSuite ++bound; Tightening bound2 = *bound; - if ( ( bound2._variable != f ) || - ( bound2._value != 1 ) || + if ( ( bound2._variable != f ) || ( bound2._value != 1 ) || ( bound2._type != Tightening::LB ) ) return false; @@ -270,16 +266,14 @@ class SignConstraintTestSuite : public CxxTest::TestSuite } // Return true only if the 2 bounds match and there are no equations - bool isNegativeSplit( unsigned b, unsigned f, - List::iterator &split ) + bool isNegativeSplit( unsigned b, unsigned f, List::iterator &split ) { List bounds = split->getBoundTightenings(); auto bound = bounds.begin(); Tightening bound1 = *bound; - if ( ( bound1._variable != b ) || - ( bound1._value != 0.0 ) || + if ( ( bound1._variable != b ) || ( bound1._value != 0.0 ) || ( bound1._type != Tightening::UB ) ) return false; @@ -289,8 +283,7 @@ class SignConstraintTestSuite : public CxxTest::TestSuite ++bound; Tightening bound2 = *bound; - if ( ( bound2._variable != f ) || - ( bound2._value != -1 ) || + if ( ( bound2._variable != f ) || ( bound2._value != -1 ) || ( bound2._type != Tightening::UB ) ) return false; @@ -347,7 +340,7 @@ class SignConstraintTestSuite : public CxxTest::TestSuite TS_ASSERT_EQUALS( splits.size(), 2U ); - sign.registerBoundManager( boundManager ); + sign.registerBoundManager( boundManager ); sign.notifyLowerBound( 1, 0 ); TS_ASSERT_THROWS_EQUALS( splits = sign.getCaseSplits(), const MarabouError &e, @@ -357,7 +350,7 @@ class SignConstraintTestSuite : public CxxTest::TestSuite sign.unregisterAsWatcher( &tableau ); sign = SignConstraint( b, f ); - sign.registerBoundManager( boundManager ); + sign.registerBoundManager( boundManager ); sign.registerAsWatcher( &tableau ); splits = sign.getCaseSplits(); @@ -378,14 +371,15 @@ class SignConstraintTestSuite : public CxxTest::TestSuite unsigned f = 4; MockTableau tableau; - IBoundManager *boundManager = &tableau.getBoundManager();; + IBoundManager *boundManager = &tableau.getBoundManager(); + ; boundManager->initialize( 5 ); SignConstraint sign( b, f ); sign.registerAsWatcher( &tableau ); - sign.registerBoundManager( boundManager ); + sign.registerBoundManager( boundManager ); List splits = sign.getCaseSplits(); TS_ASSERT_EQUALS( splits.size(), 2U ); @@ -401,7 +395,7 @@ class SignConstraintTestSuite : public CxxTest::TestSuite sign = SignConstraint( b, f ); sign.registerAsWatcher( &tableau ); - sign.registerBoundManager( boundManager ); + sign.registerBoundManager( boundManager ); splits = sign.getCaseSplits(); TS_ASSERT_EQUALS( splits.size(), 2U ); @@ -420,7 +414,8 @@ class SignConstraintTestSuite : public CxxTest::TestSuite unsigned f = 4; MockTableau tableau; - IBoundManager *boundManager = &tableau.getBoundManager();; + IBoundManager *boundManager = &tableau.getBoundManager(); + ; boundManager->initialize( 5 ); // Upper bounds @@ -819,7 +814,6 @@ class SignConstraintTestSuite : public CxxTest::TestSuite entailedTightenings2.clear(); } - } SignConstraint prepareSign( unsigned b, unsigned f, IBoundManager *boundManager ) { @@ -965,7 +959,6 @@ class SignConstraintTestSuite : public CxxTest::TestSuite tightenings.clear(); } } - } void test_serialize_and_unserialize() @@ -980,8 +973,7 @@ class SignConstraintTestSuite : public CxxTest::TestSuite String originalSerialized = originalSign.serializeToString(); SignConstraint recoveredSign( originalSerialized ); - TS_ASSERT_EQUALS( originalSign.serializeToString(), - recoveredSign.serializeToString() ); + TS_ASSERT_EQUALS( originalSign.serializeToString(), recoveredSign.serializeToString() ); } void test_polarity() @@ -1048,15 +1040,17 @@ class SignConstraintTestSuite : public CxxTest::TestSuite Context context; SignConstraint *sign1 = new SignConstraint( 4, 6 ); - TS_ASSERT_EQUALS( sign1->getContext(), static_cast( nullptr ) ); - TS_ASSERT_EQUALS( sign1->getActiveStatusCDO(), static_cast*>( nullptr ) ); - TS_ASSERT_EQUALS( sign1->getPhaseStatusCDO(), static_cast*>( nullptr ) ); - TS_ASSERT_EQUALS( sign1->getInfeasibleCasesCDList(), static_cast*>( nullptr ) ); + TS_ASSERT_EQUALS( sign1->getContext(), static_cast( nullptr ) ); + TS_ASSERT_EQUALS( sign1->getActiveStatusCDO(), static_cast *>( nullptr ) ); + TS_ASSERT_EQUALS( sign1->getPhaseStatusCDO(), static_cast *>( nullptr ) ); + TS_ASSERT_EQUALS( sign1->getInfeasibleCasesCDList(), + static_cast *>( nullptr ) ); TS_ASSERT_THROWS_NOTHING( sign1->initializeCDOs( &context ) ); TS_ASSERT_EQUALS( sign1->getContext(), &context ); - TS_ASSERT_DIFFERS( sign1->getActiveStatusCDO(), static_cast*>( nullptr ) ); - TS_ASSERT_DIFFERS( sign1->getPhaseStatusCDO(), static_cast*>( nullptr ) ); - TS_ASSERT_DIFFERS( sign1->getInfeasibleCasesCDList(), static_cast*>( nullptr ) ); + TS_ASSERT_DIFFERS( sign1->getActiveStatusCDO(), static_cast *>( nullptr ) ); + TS_ASSERT_DIFFERS( sign1->getPhaseStatusCDO(), static_cast *>( nullptr ) ); + TS_ASSERT_DIFFERS( sign1->getInfeasibleCasesCDList(), + static_cast *>( nullptr ) ); bool active = false; TS_ASSERT_THROWS_NOTHING( active = sign1->isActive() ); @@ -1132,7 +1126,8 @@ class SignConstraintTestSuite : public CxxTest::TestSuite // The sign is fixed, do not add cost term. SignConstraint sign1 = SignConstraint( b, f ); MockTableau tableau; - IBoundManager *boundManager = &tableau.getBoundManager();; + IBoundManager *boundManager = &tableau.getBoundManager(); + ; boundManager->initialize( 6 ); sign1.registerBoundManager( boundManager ); @@ -1214,7 +1209,8 @@ class SignConstraintTestSuite : public CxxTest::TestSuite SignConstraint sign = SignConstraint( b, f ); MockTableau tableau; - IBoundManager *boundManager = &tableau.getBoundManager();; + IBoundManager *boundManager = &tableau.getBoundManager(); + ; sign.registerBoundManager( boundManager ); tableau.setValue( b, 1.5 ); @@ -1222,12 +1218,10 @@ class SignConstraintTestSuite : public CxxTest::TestSuite Map assignment; assignment[0] = -1; - TS_ASSERT_EQUALS( sign.getPhaseStatusInAssignment( assignment ), - SIGN_PHASE_NEGATIVE ); + TS_ASSERT_EQUALS( sign.getPhaseStatusInAssignment( assignment ), SIGN_PHASE_NEGATIVE ); assignment[0] = 15; - TS_ASSERT_EQUALS( sign.getPhaseStatusInAssignment( assignment ), - SIGN_PHASE_POSITIVE ); + TS_ASSERT_EQUALS( sign.getPhaseStatusInAssignment( assignment ), SIGN_PHASE_POSITIVE ); } void test_add_auxiliary_equations() @@ -1248,8 +1242,7 @@ class SignConstraintTestSuite : public CxxTest::TestSuite query.setLowerBound( 6, -1 ); query.setLowerBound( 6, 1 ); - TS_ASSERT_THROWS_NOTHING( sign.addAuxiliaryEquationsAfterPreprocessing - ( query ) ); + TS_ASSERT_THROWS_NOTHING( sign.addAuxiliaryEquationsAfterPreprocessing( query ) ); const List &equations( query.getEquations() ); @@ -1278,7 +1271,7 @@ class SignConstraintTestSuite : public CxxTest::TestSuite TS_ASSERT_EQUALS( eq._scalar, 1 ); - eq = *(++ equations.begin()); + eq = *( ++equations.begin() ); TS_ASSERT_EQUALS( eq._addends.size(), 3U ); diff --git a/src/engine/tests/Test_SmtCore.h b/src/engine/tests/Test_SmtCore.h index f910c9220a..4b44ec212f 100644 --- a/src/engine/tests/Test_SmtCore.h +++ b/src/engine/tests/Test_SmtCore.h @@ -13,8 +13,6 @@ **/ -#include - #include "InputQuery.h" #include "MockEngine.h" #include "MockErrno.h" @@ -23,6 +21,7 @@ #include "ReluConstraint.h" #include "SmtCore.h" +#include #include class MockForSmtCore @@ -55,7 +54,7 @@ class SmtCoreTestSuite : public CxxTest::TestSuite return NULL; } - void restoreState( const PiecewiseLinearConstraint */* state */ ) + void restoreState( const PiecewiseLinearConstraint * /* state */ ) { } @@ -161,7 +160,7 @@ class SmtCoreTestSuite : public CxxTest::TestSuite { } - void getAuxiliaryEquations( List &/* newEquations */ ) const + void getAuxiliaryEquations( List & /* newEquations */ ) const { } @@ -170,9 +169,9 @@ class SmtCoreTestSuite : public CxxTest::TestSuite return ""; } - void initTighteningRow( const unsigned /*counterpart*/ ) - { - } + void initTighteningRow( const unsigned /*counterpart*/ ) + { + } void addTableauAuxVar( unsigned /*tableauAuxVar*/, unsigned /*constraintAuxVar*/ ) { @@ -198,7 +197,9 @@ class SmtCoreTestSuite : public CxxTest::TestSuite SmtCore smtCore( engine ); - for ( unsigned i = 0; i < ( unsigned ) Options::get()->getInt( Options::CONSTRAINT_VIOLATION_THRESHOLD ) - 1; ++i ) + for ( unsigned i = 0; + i < (unsigned)Options::get()->getInt( Options::CONSTRAINT_VIOLATION_THRESHOLD ) - 1; + ++i ) { smtCore.reportViolatedConstraint( &constraint1 ); TS_ASSERT( !smtCore.needToSplit() ); @@ -243,7 +244,9 @@ class SmtCoreTestSuite : public CxxTest::TestSuite constraint.nextSplits.append( split2 ); constraint.nextSplits.append( split3 ); - for ( unsigned i = 0; i < ( unsigned ) Options::get()->getInt( Options::CONSTRAINT_VIOLATION_THRESHOLD ); ++i ) + for ( unsigned i = 0; + i < (unsigned)Options::get()->getInt( Options::CONSTRAINT_VIOLATION_THRESHOLD ); + ++i ) smtCore.reportViolatedConstraint( &constraint ); engine->lastStoredState = NULL; @@ -359,7 +362,9 @@ class SmtCoreTestSuite : public CxxTest::TestSuite constraint.nextSplits.append( split2 ); constraint.nextSplits.append( split3 ); - for ( unsigned i = 0; i < ( unsigned ) Options::get()->getInt( Options::CONSTRAINT_VIOLATION_THRESHOLD ); ++i ) + for ( unsigned i = 0; + i < (unsigned)Options::get()->getInt( Options::CONSTRAINT_VIOLATION_THRESHOLD ); + ++i ) smtCore.reportViolatedConstraint( &constraint ); constraint.nextIsActive = false; @@ -402,7 +407,9 @@ class SmtCoreTestSuite : public CxxTest::TestSuite constraint.nextSplits.append( split1 ); constraint.nextSplits.append( split2 ); - for ( unsigned i = 0; i < ( unsigned ) Options::get()->getInt( Options::CONSTRAINT_VIOLATION_THRESHOLD ); ++i ) + for ( unsigned i = 0; + i < (unsigned)Options::get()->getInt( Options::CONSTRAINT_VIOLATION_THRESHOLD ); + ++i ) smtCore.reportViolatedConstraint( &constraint ); constraint.nextIsActive = true; @@ -435,7 +442,9 @@ class SmtCoreTestSuite : public CxxTest::TestSuite constraint2.nextSplits.append( split4 ); constraint2.nextSplits.append( split5 ); - for ( unsigned i = 0; i < ( unsigned ) Options::get()->getInt( Options::CONSTRAINT_VIOLATION_THRESHOLD ); ++i ) + for ( unsigned i = 0; + i < (unsigned)Options::get()->getInt( Options::CONSTRAINT_VIOLATION_THRESHOLD ); + ++i ) smtCore.reportViolatedConstraint( &constraint2 ); constraint2.nextIsActive = true; @@ -482,7 +491,9 @@ class SmtCoreTestSuite : public CxxTest::TestSuite split1.storeBoundTightening( bound1 ); TS_ASSERT_THROWS_NOTHING( smtCore.recordImpliedValidSplit( split1 ) ); - for ( unsigned i = 0; i < ( unsigned ) Options::get()->getInt( Options::CONSTRAINT_VIOLATION_THRESHOLD ); ++i ) + for ( unsigned i = 0; + i < (unsigned)Options::get()->getInt( Options::CONSTRAINT_VIOLATION_THRESHOLD ); + ++i ) smtCore.reportViolatedConstraint( &relu1 ); TS_ASSERT( smtCore.needToSplit() ); @@ -494,7 +505,9 @@ class SmtCoreTestSuite : public CxxTest::TestSuite split2.storeBoundTightening( bound2 ); TS_ASSERT_THROWS_NOTHING( smtCore.recordImpliedValidSplit( split2 ) ); - for ( unsigned i = 0; i < ( unsigned ) Options::get()->getInt( Options::CONSTRAINT_VIOLATION_THRESHOLD ); ++i ) + for ( unsigned i = 0; + i < (unsigned)Options::get()->getInt( Options::CONSTRAINT_VIOLATION_THRESHOLD ); + ++i ) smtCore.reportViolatedConstraint( &relu2 ); TS_ASSERT( smtCore.needToSplit() ); @@ -510,13 +523,15 @@ class SmtCoreTestSuite : public CxxTest::TestSuite // Examine the first stackEntry SmtStackEntry *stackEntry = *( smtState._stack.begin() ); TS_ASSERT( stackEntry->_activeSplit == *( relu1.getCaseSplits().begin() ) ); - TS_ASSERT( *( stackEntry->_alternativeSplits.begin() ) == *( ++relu1.getCaseSplits().begin() ) ); + TS_ASSERT( *( stackEntry->_alternativeSplits.begin() ) == + *( ++relu1.getCaseSplits().begin() ) ); TS_ASSERT( stackEntry->_impliedValidSplits.size() == 1 ); TS_ASSERT( *( stackEntry->_impliedValidSplits.begin() ) == split2 ); // Examine the second stackEntry stackEntry = *( ++smtState._stack.begin() ); TS_ASSERT( stackEntry->_activeSplit == *( relu2.getCaseSplits().begin() ) ); - TS_ASSERT( *( stackEntry->_alternativeSplits.begin() ) == *( ++relu2.getCaseSplits().begin() ) ); + TS_ASSERT( *( stackEntry->_alternativeSplits.begin() ) == + *( ++relu2.getCaseSplits().begin() ) ); TS_ASSERT( stackEntry->_impliedValidSplits.size() == 0 ); clearSmtState( smtState ); @@ -531,7 +546,8 @@ class SmtCoreTestSuite : public CxxTest::TestSuite // Examine the first stackEntry stackEntry = *( smtState._stack.begin() ); TS_ASSERT( stackEntry->_activeSplit == *( relu1.getCaseSplits().begin() ) ); - TS_ASSERT( *( stackEntry->_alternativeSplits.begin() ) == *( ++relu1.getCaseSplits().begin() ) ); + TS_ASSERT( *( stackEntry->_alternativeSplits.begin() ) == + *( ++relu1.getCaseSplits().begin() ) ); TS_ASSERT( stackEntry->_impliedValidSplits.size() == 1 ); TS_ASSERT( *( stackEntry->_impliedValidSplits.begin() ) == split2 ); // Examine the second stackEntry diff --git a/src/engine/tests/Test_SumOfInfeasibilitiesManager.h b/src/engine/tests/Test_SumOfInfeasibilitiesManager.h index 0385e29e96..e888d13001 100644 --- a/src/engine/tests/Test_SumOfInfeasibilitiesManager.h +++ b/src/engine/tests/Test_SumOfInfeasibilitiesManager.h @@ -13,22 +13,19 @@ **/ -#include - #include "InputQuery.h" #include "LinearExpression.h" #include "MaxConstraint.h" +#include "MockErrno.h" #include "MockTableau.h" #include "Options.h" #include "ReluConstraint.h" #include "SumOfInfeasibilitiesManager.h" - #include "Vector.h" -#include "MockErrno.h" +#include -class MockForSoI : - public T::Base_rand +class MockForSoI : public T::Base_rand { public: MockForSoI() @@ -72,18 +69,18 @@ class SumOfInfeasibilitiesManagerTestSuite : public CxxTest::TestSuite R / 4 -- 5 */ - ipq.setNumberOfVariables(7); - ReluConstraint *relu1 = new ReluConstraint(0,1); - ReluConstraint *relu2 = new ReluConstraint(2,3); - ReluConstraint *relu3 = new ReluConstraint(4,5); - MaxConstraint *max1 = new MaxConstraint(6, {1,3,5}); + ipq.setNumberOfVariables( 7 ); + ReluConstraint *relu1 = new ReluConstraint( 0, 1 ); + ReluConstraint *relu2 = new ReluConstraint( 2, 3 ); + ReluConstraint *relu3 = new ReluConstraint( 4, 5 ); + MaxConstraint *max1 = new MaxConstraint( 6, { 1, 3, 5 } ); max1->transformToUseAuxVariables( ipq ); - ipq.addPiecewiseLinearConstraint(relu1); - ipq.addPiecewiseLinearConstraint(relu2); - ipq.addPiecewiseLinearConstraint(relu3); - ipq.addPiecewiseLinearConstraint(max1); + ipq.addPiecewiseLinearConstraint( relu1 ); + ipq.addPiecewiseLinearConstraint( relu2 ); + ipq.addPiecewiseLinearConstraint( relu3 ); + ipq.addPiecewiseLinearConstraint( max1 ); for ( unsigned i = 0; i <= 6; ++i ) { @@ -99,7 +96,7 @@ class SumOfInfeasibilitiesManagerTestSuite : public CxxTest::TestSuite ipq.markInputVariable( 2, 1 ); ipq.markInputVariable( 4, 2 ); - plConstraints = {relu1, relu2, relu3, max1}; + plConstraints = { relu1, relu2, relu3, max1 }; for ( const auto &c : plConstraints ) { @@ -109,7 +106,6 @@ class SumOfInfeasibilitiesManagerTestSuite : public CxxTest::TestSuite c->notifyLowerBound( var, -3 ); c->notifyUpperBound( var, 3 ); } - } relu1->notifyLowerBound( 1, 0 ); relu2->notifyLowerBound( 3, 0 ); @@ -133,14 +129,11 @@ class SumOfInfeasibilitiesManagerTestSuite : public CxxTest::TestSuite createInputQuery( ipq, plConstraints, tableau ); ipq.getNetworkLevelReasoner()->setTableau( &tableau ); - Options::get()->setString - ( Options::SOI_INITIALIZATION_STRATEGY, "input-assignment" ); + Options::get()->setString( Options::SOI_INITIALIZATION_STRATEGY, "input-assignment" ); std::unique_ptr soiManager; - TS_ASSERT_THROWS_NOTHING - ( soiManager = - std::unique_ptr - ( new SumOfInfeasibilitiesManager( ipq, tableau ) ) ); + TS_ASSERT_THROWS_NOTHING( soiManager = std::unique_ptr( + new SumOfInfeasibilitiesManager( ipq, tableau ) ) ); tableau.setValue( 0, -1 ); tableau.setValue( 1, 0 ); @@ -154,25 +147,23 @@ class SumOfInfeasibilitiesManagerTestSuite : public CxxTest::TestSuite tableau.setValue( 9, 0 ); // The input assignment is [-1, 1, 2], the output of the max should be 2 - TS_ASSERT_THROWS_NOTHING - (soiManager->initializePhasePattern() ); + TS_ASSERT_THROWS_NOTHING( soiManager->initializePhasePattern() ); // So the cost compoenents in the SoI should be: // relu1: inactive, relu2: active, relu3: active, max: third max input LinearExpression cost; - TS_ASSERT_THROWS_NOTHING( plConstraints[0]->getCostFunctionComponent - ( cost, RELU_PHASE_INACTIVE ) ); - TS_ASSERT_THROWS_NOTHING( plConstraints[1]->getCostFunctionComponent - ( cost, RELU_PHASE_ACTIVE ) ); - TS_ASSERT_THROWS_NOTHING( plConstraints[2]->getCostFunctionComponent - ( cost, RELU_PHASE_ACTIVE ) ); + TS_ASSERT_THROWS_NOTHING( + plConstraints[0]->getCostFunctionComponent( cost, RELU_PHASE_INACTIVE ) ); + TS_ASSERT_THROWS_NOTHING( + plConstraints[1]->getCostFunctionComponent( cost, RELU_PHASE_ACTIVE ) ); + TS_ASSERT_THROWS_NOTHING( + plConstraints[2]->getCostFunctionComponent( cost, RELU_PHASE_ACTIVE ) ); List phases = plConstraints[3]->getAllCases(); - TS_ASSERT_THROWS_NOTHING( plConstraints[3]->getCostFunctionComponent - ( cost, *( ++( ++phases.begin() ) ) ) ); + TS_ASSERT_THROWS_NOTHING( + plConstraints[3]->getCostFunctionComponent( cost, *( ++( ++phases.begin() ) ) ) ); TS_ASSERT_EQUALS( cost, soiManager->getCurrentSoIPhasePattern() ); TS_ASSERT_EQUALS( cost, soiManager->getLastAcceptedSoIPhasePattern() ); - TS_ASSERT_EQUALS( soiManager->getConstraintsUpdatedInLastProposal().size(), - 0u ); + TS_ASSERT_EQUALS( soiManager->getConstraintsUpdatedInLastProposal().size(), 0u ); } void test_initialize_phase_pattern_with_input_assignment2() @@ -183,14 +174,11 @@ class SumOfInfeasibilitiesManagerTestSuite : public CxxTest::TestSuite createInputQuery( ipq, plConstraints, tableau ); ipq.getNetworkLevelReasoner()->setTableau( &tableau ); - Options::get()->setString - ( Options::SOI_INITIALIZATION_STRATEGY, "input-assignment" ); + Options::get()->setString( Options::SOI_INITIALIZATION_STRATEGY, "input-assignment" ); std::unique_ptr soiManager; - TS_ASSERT_THROWS_NOTHING - ( soiManager = - std::unique_ptr - ( new SumOfInfeasibilitiesManager( ipq, tableau ) ) ); + TS_ASSERT_THROWS_NOTHING( soiManager = std::unique_ptr( + new SumOfInfeasibilitiesManager( ipq, tableau ) ) ); // Phase is fixed, won't add the second relu to SoI tableau.setValue( 0, 1 ); @@ -213,16 +201,15 @@ class SumOfInfeasibilitiesManagerTestSuite : public CxxTest::TestSuite // should be 2 // So the cost compoenents in the SoI should be: // relu1: active, relu3: inactive, max: PHASE_ELIMINATED - TS_ASSERT_THROWS_NOTHING - (soiManager->initializePhasePattern() ); + TS_ASSERT_THROWS_NOTHING( soiManager->initializePhasePattern() ); LinearExpression cost; - TS_ASSERT_THROWS_NOTHING( plConstraints[0]->getCostFunctionComponent - ( cost, RELU_PHASE_ACTIVE ) ); - TS_ASSERT_THROWS_NOTHING( plConstraints[2]->getCostFunctionComponent - ( cost, RELU_PHASE_INACTIVE ) ); - TS_ASSERT_THROWS_NOTHING( plConstraints[3]->getCostFunctionComponent - ( cost, MAX_PHASE_ELIMINATED ) ); + TS_ASSERT_THROWS_NOTHING( + plConstraints[0]->getCostFunctionComponent( cost, RELU_PHASE_ACTIVE ) ); + TS_ASSERT_THROWS_NOTHING( + plConstraints[2]->getCostFunctionComponent( cost, RELU_PHASE_INACTIVE ) ); + TS_ASSERT_THROWS_NOTHING( + plConstraints[3]->getCostFunctionComponent( cost, MAX_PHASE_ELIMINATED ) ); TS_ASSERT_EQUALS( cost, soiManager->getCurrentSoIPhasePattern() ); } @@ -235,14 +222,11 @@ class SumOfInfeasibilitiesManagerTestSuite : public CxxTest::TestSuite createInputQuery( ipq, plConstraints, tableau ); ipq.getNetworkLevelReasoner()->setTableau( &tableau ); - Options::get()->setString - ( Options::SOI_INITIALIZATION_STRATEGY, "current-assignment" ); + Options::get()->setString( Options::SOI_INITIALIZATION_STRATEGY, "current-assignment" ); std::unique_ptr soiManager; - TS_ASSERT_THROWS_NOTHING - ( soiManager = - std::unique_ptr - ( new SumOfInfeasibilitiesManager( ipq, tableau ) ) ); + TS_ASSERT_THROWS_NOTHING( soiManager = std::unique_ptr( + new SumOfInfeasibilitiesManager( ipq, tableau ) ) ); tableau.nextValues[0] = -1; tableau.nextValues[1] = 0; @@ -256,25 +240,23 @@ class SumOfInfeasibilitiesManagerTestSuite : public CxxTest::TestSuite tableau.nextValues[9] = 0; // The input assignment is [-1, 1, 2], the output of the max should be 2 - TS_ASSERT_THROWS_NOTHING - (soiManager->initializePhasePattern() ); + TS_ASSERT_THROWS_NOTHING( soiManager->initializePhasePattern() ); // So the cost compoenents in the SoI should be: // relu1: inactive, relu2: active, relu3: active, max: third max input LinearExpression cost; - TS_ASSERT_THROWS_NOTHING( plConstraints[0]->getCostFunctionComponent - ( cost, RELU_PHASE_INACTIVE ) ); - TS_ASSERT_THROWS_NOTHING( plConstraints[1]->getCostFunctionComponent - ( cost, RELU_PHASE_ACTIVE ) ); - TS_ASSERT_THROWS_NOTHING( plConstraints[2]->getCostFunctionComponent - ( cost, RELU_PHASE_ACTIVE ) ); + TS_ASSERT_THROWS_NOTHING( + plConstraints[0]->getCostFunctionComponent( cost, RELU_PHASE_INACTIVE ) ); + TS_ASSERT_THROWS_NOTHING( + plConstraints[1]->getCostFunctionComponent( cost, RELU_PHASE_ACTIVE ) ); + TS_ASSERT_THROWS_NOTHING( + plConstraints[2]->getCostFunctionComponent( cost, RELU_PHASE_ACTIVE ) ); List phases = plConstraints[3]->getAllCases(); - TS_ASSERT_THROWS_NOTHING( plConstraints[3]->getCostFunctionComponent - ( cost, *( ++phases.begin() ) ) ); + TS_ASSERT_THROWS_NOTHING( + plConstraints[3]->getCostFunctionComponent( cost, *( ++phases.begin() ) ) ); TS_ASSERT_EQUALS( cost, soiManager->getCurrentSoIPhasePattern() ); TS_ASSERT_EQUALS( cost, soiManager->getLastAcceptedSoIPhasePattern() ); - TS_ASSERT_EQUALS( soiManager->getConstraintsUpdatedInLastProposal().size(), - 0u ); + TS_ASSERT_EQUALS( soiManager->getConstraintsUpdatedInLastProposal().size(), 0u ); } void test_propose_phase_pattern_update_randomly() @@ -295,23 +277,19 @@ class SumOfInfeasibilitiesManagerTestSuite : public CxxTest::TestSuite tableau.nextValues[8] = 0; tableau.nextValues[9] = 0; - Options::get()->setString - ( Options::SOI_INITIALIZATION_STRATEGY, "input-assignment" ); - Options::get()->setString - ( Options::SOI_SEARCH_STRATEGY, "mcmc" ); + Options::get()->setString( Options::SOI_INITIALIZATION_STRATEGY, "input-assignment" ); + Options::get()->setString( Options::SOI_SEARCH_STRATEGY, "mcmc" ); std::unique_ptr soiManager; - TS_ASSERT_THROWS_NOTHING - ( soiManager = - std::unique_ptr - ( new SumOfInfeasibilitiesManager( ipq, tableau ) ) ); + TS_ASSERT_THROWS_NOTHING( soiManager = std::unique_ptr( + new SumOfInfeasibilitiesManager( ipq, tableau ) ) ); TS_ASSERT_THROWS_NOTHING( soiManager->initializePhasePattern() ); for ( const auto &plConstraint : plConstraints ) { - soiManager->setPhaseStatusInLastAcceptedPhasePattern - ( plConstraint, *( plConstraint->getAllCases().begin() ) ); + soiManager->setPhaseStatusInLastAcceptedPhasePattern( + plConstraint, *( plConstraint->getAllCases().begin() ) ); } mock->randWasCalled = 0; @@ -321,23 +299,17 @@ class SumOfInfeasibilitiesManagerTestSuite : public CxxTest::TestSuite // The cost term of the second relu is flipped. LinearExpression cost1; - TS_ASSERT_THROWS_NOTHING( plConstraints[0]->getCostFunctionComponent - ( cost1, *( plConstraints[0]-> - getAllCases().begin() ) ) ); - TS_ASSERT_THROWS_NOTHING( plConstraints[1]->getCostFunctionComponent - ( cost1, *(++( plConstraints[1]-> - getAllCases().begin() ) ) ) ); - TS_ASSERT_THROWS_NOTHING( plConstraints[2]->getCostFunctionComponent - ( cost1, *( plConstraints[2]-> - getAllCases().begin() ) ) ); - TS_ASSERT_THROWS_NOTHING( plConstraints[3]->getCostFunctionComponent - ( cost1, *( plConstraints[3]-> - getAllCases().begin() ) ) ); - - TS_ASSERT_EQUALS( soiManager->getConstraintsUpdatedInLastProposal().size(), - 1u ); - TS_ASSERT_EQUALS( *soiManager-> - getConstraintsUpdatedInLastProposal().begin(), + TS_ASSERT_THROWS_NOTHING( plConstraints[0]->getCostFunctionComponent( + cost1, *( plConstraints[0]->getAllCases().begin() ) ) ); + TS_ASSERT_THROWS_NOTHING( plConstraints[1]->getCostFunctionComponent( + cost1, *( ++( plConstraints[1]->getAllCases().begin() ) ) ) ); + TS_ASSERT_THROWS_NOTHING( plConstraints[2]->getCostFunctionComponent( + cost1, *( plConstraints[2]->getAllCases().begin() ) ) ); + TS_ASSERT_THROWS_NOTHING( plConstraints[3]->getCostFunctionComponent( + cost1, *( plConstraints[3]->getAllCases().begin() ) ) ); + + TS_ASSERT_EQUALS( soiManager->getConstraintsUpdatedInLastProposal().size(), 1u ); + TS_ASSERT_EQUALS( *soiManager->getConstraintsUpdatedInLastProposal().begin(), plConstraints[1] ); TS_ASSERT_EQUALS( cost1, soiManager->getCurrentSoIPhasePattern() ); @@ -352,25 +324,19 @@ class SumOfInfeasibilitiesManagerTestSuite : public CxxTest::TestSuite // statuses and 7 % 2 = 1. LinearExpression cost2; - TS_ASSERT_THROWS_NOTHING( plConstraints[0]->getCostFunctionComponent - ( cost2, *( plConstraints[0]-> - getAllCases().begin() ) ) ); - TS_ASSERT_THROWS_NOTHING( plConstraints[1]->getCostFunctionComponent - ( cost2, *( plConstraints[1]-> - getAllCases().begin() ) ) ); - TS_ASSERT_THROWS_NOTHING( plConstraints[2]->getCostFunctionComponent - ( cost2, *( plConstraints[2]-> - getAllCases().begin() ) ) ); - TS_ASSERT_THROWS_NOTHING( plConstraints[3]->getCostFunctionComponent - ( cost2, *(++(++( plConstraints[3]-> - getAllCases().begin() ) ) ) ) ); + TS_ASSERT_THROWS_NOTHING( plConstraints[0]->getCostFunctionComponent( + cost2, *( plConstraints[0]->getAllCases().begin() ) ) ); + TS_ASSERT_THROWS_NOTHING( plConstraints[1]->getCostFunctionComponent( + cost2, *( plConstraints[1]->getAllCases().begin() ) ) ); + TS_ASSERT_THROWS_NOTHING( plConstraints[2]->getCostFunctionComponent( + cost2, *( plConstraints[2]->getAllCases().begin() ) ) ); + TS_ASSERT_THROWS_NOTHING( plConstraints[3]->getCostFunctionComponent( + cost2, *( ++( ++( plConstraints[3]->getAllCases().begin() ) ) ) ) ); TS_ASSERT_EQUALS( cost2, soiManager->getCurrentSoIPhasePattern() ); - TS_ASSERT_EQUALS( soiManager->getConstraintsUpdatedInLastProposal().size(), - 1u ); - TS_ASSERT_EQUALS( *soiManager-> - getConstraintsUpdatedInLastProposal().begin(), + TS_ASSERT_EQUALS( soiManager->getConstraintsUpdatedInLastProposal().size(), 1u ); + TS_ASSERT_EQUALS( *soiManager->getConstraintsUpdatedInLastProposal().begin(), plConstraints[3] ); TS_ASSERT_THROWS_NOTHING( soiManager->acceptCurrentPhasePattern() ); @@ -378,8 +344,7 @@ class SumOfInfeasibilitiesManagerTestSuite : public CxxTest::TestSuite TS_ASSERT_EQUALS( cost2, soiManager->getLastAcceptedSoIPhasePattern() ); TS_ASSERT_EQUALS( cost2, soiManager->getCurrentSoIPhasePattern() ); - TS_ASSERT_EQUALS( soiManager->getConstraintsUpdatedInLastProposal().size(), - 0u ); + TS_ASSERT_EQUALS( soiManager->getConstraintsUpdatedInLastProposal().size(), 0u ); } void test_propose_phase_pattern_update_walksat() @@ -400,29 +365,22 @@ class SumOfInfeasibilitiesManagerTestSuite : public CxxTest::TestSuite tableau.nextValues[8] = 0.5; tableau.nextValues[9] = 0.5; - Options::get()->setString - ( Options::SOI_INITIALIZATION_STRATEGY, "input-assignment" ); - Options::get()->setString - ( Options::SOI_SEARCH_STRATEGY, "walksat" ); + Options::get()->setString( Options::SOI_INITIALIZATION_STRATEGY, "input-assignment" ); + Options::get()->setString( Options::SOI_SEARCH_STRATEGY, "walksat" ); std::unique_ptr soiManager; - TS_ASSERT_THROWS_NOTHING - ( soiManager = - std::unique_ptr - ( new SumOfInfeasibilitiesManager( ipq, tableau ) ) ); + TS_ASSERT_THROWS_NOTHING( soiManager = std::unique_ptr( + new SumOfInfeasibilitiesManager( ipq, tableau ) ) ); TS_ASSERT_THROWS_NOTHING( soiManager->initializePhasePattern() ); TS_ASSERT_THROWS_NOTHING( soiManager->obtainCurrentAssignment() ); - soiManager->setPhaseStatusInLastAcceptedPhasePattern - ( plConstraints[0], RELU_PHASE_ACTIVE ); - soiManager->setPhaseStatusInLastAcceptedPhasePattern - ( plConstraints[1], RELU_PHASE_INACTIVE ); - soiManager->setPhaseStatusInLastAcceptedPhasePattern - ( plConstraints[2], RELU_PHASE_ACTIVE ); - soiManager->setPhaseStatusInLastAcceptedPhasePattern - ( plConstraints[3], *( plConstraints[3]-> - getAllCases().begin() ) ); + soiManager->setPhaseStatusInLastAcceptedPhasePattern( plConstraints[0], RELU_PHASE_ACTIVE ); + soiManager->setPhaseStatusInLastAcceptedPhasePattern( plConstraints[1], + RELU_PHASE_INACTIVE ); + soiManager->setPhaseStatusInLastAcceptedPhasePattern( plConstraints[2], RELU_PHASE_ACTIVE ); + soiManager->setPhaseStatusInLastAcceptedPhasePattern( + plConstraints[3], *( plConstraints[3]->getAllCases().begin() ) ); // Reduced cost for relu1: 2, for relu2: 1, for relu3: -2, // for max: 1.5. So pick relu1. @@ -430,22 +388,19 @@ class SumOfInfeasibilitiesManagerTestSuite : public CxxTest::TestSuite // The cost term of the second relu is flipped. LinearExpression cost1; - TS_ASSERT_THROWS_NOTHING( plConstraints[0]->getCostFunctionComponent - ( cost1, RELU_PHASE_INACTIVE ) ); - TS_ASSERT_THROWS_NOTHING( plConstraints[1]->getCostFunctionComponent - ( cost1, RELU_PHASE_INACTIVE ) ); - TS_ASSERT_THROWS_NOTHING( plConstraints[2]->getCostFunctionComponent - ( cost1, RELU_PHASE_ACTIVE ) ); - TS_ASSERT_THROWS_NOTHING( plConstraints[3]->getCostFunctionComponent - ( cost1, *( plConstraints[3]-> - getAllCases().begin() ) ) ); + TS_ASSERT_THROWS_NOTHING( + plConstraints[0]->getCostFunctionComponent( cost1, RELU_PHASE_INACTIVE ) ); + TS_ASSERT_THROWS_NOTHING( + plConstraints[1]->getCostFunctionComponent( cost1, RELU_PHASE_INACTIVE ) ); + TS_ASSERT_THROWS_NOTHING( + plConstraints[2]->getCostFunctionComponent( cost1, RELU_PHASE_ACTIVE ) ); + TS_ASSERT_THROWS_NOTHING( plConstraints[3]->getCostFunctionComponent( + cost1, *( plConstraints[3]->getAllCases().begin() ) ) ); TS_ASSERT_EQUALS( cost1, soiManager->getCurrentSoIPhasePattern() ); - TS_ASSERT_EQUALS( soiManager->getConstraintsUpdatedInLastProposal().size(), - 1u ); - TS_ASSERT_EQUALS( *soiManager-> - getConstraintsUpdatedInLastProposal().begin(), + TS_ASSERT_EQUALS( soiManager->getConstraintsUpdatedInLastProposal().size(), 1u ); + TS_ASSERT_EQUALS( *soiManager->getConstraintsUpdatedInLastProposal().begin(), plConstraints[0] ); @@ -457,22 +412,19 @@ class SumOfInfeasibilitiesManagerTestSuite : public CxxTest::TestSuite // The cost term of the second relu is flipped. LinearExpression cost2; - TS_ASSERT_THROWS_NOTHING( plConstraints[0]->getCostFunctionComponent - ( cost2, RELU_PHASE_ACTIVE ) ); - TS_ASSERT_THROWS_NOTHING( plConstraints[1]->getCostFunctionComponent - ( cost2, RELU_PHASE_INACTIVE ) ); - TS_ASSERT_THROWS_NOTHING( plConstraints[2]->getCostFunctionComponent - ( cost2, RELU_PHASE_ACTIVE ) ); - TS_ASSERT_THROWS_NOTHING( plConstraints[3]->getCostFunctionComponent - ( cost2, *( ++plConstraints[3]-> - getAllCases().begin() ) ) ); + TS_ASSERT_THROWS_NOTHING( + plConstraints[0]->getCostFunctionComponent( cost2, RELU_PHASE_ACTIVE ) ); + TS_ASSERT_THROWS_NOTHING( + plConstraints[1]->getCostFunctionComponent( cost2, RELU_PHASE_INACTIVE ) ); + TS_ASSERT_THROWS_NOTHING( + plConstraints[2]->getCostFunctionComponent( cost2, RELU_PHASE_ACTIVE ) ); + TS_ASSERT_THROWS_NOTHING( plConstraints[3]->getCostFunctionComponent( + cost2, *( ++plConstraints[3]->getAllCases().begin() ) ) ); TS_ASSERT_EQUALS( cost2, soiManager->getCurrentSoIPhasePattern() ); - TS_ASSERT_EQUALS( soiManager->getConstraintsUpdatedInLastProposal().size(), - 1u ); - TS_ASSERT_EQUALS( *soiManager-> - getConstraintsUpdatedInLastProposal().begin(), + TS_ASSERT_EQUALS( soiManager->getConstraintsUpdatedInLastProposal().size(), 1u ); + TS_ASSERT_EQUALS( *soiManager->getConstraintsUpdatedInLastProposal().begin(), plConstraints[3] ); } @@ -482,47 +434,40 @@ class SumOfInfeasibilitiesManagerTestSuite : public CxxTest::TestSuite MockTableau tableau; // Set beta to 5. - Options::get()->setFloat - ( Options::PROBABILITY_DENSITY_PARAMETER, 5 ); + Options::get()->setFloat( Options::PROBABILITY_DENSITY_PARAMETER, 5 ); std::unique_ptr soiManager; - TS_ASSERT_THROWS_NOTHING - ( soiManager = - std::unique_ptr - ( new SumOfInfeasibilitiesManager( ipq, tableau ) ) ); + TS_ASSERT_THROWS_NOTHING( soiManager = std::unique_ptr( + new SumOfInfeasibilitiesManager( ipq, tableau ) ) ); mock->randWasCalled = 0; // Only accept if the probability to accept is larger than 80%. - mock->nextRandValue = (int) RAND_MAX * 0.8; + mock->nextRandValue = (int)RAND_MAX * 0.8; double costOfLastAcceptedPhasePattern = 10; double costOfProposedPhasePattern = 9; - TS_ASSERT( soiManager->decideToAcceptCurrentProposal - ( costOfLastAcceptedPhasePattern, - costOfProposedPhasePattern ) ); + TS_ASSERT( soiManager->decideToAcceptCurrentProposal( costOfLastAcceptedPhasePattern, + costOfProposedPhasePattern ) ); // Always accept if the new cost is lower. TS_ASSERT_EQUALS( mock->randWasCalled, 0u ); costOfProposedPhasePattern = 10.1; // Prob. to accept is e^( -beta * (10.5 - 10)) ~= 60%, thus rejected. - TS_ASSERT( !soiManager->decideToAcceptCurrentProposal - ( costOfLastAcceptedPhasePattern, - costOfProposedPhasePattern ) ); + TS_ASSERT( !soiManager->decideToAcceptCurrentProposal( costOfLastAcceptedPhasePattern, + costOfProposedPhasePattern ) ); TS_ASSERT_EQUALS( mock->randWasCalled, 1u ); // Only accept if the probability to accept is larger than 40%. - mock->nextRandValue = (int) RAND_MAX * 0.4; + mock->nextRandValue = (int)RAND_MAX * 0.4; // Prob. to accept is still ~60%, thus accepted. - TS_ASSERT( soiManager->decideToAcceptCurrentProposal - ( costOfLastAcceptedPhasePattern, - costOfProposedPhasePattern ) ); + TS_ASSERT( soiManager->decideToAcceptCurrentProposal( costOfLastAcceptedPhasePattern, + costOfProposedPhasePattern ) ); TS_ASSERT_EQUALS( mock->randWasCalled, 2u ); costOfProposedPhasePattern = 10.5; // Accept with prob. e^( -beta * (10.5 - 10)) ~= 8.2%, thus rejected. - TS_ASSERT( !soiManager->decideToAcceptCurrentProposal - ( costOfLastAcceptedPhasePattern, - costOfProposedPhasePattern ) ); + TS_ASSERT( !soiManager->decideToAcceptCurrentProposal( costOfLastAcceptedPhasePattern, + costOfProposedPhasePattern ) ); TS_ASSERT_EQUALS( mock->randWasCalled, 3u ); } @@ -534,14 +479,11 @@ class SumOfInfeasibilitiesManagerTestSuite : public CxxTest::TestSuite createInputQuery( ipq, plConstraints, tableau ); ipq.getNetworkLevelReasoner()->setTableau( &tableau ); - Options::get()->setString - ( Options::SOI_INITIALIZATION_STRATEGY, "input-assignment" ); + Options::get()->setString( Options::SOI_INITIALIZATION_STRATEGY, "input-assignment" ); std::unique_ptr soiManager; - TS_ASSERT_THROWS_NOTHING - ( soiManager = - std::unique_ptr - ( new SumOfInfeasibilitiesManager( ipq, tableau ) ) ); + TS_ASSERT_THROWS_NOTHING( soiManager = std::unique_ptr( + new SumOfInfeasibilitiesManager( ipq, tableau ) ) ); // relu1, relu2 satisfied, relu3 not satisfied, max not satisfied. tableau.nextValues[0] = -1; @@ -556,29 +498,26 @@ class SumOfInfeasibilitiesManagerTestSuite : public CxxTest::TestSuite tableau.nextValues[9] = 1; - TS_ASSERT_THROWS_NOTHING - (soiManager->initializePhasePattern() ); + TS_ASSERT_THROWS_NOTHING( soiManager->initializePhasePattern() ); for ( const auto &plConstraint : plConstraints ) { - soiManager->setPhaseStatusInCurrentPhasePattern - ( plConstraint, *( plConstraint->getAllCases().begin() ) ); + soiManager->setPhaseStatusInCurrentPhasePattern( + plConstraint, *( plConstraint->getAllCases().begin() ) ); } - TS_ASSERT_THROWS_NOTHING - (soiManager->updateCurrentPhasePatternForSatisfiedPLConstraints() ); + TS_ASSERT_THROWS_NOTHING( + soiManager->updateCurrentPhasePatternForSatisfiedPLConstraints() ); LinearExpression cost; - TS_ASSERT_THROWS_NOTHING( plConstraints[0]->getCostFunctionComponent - ( cost, RELU_PHASE_INACTIVE ) ); - TS_ASSERT_THROWS_NOTHING( plConstraints[1]->getCostFunctionComponent - ( cost, RELU_PHASE_ACTIVE ) ); - TS_ASSERT_THROWS_NOTHING( plConstraints[2]->getCostFunctionComponent - ( cost, *( plConstraints[2]-> - getAllCases().begin() ) ) ); - TS_ASSERT_THROWS_NOTHING( plConstraints[3]->getCostFunctionComponent - ( cost, *( plConstraints[3]-> - getAllCases().begin() ) ) ); + TS_ASSERT_THROWS_NOTHING( + plConstraints[0]->getCostFunctionComponent( cost, RELU_PHASE_INACTIVE ) ); + TS_ASSERT_THROWS_NOTHING( + plConstraints[1]->getCostFunctionComponent( cost, RELU_PHASE_ACTIVE ) ); + TS_ASSERT_THROWS_NOTHING( plConstraints[2]->getCostFunctionComponent( + cost, *( plConstraints[2]->getAllCases().begin() ) ) ); + TS_ASSERT_THROWS_NOTHING( plConstraints[3]->getCostFunctionComponent( + cost, *( plConstraints[3]->getAllCases().begin() ) ) ); TS_ASSERT_EQUALS( cost, soiManager->getCurrentSoIPhasePattern() ); } @@ -591,14 +530,11 @@ class SumOfInfeasibilitiesManagerTestSuite : public CxxTest::TestSuite createInputQuery( ipq, plConstraints, tableau ); ipq.getNetworkLevelReasoner()->setTableau( &tableau ); - Options::get()->setString - ( Options::SOI_INITIALIZATION_STRATEGY, "input-assignment" ); + Options::get()->setString( Options::SOI_INITIALIZATION_STRATEGY, "input-assignment" ); std::unique_ptr soiManager; - TS_ASSERT_THROWS_NOTHING - ( soiManager = - std::unique_ptr - ( new SumOfInfeasibilitiesManager( ipq, tableau ) ) ); + TS_ASSERT_THROWS_NOTHING( soiManager = std::unique_ptr( + new SumOfInfeasibilitiesManager( ipq, tableau ) ) ); // relu1, relu2 satisfied, relu3 not satisfied, max not satisfied. tableau.setValue( 0, -1 ); @@ -612,43 +548,39 @@ class SumOfInfeasibilitiesManagerTestSuite : public CxxTest::TestSuite tableau.setValue( 8, 1.5 ); tableau.setValue( 9, 1 ); - TS_ASSERT_THROWS_NOTHING - (soiManager->initializePhasePattern() ); + TS_ASSERT_THROWS_NOTHING( soiManager->initializePhasePattern() ); for ( const auto &plConstraint : plConstraints ) { - soiManager->setPhaseStatusInCurrentPhasePattern - ( plConstraint, *( plConstraint->getAllCases().begin() ) ); + soiManager->setPhaseStatusInCurrentPhasePattern( + plConstraint, *( plConstraint->getAllCases().begin() ) ); } - TS_ASSERT_THROWS_NOTHING( soiManager->removeCostComponentFromHeuristicCost - ( plConstraints[0] ) ); - TS_ASSERT_THROWS_NOTHING( soiManager->removeCostComponentFromHeuristicCost - ( plConstraints[3] ) ); + TS_ASSERT_THROWS_NOTHING( + soiManager->removeCostComponentFromHeuristicCost( plConstraints[0] ) ); + TS_ASSERT_THROWS_NOTHING( + soiManager->removeCostComponentFromHeuristicCost( plConstraints[3] ) ); LinearExpression cost; - TS_ASSERT_THROWS_NOTHING( plConstraints[1]->getCostFunctionComponent - ( cost, *( plConstraints[1]-> - getAllCases().begin() ) ) ); - TS_ASSERT_THROWS_NOTHING( plConstraints[2]->getCostFunctionComponent - ( cost, *( plConstraints[2]-> - getAllCases().begin() ) ) ); + TS_ASSERT_THROWS_NOTHING( plConstraints[1]->getCostFunctionComponent( + cost, *( plConstraints[1]->getAllCases().begin() ) ) ); + TS_ASSERT_THROWS_NOTHING( plConstraints[2]->getCostFunctionComponent( + cost, *( plConstraints[2]->getAllCases().begin() ) ) ); TS_ASSERT_EQUALS( cost, soiManager->getCurrentSoIPhasePattern() ); // Reinitialize. - TS_ASSERT_THROWS_NOTHING - (soiManager->initializePhasePattern() ); - for ( const auto &plConstraint : plConstraints ) + TS_ASSERT_THROWS_NOTHING( soiManager->initializePhasePattern() ); + for ( const auto &plConstraint : plConstraints ) { - soiManager->setPhaseStatusInCurrentPhasePattern - ( plConstraint, *( plConstraint->getAllCases().begin() ) ); + soiManager->setPhaseStatusInCurrentPhasePattern( + plConstraint, *( plConstraint->getAllCases().begin() ) ); } - TS_ASSERT_THROWS_NOTHING( soiManager->removeCostComponentFromHeuristicCost - ( plConstraints[0] ) ); - TS_ASSERT_THROWS_NOTHING( soiManager->removeCostComponentFromHeuristicCost - ( plConstraints[3] ) ); + TS_ASSERT_THROWS_NOTHING( + soiManager->removeCostComponentFromHeuristicCost( plConstraints[0] ) ); + TS_ASSERT_THROWS_NOTHING( + soiManager->removeCostComponentFromHeuristicCost( plConstraints[3] ) ); TS_ASSERT_EQUALS( cost, soiManager->getCurrentSoIPhasePattern() ); } diff --git a/src/engine/tests/Test_Tableau.h b/src/engine/tests/Test_Tableau.h index 6f535e1514..fd9f928dbe 100644 --- a/src/engine/tests/Test_Tableau.h +++ b/src/engine/tests/Test_Tableau.h @@ -14,19 +14,18 @@ ** [[ Add lengthier description here ]] **/ -#include - #include "BoundManager.h" -#include "context/context.h" #include "Equation.h" +#include "MarabouError.h" #include "MockCostFunctionManager.h" #include "MockErrno.h" -#include "MarabouError.h" #include "Options.h" #include "Tableau.h" #include "TableauRow.h" #include "TableauState.h" +#include "context/context.h" +#include #include using namespace CVC4::context; @@ -93,9 +92,7 @@ class TableauTestSuite : public CxxTest::TestSuite */ double A[] = { - 3, 2, 1, 2, 1, 0, 0, - 1, 1, 1, 1, 0, 1, 0, - 4, 3, 3, 4, 0, 0, 1, + 3, 2, 1, 2, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 4, 3, 3, 4, 0, 0, 1, }; tableau.setConstraintMatrix( A ); @@ -328,7 +325,7 @@ class TableauTestSuite : public CxxTest::TestSuite costFunctionManager.nextCostFunction[3] = -1; costFunctionManager.nextBasicCost[0] = -1; - costFunctionManager.nextBasicCost[1] = 0; + costFunctionManager.nextBasicCost[1] = 0; costFunctionManager.nextBasicCost[2] = +1; tableau->setEnteringVariableIndex( 2u ); @@ -436,7 +433,7 @@ class TableauTestSuite : public CxxTest::TestSuite costFunctionManager.nextCostFunction[3] = -1; costFunctionManager.nextBasicCost[0] = -1; - costFunctionManager.nextBasicCost[1] = 0; + costFunctionManager.nextBasicCost[1] = 0; costFunctionManager.nextBasicCost[2] = +1; tableau->setEnteringVariableIndex( 2u ); @@ -500,7 +497,7 @@ class TableauTestSuite : public CxxTest::TestSuite costFunctionManager.nextCostFunction[3] = -1; costFunctionManager.nextBasicCost[0] = -1; - costFunctionManager.nextBasicCost[1] = 0; + costFunctionManager.nextBasicCost[1] = 0; costFunctionManager.nextBasicCost[2] = +1; tableau->setEnteringVariableIndex( 2u ); @@ -574,9 +571,9 @@ class TableauTestSuite : public CxxTest::TestSuite TableauRow row( 4 ); - // x5 = 225 - 3x1 - 2x2 - x3 - 2x4 - // x6 = 117 - x1 - x2 - x3 - x4 - // x7 = 420 - 4x1 - 3x2 - 3x3 - 4x4 + // x5 = 225 - 3x1 - 2x2 - x3 - 2x4 + // x6 = 117 - x1 - x2 - x3 - x4 + // x7 = 420 - 4x1 - 3x2 - 3x3 - 4x4 TS_ASSERT_THROWS_NOTHING( tableau->getTableauRow( 0, &row ) ); @@ -647,7 +644,7 @@ class TableauTestSuite : public CxxTest::TestSuite costFunctionManager.nextCostFunction[3] = -1; costFunctionManager.nextBasicCost[0] = -1; - costFunctionManager.nextBasicCost[1] = 0; + costFunctionManager.nextBasicCost[1] = 0; costFunctionManager.nextBasicCost[2] = +1; tableau->setEnteringVariableIndex( 2u ); @@ -658,7 +655,8 @@ class TableauTestSuite : public CxxTest::TestSuite const double expectedChangeColumn[] = { 1.0, 1.0, 3.0 }; for ( unsigned i = 0; i < 3; ++i ) - TS_ASSERT( FloatUtils::areEqual( tableau->getChangeColumn()[i], expectedChangeColumn[i] ) ); + TS_ASSERT( + FloatUtils::areEqual( tableau->getChangeColumn()[i], expectedChangeColumn[i] ) ); TS_ASSERT_THROWS_NOTHING( tableau->pickLeavingVariable() ); TS_ASSERT_EQUALS( tableau->getEnteringVariable(), 2u ); @@ -680,15 +678,15 @@ class TableauTestSuite : public CxxTest::TestSuite // Old equations are: - // x5 = 225 - 3x1 - 2x2 - x3 - 2x4 - // x6 = 117 - x1 - x2 - x3 - x4 - // x7 = 420 - 4x1 - 3x2 - 3x3 - 4x4 + // x5 = 225 - 3x1 - 2x2 - x3 - 2x4 + // x6 = 117 - x1 - x2 - x3 - x4 + // x7 = 420 - 4x1 - 3x2 - 3x3 - 4x4 // New equations are: - // x5 = 108 - 2x1 - x2 + x6 - x4 - // x3 = 117 - x1 - x2 - x6 - x4 - // x7 = 69 - x1 + 3x6 - x4 + // x5 = 108 - 2x1 - x2 + x6 - x4 + // x3 = 117 - x1 - x2 - x6 - x4 + // x7 = 69 - x1 + 3x6 - x4 TS_ASSERT_THROWS_NOTHING( tableau->getTableauRow( 0, &row ) ); @@ -887,15 +885,15 @@ class TableauTestSuite : public CxxTest::TestSuite // Old equations are: - // x5 = 225 - 3x1 - 2x2 - x3 - 2x4 - // x6 = 117 - x1 - x2 - x3 - x4 - // x7 = 420 - 4x1 - 3x2 - 3x3 - 4x4 + // x5 = 225 - 3x1 - 2x2 - x3 - 2x4 + // x6 = 117 - x1 - x2 - x3 - x4 + // x7 = 420 - 4x1 - 3x2 - 3x3 - 4x4 // New equations are: - // x5 = 108 - 2x1 - x2 + x6 - x4 - // x3 = 117 - x1 - x2 - x6 - x4 - // x7 = 69 - x1 + 3x6 - x4 + // x5 = 108 - 2x1 - x2 + x6 - x4 + // x3 = 117 - x1 - x2 - x6 - x4 + // x7 = 69 - x1 + 3x6 - x4 // Check equations after the pivot TS_ASSERT_THROWS_NOTHING( tableau->getTableauRow( 0, &row ) ); @@ -996,7 +994,7 @@ class TableauTestSuite : public CxxTest::TestSuite costFunctionManager.nextCostFunction[3] = -1; costFunctionManager.nextBasicCost[0] = -1; - costFunctionManager.nextBasicCost[1] = 0; + costFunctionManager.nextBasicCost[1] = 0; costFunctionManager.nextBasicCost[2] = +1; TS_ASSERT( hasCandidates( *tableau ) ); @@ -1026,9 +1024,8 @@ class TableauTestSuite : public CxxTest::TestSuite TableauState *tableauState = NULL; TS_ASSERT( tableauState = new TableauState ); - TS_ASSERT_THROWS_NOTHING( tableau->storeState - ( *tableauState, - TableauStateStorageLevel::STORE_ENTIRE_TABLEAU_STATE ) ); + TS_ASSERT_THROWS_NOTHING( tableau->storeState( + *tableauState, TableauStateStorageLevel::STORE_ENTIRE_TABLEAU_STATE ) ); // Do some more stuff TS_ASSERT_THROWS_NOTHING( tableau->computeCostFunction() ); @@ -1057,9 +1054,8 @@ class TableauTestSuite : public CxxTest::TestSuite TS_ASSERT( !tableau->isBasic( 5u ) ); // Now restore the tableau - TS_ASSERT_THROWS_NOTHING( tableau->restoreState - ( *tableauState, - TableauStateStorageLevel::STORE_ENTIRE_TABLEAU_STATE ) ); + TS_ASSERT_THROWS_NOTHING( tableau->restoreState( + *tableauState, TableauStateStorageLevel::STORE_ENTIRE_TABLEAU_STATE ) ); // Do some more stuff again TS_ASSERT_THROWS_NOTHING( tableau->computeCostFunction() ); @@ -1133,7 +1129,7 @@ class TableauTestSuite : public CxxTest::TestSuite costFunctionManager.nextCostFunction[3] = -1; costFunctionManager.nextBasicCost[0] = -1; - costFunctionManager.nextBasicCost[1] = 0; + costFunctionManager.nextBasicCost[1] = 0; costFunctionManager.nextBasicCost[2] = +1; TS_ASSERT_THROWS_NOTHING( tableau->computeChangeColumn() ); @@ -1405,11 +1401,11 @@ class TableauTestSuite : public CxxTest::TestSuite TS_ASSERT( tableau->areLinearlyDependent( 0, 4, coefficient, inverseCoefficient ) ); TS_ASSERT( FloatUtils::areEqual( coefficient, -3 ) ); - TS_ASSERT( FloatUtils::areEqual( inverseCoefficient, -1.0/3 ) ); + TS_ASSERT( FloatUtils::areEqual( inverseCoefficient, -1.0 / 3 ) ); TS_ASSERT( tableau->areLinearlyDependent( 1, 4, coefficient, inverseCoefficient ) ); TS_ASSERT( FloatUtils::areEqual( coefficient, -2 ) ); - TS_ASSERT( FloatUtils::areEqual( inverseCoefficient, -1.0/2 ) ); + TS_ASSERT( FloatUtils::areEqual( inverseCoefficient, -1.0 / 2 ) ); TS_ASSERT( tableau->areLinearlyDependent( 2, 4, coefficient, inverseCoefficient ) ); TS_ASSERT( FloatUtils::areEqual( coefficient, -1 ) ); @@ -1417,7 +1413,7 @@ class TableauTestSuite : public CxxTest::TestSuite TS_ASSERT( tableau->areLinearlyDependent( 3, 4, coefficient, inverseCoefficient ) ); TS_ASSERT( FloatUtils::areEqual( coefficient, -2 ) ); - TS_ASSERT( FloatUtils::areEqual( inverseCoefficient, -1.0/2 ) ); + TS_ASSERT( FloatUtils::areEqual( inverseCoefficient, -1.0 / 2 ) ); TS_ASSERT( tableau->areLinearlyDependent( 0, 5, coefficient, inverseCoefficient ) ); TS_ASSERT( FloatUtils::areEqual( coefficient, -1 ) ); @@ -1437,19 +1433,19 @@ class TableauTestSuite : public CxxTest::TestSuite TS_ASSERT( tableau->areLinearlyDependent( 0, 6, coefficient, inverseCoefficient ) ); TS_ASSERT( FloatUtils::areEqual( coefficient, -4 ) ); - TS_ASSERT( FloatUtils::areEqual( inverseCoefficient, -1.0/4 ) ); + TS_ASSERT( FloatUtils::areEqual( inverseCoefficient, -1.0 / 4 ) ); TS_ASSERT( tableau->areLinearlyDependent( 1, 6, coefficient, inverseCoefficient ) ); TS_ASSERT( FloatUtils::areEqual( coefficient, -3 ) ); - TS_ASSERT( FloatUtils::areEqual( inverseCoefficient, -1.0/3 ) ); + TS_ASSERT( FloatUtils::areEqual( inverseCoefficient, -1.0 / 3 ) ); TS_ASSERT( tableau->areLinearlyDependent( 2, 6, coefficient, inverseCoefficient ) ); TS_ASSERT( FloatUtils::areEqual( coefficient, -3 ) ); - TS_ASSERT( FloatUtils::areEqual( inverseCoefficient, -1.0/3 ) ); + TS_ASSERT( FloatUtils::areEqual( inverseCoefficient, -1.0 / 3 ) ); TS_ASSERT( tableau->areLinearlyDependent( 3, 6, coefficient, inverseCoefficient ) ); TS_ASSERT( FloatUtils::areEqual( coefficient, -4 ) ); - TS_ASSERT( FloatUtils::areEqual( inverseCoefficient, -1.0/4 ) ); + TS_ASSERT( FloatUtils::areEqual( inverseCoefficient, -1.0 / 4 ) ); // Now perform a pivot, and see that things still make sense afterwards diff --git a/src/input_parsers/AcasNeuralNetwork.cpp b/src/input_parsers/AcasNeuralNetwork.cpp index f0e28e474a..a2b1530f63 100644 --- a/src/input_parsers/AcasNeuralNetwork.cpp +++ b/src/input_parsers/AcasNeuralNetwork.cpp @@ -14,6 +14,7 @@ **/ #include "AcasNeuralNetwork.h" + #include "AcasNnet.h" #include "FloatUtils.h" #include "Vector.h" @@ -69,14 +70,16 @@ unsigned AcasNeuralNetwork::getLayerSize( unsigned layer ) const return (unsigned)_network->layerSizes[layer]; } -void AcasNeuralNetwork::evaluate( const Vector &inputs, Vector &outputs, unsigned outputSize ) const +void AcasNeuralNetwork::evaluate( const Vector &inputs, + Vector &outputs, + unsigned outputSize ) const { Vector inputVector( inputs.size(), 0.0 ); Vector outputVector( outputSize, 0.0 ); double *input( inputVector.data() ); double *output( outputVector.data() ); - for ( unsigned i = 0; i < inputs.size(); ++i ) + for ( unsigned i = 0; i < inputs.size(); ++i ) input[i] = inputs.get( i ); bool normalizeInput = false; @@ -96,13 +99,9 @@ void AcasNeuralNetwork::evaluate( const Vector &inputs, Vector & void AcasNeuralNetwork::getInputRange( unsigned index, double &min, double &max ) { - max = - ( _network->maxes[index] - _network->means[index] ) - / ( _network->ranges[index] ); + max = ( _network->maxes[index] - _network->means[index] ) / ( _network->ranges[index] ); - min = - ( _network->mins[index] - _network->means[index] ) - / ( _network->ranges[index] ); + min = ( _network->mins[index] - _network->means[index] ) / ( _network->ranges[index] ); } // diff --git a/src/input_parsers/AcasNeuralNetwork.h b/src/input_parsers/AcasNeuralNetwork.h index fb615f1f40..14fdf837fb 100644 --- a/src/input_parsers/AcasNeuralNetwork.h +++ b/src/input_parsers/AcasNeuralNetwork.h @@ -19,6 +19,7 @@ #include "AcasNnet.h" #include "MString.h" #include "Vector.h" + #include #include #include @@ -57,7 +58,8 @@ class AcasNeuralNetwork /* Evaluate the network for a given vector of inputs. */ - void evaluate( const Vector &inputs, Vector &outputs, unsigned outputSize ) const; + void + evaluate( const Vector &inputs, Vector &outputs, unsigned outputSize ) const; /* Returns the input range [min, max] for the input node specified by index. diff --git a/src/input_parsers/AcasNnet.cpp b/src/input_parsers/AcasNnet.cpp index 91f20461c8..439170ae25 100644 --- a/src/input_parsers/AcasNnet.cpp +++ b/src/input_parsers/AcasNnet.cpp @@ -14,131 +14,132 @@ **/ #include "AcasNnet.h" + #include "InputParserError.h" #include #include #include -//Take in a .nnet filename with path and load the network from the file -//Inputs: filename - const char* that specifies the name and path of file -//Outputs: void * - points to the loaded neural network -AcasNnet *load_network(const char* filename) +// Take in a .nnet filename with path and load the network from the file +// Inputs: filename - const char* that specifies the name and path of file +// Outputs: void * - points to the loaded neural network +AcasNnet *load_network( const char *filename ) { - //Load file and check if it exists - FILE *fstream = fopen(filename,"r"); + // Load file and check if it exists + FILE *fstream = fopen( filename, "r" ); - if (fstream == NULL) + if ( fstream == NULL ) { throw InputParserError( InputParserError::FILE_DOESNT_EXIST ); } - //Initialize variables + // Initialize variables int bufferSize = 40960; char *buffer = new char[bufferSize]; char *record, *line; - int i=0, layer=0, row=0, j=0, param=0; + int i = 0, layer = 0, row = 0, j = 0, param = 0; AcasNnet *nnet = new AcasNnet(); - //Read int parameters of neural network - line=fgets(buffer,bufferSize,fstream); - while (strstr(line, "//")!=NULL) - line=fgets(buffer,bufferSize,fstream); //skip header lines - record = strtok(line,",\n"); - nnet->numLayers = atoi(record); - nnet->inputSize = atoi(strtok(NULL,",\n")); - nnet->outputSize = atoi(strtok(NULL,",\n")); - nnet->maxLayerSize = atoi(strtok(NULL,",\n")); - - //Allocate space for and read values of the array members of the network - nnet->layerSizes = new int[(((nnet->numLayers)+1))]; - line = fgets(buffer,bufferSize,fstream); - record = strtok(line,",\n"); - for (i = 0; i<((nnet->numLayers)+1); i++) + // Read int parameters of neural network + line = fgets( buffer, bufferSize, fstream ); + while ( strstr( line, "//" ) != NULL ) + line = fgets( buffer, bufferSize, fstream ); // skip header lines + record = strtok( line, ",\n" ); + nnet->numLayers = atoi( record ); + nnet->inputSize = atoi( strtok( NULL, ",\n" ) ); + nnet->outputSize = atoi( strtok( NULL, ",\n" ) ); + nnet->maxLayerSize = atoi( strtok( NULL, ",\n" ) ); + + // Allocate space for and read values of the array members of the network + nnet->layerSizes = new int[( ( ( nnet->numLayers ) + 1 ) )]; + line = fgets( buffer, bufferSize, fstream ); + record = strtok( line, ",\n" ); + for ( i = 0; i < ( ( nnet->numLayers ) + 1 ); i++ ) { - nnet->layerSizes[i] = atoi(record); - record = strtok(NULL,",\n"); + nnet->layerSizes[i] = atoi( record ); + record = strtok( NULL, ",\n" ); } - //Load the symmetric paramter - line = fgets(buffer,bufferSize,fstream); - record = strtok(line,",\n"); - nnet->symmetric = atoi(record); + // Load the symmetric paramter + line = fgets( buffer, bufferSize, fstream ); + record = strtok( line, ",\n" ); + nnet->symmetric = atoi( record ); - //Load Min and Max values of inputs - nnet->mins = new double[(nnet->inputSize)]; - line = fgets(buffer,bufferSize,fstream); - record = strtok(line,",\n"); - for (i = 0; i<(nnet->inputSize); i++) + // Load Min and Max values of inputs + nnet->mins = new double[( nnet->inputSize )]; + line = fgets( buffer, bufferSize, fstream ); + record = strtok( line, ",\n" ); + for ( i = 0; i < ( nnet->inputSize ); i++ ) { - nnet->mins[i] = atof(record); - record = strtok(NULL,",\n"); + nnet->mins[i] = atof( record ); + record = strtok( NULL, ",\n" ); } - nnet->maxes = new double[(nnet->inputSize)]; - line = fgets(buffer,bufferSize,fstream); - record = strtok(line,",\n"); - for (i = 0; i<(nnet->inputSize); i++) + nnet->maxes = new double[( nnet->inputSize )]; + line = fgets( buffer, bufferSize, fstream ); + record = strtok( line, ",\n" ); + for ( i = 0; i < ( nnet->inputSize ); i++ ) { - nnet->maxes[i] = atof(record); - record = strtok(NULL,",\n"); + nnet->maxes[i] = atof( record ); + record = strtok( NULL, ",\n" ); } - //Load Mean and Range of inputs - nnet->means = new double[(((nnet->inputSize)+1))]; - line = fgets(buffer,bufferSize,fstream); - record = strtok(line,",\n"); - for (i = 0; i<((nnet->inputSize)+1); i++) + // Load Mean and Range of inputs + nnet->means = new double[( ( ( nnet->inputSize ) + 1 ) )]; + line = fgets( buffer, bufferSize, fstream ); + record = strtok( line, ",\n" ); + for ( i = 0; i < ( ( nnet->inputSize ) + 1 ); i++ ) { - nnet->means[i] = atof(record); - record = strtok(NULL,",\n"); + nnet->means[i] = atof( record ); + record = strtok( NULL, ",\n" ); } - nnet->ranges = new double[(((nnet->inputSize)+1))]; - line = fgets(buffer,bufferSize,fstream); - record = strtok(line,",\n"); - for (i = 0; i<((nnet->inputSize)+1); i++) + nnet->ranges = new double[( ( ( nnet->inputSize ) + 1 ) )]; + line = fgets( buffer, bufferSize, fstream ); + record = strtok( line, ",\n" ); + for ( i = 0; i < ( ( nnet->inputSize ) + 1 ); i++ ) { - nnet->ranges[i] = atof(record); - record = strtok(NULL,",\n"); + nnet->ranges[i] = atof( record ); + record = strtok( NULL, ",\n" ); } - //Allocate space for matrix of Neural Network + // Allocate space for matrix of Neural Network // - //The first dimension will be the layer number - //The second dimension will be 0 for weights, 1 for biases - //The third dimension will be the number of neurons in that layer - //The fourth dimension will be the number of inputs to that layer + // The first dimension will be the layer number + // The second dimension will be 0 for weights, 1 for biases + // The third dimension will be the number of neurons in that layer + // The fourth dimension will be the number of inputs to that layer // - //Note that the bias array will have only number per neuron, so - // its fourth dimension will always be one + // Note that the bias array will have only number per neuron, so + // its fourth dimension will always be one // - nnet->matrix = new double ***[((nnet->numLayers))]; - for (layer = 0; layer<(nnet->numLayers); layer++) + nnet->matrix = new double ***[( ( nnet->numLayers ) )]; + for ( layer = 0; layer < ( nnet->numLayers ); layer++ ) { - nnet->matrix[layer] = new double**[2]; - nnet->matrix[layer][0] = new double*[nnet->layerSizes[layer+1]]; - nnet->matrix[layer][1] = new double*[nnet->layerSizes[layer+1]]; - for (row = 0; rowlayerSizes[layer+1]; row++) + nnet->matrix[layer] = new double **[2]; + nnet->matrix[layer][0] = new double *[nnet->layerSizes[layer + 1]]; + nnet->matrix[layer][1] = new double *[nnet->layerSizes[layer + 1]]; + for ( row = 0; row < nnet->layerSizes[layer + 1]; row++ ) { nnet->matrix[layer][0][row] = new double[nnet->layerSizes[layer]]; nnet->matrix[layer][1][row] = new double[1]; } } - //Iteration parameters + // Iteration parameters layer = 0; param = 0; - i=0; - j=0; + i = 0; + j = 0; - //Read in parameters and put them in the matrix - while((line=fgets(buffer,bufferSize,fstream))!=NULL) + // Read in parameters and put them in the matrix + while ( ( line = fgets( buffer, bufferSize, fstream ) ) != NULL ) { - if(i>=nnet->layerSizes[layer+1]) + if ( i >= nnet->layerSizes[layer + 1] ) { - if (param==0) + if ( param == 0 ) { param = 1; } @@ -147,16 +148,16 @@ AcasNnet *load_network(const char* filename) param = 0; layer++; } - i=0; - j=0; + i = 0; + j = 0; } - record = strtok(line,",\n"); - while(record != NULL) + record = strtok( line, ",\n" ); + while ( record != NULL ) { - nnet->matrix[layer][param][i][j++] = atof(record); - record = strtok(NULL,",\n"); + nnet->matrix[layer][param][i][j++] = atof( record ); + record = strtok( NULL, ",\n" ); } - j=0; + j = 0; i++; } nnet->inputs = new double[nnet->maxLayerSize]; @@ -164,159 +165,165 @@ AcasNnet *load_network(const char* filename) delete[] buffer; - fclose(fstream); + fclose( fstream ); - //return a pointer to the neural network + // return a pointer to the neural network return nnet; } -//Deallocate memory used by a neural network -//Inputs: void *network: Points to network struct -//Output: void -void destroy_network(AcasNnet *nnet) +// Deallocate memory used by a neural network +// Inputs: void *network: Points to network struct +// Output: void +void destroy_network( AcasNnet *nnet ) { - int i=0, row=0; - if (nnet!=NULL) + int i = 0, row = 0; + if ( nnet != NULL ) { - // AcasNnet *nnet = static_cast(network); - for(i=0; i<(nnet->numLayers); i++) + // AcasNnet *nnet = static_cast(network); + for ( i = 0; i < ( nnet->numLayers ); i++ ) { - for(row=0;rowlayerSizes[i+1];row++) + for ( row = 0; row < nnet->layerSizes[i + 1]; row++ ) { - //free weight and bias arrays + // free weight and bias arrays delete[] nnet->matrix[i][0][row]; delete[] nnet->matrix[i][1][row]; } - //free pointer to weights and biases - delete[](nnet->matrix[i][0]); - delete[](nnet->matrix[i][1]); + // free pointer to weights and biases + delete[]( nnet->matrix[i][0] ); + delete[]( nnet->matrix[i][1] ); - //free pointer to the layer of the network - delete[](nnet->matrix[i]); + // free pointer to the layer of the network + delete[]( nnet->matrix[i] ); } - //free network parameters and the struct - delete[](nnet->layerSizes); - delete[](nnet->mins); - delete[](nnet->maxes); - delete[](nnet->means); - delete[](nnet->ranges); - delete[](nnet->matrix); - delete[](nnet->inputs); - delete[](nnet->temp); - delete(nnet); + // free network parameters and the struct + delete[]( nnet->layerSizes ); + delete[]( nnet->mins ); + delete[]( nnet->maxes ); + delete[]( nnet->means ); + delete[]( nnet->ranges ); + delete[]( nnet->matrix ); + delete[]( nnet->inputs ); + delete[]( nnet->temp ); + delete ( nnet ); } } -//Complete one forward pass for a given set of inputs and return Q values -//Inputs: void *network - pointer to the neural net struct -// double *input - double pointer to the inputs to the network -// The inputs should be in form [r,th,psi,vOwn,vInt,tau,pa] -// with the angles being in radians -// double *output - double pointer to the outputs from the network +// Complete one forward pass for a given set of inputs and return Q values +// Inputs: void *network - pointer to the neural net struct +// double *input - double pointer to the inputs to the network +// The inputs should be in form [r,th,psi,vOwn,vInt,tau,pa] +// with the angles being in radians +// double *output - double pointer to the outputs from the network -//Output: int - 1 if the forward pass was successful, -1 otherwise -int evaluate_network(void *network, double *input, double *output, bool normalizeInput, bool normalizeOutput) +// Output: int - 1 if the forward pass was successful, -1 otherwise +int evaluate_network( void *network, + double *input, + double *output, + bool normalizeInput, + bool normalizeOutput ) { - int i,j,layer; - if (network ==NULL) + int i, j, layer; + if ( network == NULL ) { - printf("Data is Null!\n"); + printf( "Data is Null!\n" ); return -1; } - //Cast void* to AcasNnet struct pointer - AcasNnet *nnet = static_cast(network); - int numLayers = nnet->numLayers; - int inputSize = nnet->inputSize; - int outputSize = nnet->outputSize; - int symmetric = nnet->symmetric; + // Cast void* to AcasNnet struct pointer + AcasNnet *nnet = static_cast( network ); + int numLayers = nnet->numLayers; + int inputSize = nnet->inputSize; + int outputSize = nnet->outputSize; + int symmetric = nnet->symmetric; double ****matrix = nnet->matrix; - //Normalize inputs + // Normalize inputs if ( normalizeInput ) { - for (i=0; innet->maxes[i]) + if ( input[i] > nnet->maxes[i] ) { - nnet->inputs[i] = (nnet->maxes[i]-nnet->means[i])/(nnet->ranges[i]); + nnet->inputs[i] = ( nnet->maxes[i] - nnet->means[i] ) / ( nnet->ranges[i] ); } - else if (input[i]mins[i]) + else if ( input[i] < nnet->mins[i] ) { - nnet->inputs[i] = (nnet->mins[i]-nnet->means[i])/(nnet->ranges[i]); + nnet->inputs[i] = ( nnet->mins[i] - nnet->means[i] ) / ( nnet->ranges[i] ); } else { - nnet->inputs[i] = (input[i]-nnet->means[i])/(nnet->ranges[i]); + nnet->inputs[i] = ( input[i] - nnet->means[i] ) / ( nnet->ranges[i] ); } } - if (symmetric==1 && nnet->inputs[2]<0) + if ( symmetric == 1 && nnet->inputs[2] < 0 ) + { + nnet->inputs[2] = -nnet->inputs[2]; // Make psi positive + nnet->inputs[1] = -nnet->inputs[1]; // Flip across x-axis + } + else { - nnet->inputs[2] = -nnet->inputs[2]; //Make psi positive - nnet->inputs[1] = -nnet->inputs[1]; //Flip across x-axis - } else { symmetric = 0; } } else { - for (i=0; iinputs[i] = input[i]; } double tempVal; // printf("number of layers = %u\n", numLayers); - for (layer = 0; layer<(numLayers); layer++) + for ( layer = 0; layer < ( numLayers ); layer++ ) { - for (i=0; i < nnet->layerSizes[layer+1]; i++) + for ( i = 0; i < nnet->layerSizes[layer + 1]; i++ ) { double **weights = matrix[layer][0]; - double **biases = matrix[layer][1]; + double **biases = matrix[layer][1]; tempVal = 0.0; - //Perform weighted summation of inputs - for (j=0; jlayerSizes[layer]; j++) + // Perform weighted summation of inputs + for ( j = 0; j < nnet->layerSizes[layer]; j++ ) { - tempVal += nnet->inputs[j]*weights[i][j]; - + tempVal += nnet->inputs[j] * weights[i][j]; } - //Add bias to weighted sum + // Add bias to weighted sum tempVal += biases[i][0]; - //Perform ReLU - if (tempVal<0.0 && layer<(numLayers-1)) + // Perform ReLU + if ( tempVal < 0.0 && layer < ( numLayers - 1 ) ) { // printf( "doing RELU on layer %u\n", layer ); tempVal = 0.0; } - nnet->temp[i]=tempVal; + nnet->temp[i] = tempVal; } - //Output of one layer is the input to the next layer - for (i=0; i < nnet->layerSizes[layer+1]; i++) + // Output of one layer is the input to the next layer + for ( i = 0; i < nnet->layerSizes[layer + 1]; i++ ) { nnet->inputs[i] = nnet->temp[i]; } } - //Write the final output value to the allocated spot in memory - for (i=0; iinputs[i]*nnet->ranges[nnet->inputSize]+nnet->means[nnet->inputSize]; + output[i] = + nnet->inputs[i] * nnet->ranges[nnet->inputSize] + nnet->means[nnet->inputSize]; else output[i] = nnet->inputs[i]; } - //If symmetric, switch the Qvalues of actions -1.5 and 1.5 as well as -3 and 3 - if (symmetric == 1) + // If symmetric, switch the Qvalues of actions -1.5 and 1.5 as well as -3 and 3 + if ( symmetric == 1 ) { double tempValue = output[1]; output[1] = output[2]; @@ -326,35 +333,35 @@ int evaluate_network(void *network, double *input, double *output, bool normaliz output[4] = tempValue; } - //Return 1 for success + // Return 1 for success return 1; } -//Return the number of inputs to a network -//Inputs: void *network - pointer to a network struct -//Output: int - number of inputs to the network, -1 if the network is NULL -int num_inputs(void *network) +// Return the number of inputs to a network +// Inputs: void *network - pointer to a network struct +// Output: int - number of inputs to the network, -1 if the network is NULL +int num_inputs( void *network ) { - if (network ==NULL) + if ( network == NULL ) { - printf("Data is Null!\n"); + printf( "Data is Null!\n" ); return -1; } - AcasNnet *nnet = static_cast(network); + AcasNnet *nnet = static_cast( network ); return nnet->inputSize; } -//Return the number of outputs from a network -//Inputs: void *network - pointer to a network struct -//Output: int - number of outputs from the network, -1 if the network is NULL -int num_outputs(void *network) +// Return the number of outputs from a network +// Inputs: void *network - pointer to a network struct +// Output: int - number of outputs from the network, -1 if the network is NULL +int num_outputs( void *network ) { - if (network ==NULL) + if ( network == NULL ) { - printf("Data is Null!\n"); + printf( "Data is Null!\n" ); return -1; } - AcasNnet *nnet = static_cast(network); + AcasNnet *nnet = static_cast( network ); return nnet->outputSize; } diff --git a/src/input_parsers/AcasNnet.h b/src/input_parsers/AcasNnet.h index 90d71cef3a..f5c6a81cdc 100644 --- a/src/input_parsers/AcasNnet.h +++ b/src/input_parsers/AcasNnet.h @@ -16,32 +16,37 @@ #ifndef __AcasNnet_h__ #define __AcasNnet_h__ -//Neural Network Struct -class AcasNnet { +// Neural Network Struct +class AcasNnet +{ public: - int symmetric; //1 if network is symmetric, 0 otherwise - int numLayers; //Number of layers in the network - int inputSize; //Number of inputs to the network - int outputSize; //Number of outputs to the network - int maxLayerSize; //Maximum size dimension of a layer in the network - int *layerSizes; //Array of the dimensions of the layers in the network + int symmetric; // 1 if network is symmetric, 0 otherwise + int numLayers; // Number of layers in the network + int inputSize; // Number of inputs to the network + int outputSize; // Number of outputs to the network + int maxLayerSize; // Maximum size dimension of a layer in the network + int *layerSizes; // Array of the dimensions of the layers in the network - double *mins; //Minimum value of inputs - double *maxes; //Maximum value of inputs - double *means; //Array of the means used to scale the inputs and outputs - double *ranges; //Array of the ranges used to scale the inputs and outputs - double ****matrix; //4D jagged array that stores the weights and biases - //the neural network. - double *inputs; //Scratch array for inputs to the different layers - double *temp; //Scratch array for outputs of different layers + double *mins; // Minimum value of inputs + double *maxes; // Maximum value of inputs + double *means; // Array of the means used to scale the inputs and outputs + double *ranges; // Array of the ranges used to scale the inputs and outputs + double ****matrix; // 4D jagged array that stores the weights and biases + // the neural network. + double *inputs; // Scratch array for inputs to the different layers + double *temp; // Scratch array for outputs of different layers }; -//Functions Implemented -extern "C" AcasNnet *load_network(const char *filename); -extern "C" int num_inputs(void *network); -extern "C" int num_outputs(void *network); -extern "C" int evaluate_network(void *network, double *input, double *output, bool normalizeInput, bool normalizeOutput); -extern "C" void destroy_network(AcasNnet *network); +// Functions Implemented +extern "C" AcasNnet *load_network( const char *filename ); +extern "C" int num_inputs( void *network ); +extern "C" int num_outputs( void *network ); +extern "C" int evaluate_network( void *network, + double *input, + double *output, + bool normalizeInput, + bool normalizeOutput ); +extern "C" void destroy_network( AcasNnet *network ); #endif // __AcasNnet_h__ diff --git a/src/input_parsers/AcasParser.cpp b/src/input_parsers/AcasParser.cpp index 6a24af89ab..3bb1fe7070 100644 --- a/src/input_parsers/AcasParser.cpp +++ b/src/input_parsers/AcasParser.cpp @@ -14,6 +14,7 @@ **/ #include "AcasParser.h" + #include "FloatUtils.h" #include "InputParserError.h" #include "InputQuery.h" @@ -51,8 +52,12 @@ void AcasParser::generateQuery( InputQuery &inputQuery ) for ( unsigned i = 1; i < numberOfLayers - 1; ++i ) numberOfInternalNodes += _acasNeuralNetwork.getLayerSize( i ); - printf( "Number of layers: %u. Input layer size: %u. Output layer size: %u. Number of ReLUs: %u\n", - numberOfLayers, inputLayerSize, outputLayerSize, numberOfInternalNodes ); + printf( + "Number of layers: %u. Input layer size: %u. Output layer size: %u. Number of ReLUs: %u\n", + numberOfLayers, + inputLayerSize, + outputLayerSize, + numberOfInternalNodes ); // The total number of variables required for the encoding is computed as follows: // 1. Each input node appears once @@ -95,8 +100,8 @@ void AcasParser::generateQuery( InputQuery &inputQuery ) double min, max; _acasNeuralNetwork.getInputRange( i, min, max ); - inputQuery.setLowerBound( _nodeToF[NodeIndex(0, i)], min ); - inputQuery.setUpperBound( _nodeToF[NodeIndex(0, i)], max ); + inputQuery.setLowerBound( _nodeToF[NodeIndex( 0, i )], min ); + inputQuery.setUpperBound( _nodeToF[NodeIndex( 0, i )], max ); } for ( const auto &fNode : _nodeToF ) @@ -126,13 +131,13 @@ void AcasParser::generateQuery( InputQuery &inputQuery ) Equation equation; // The b variable - unsigned bVar = _nodeToB[NodeIndex(layer + 1, target)]; + unsigned bVar = _nodeToB[NodeIndex( layer + 1, target )]; equation.addAddend( -1.0, bVar ); // The f variables from the previous layer for ( unsigned source = 0; source < _acasNeuralNetwork.getLayerSize( layer ); ++source ) { - unsigned fVar = _nodeToF[NodeIndex(layer, source)]; + unsigned fVar = _nodeToF[NodeIndex( layer, source )]; equation.addAddend( _acasNeuralNetwork.getWeight( layer, source, target ), fVar ); } @@ -151,8 +156,8 @@ void AcasParser::generateQuery( InputQuery &inputQuery ) for ( unsigned j = 0; j < currentLayerSize; ++j ) { - unsigned b = _nodeToB[NodeIndex(i, j)]; - unsigned f = _nodeToF[NodeIndex(i, j)]; + unsigned b = _nodeToB[NodeIndex( i, j )]; + unsigned f = _nodeToF[NodeIndex( i, j )]; PiecewiseLinearConstraint *relu = new ReluConstraint( b, f ); inputQuery.addPiecewiseLinearConstraint( relu ); @@ -207,8 +212,8 @@ unsigned AcasParser::getFVariable( unsigned layer, unsigned index ) const void AcasParser::evaluate( const Vector &inputs, Vector &outputs ) const { - _acasNeuralNetwork.evaluate( inputs, outputs, - _acasNeuralNetwork.getLayerSize( _acasNeuralNetwork.getNumLayers() ) ); + _acasNeuralNetwork.evaluate( + inputs, outputs, _acasNeuralNetwork.getLayerSize( _acasNeuralNetwork.getNumLayers() ) ); } // diff --git a/src/input_parsers/BerkeleyNeuralNetwork.cpp b/src/input_parsers/BerkeleyNeuralNetwork.cpp index 9805093501..a789709a54 100644 --- a/src/input_parsers/BerkeleyNeuralNetwork.cpp +++ b/src/input_parsers/BerkeleyNeuralNetwork.cpp @@ -14,6 +14,7 @@ **/ #include "BerkeleyNeuralNetwork.h" + #include "CommonError.h" BerkeleyNeuralNetwork::Equation::Equation() @@ -102,7 +103,10 @@ void BerkeleyNeuralNetwork::parseFile() } printf( "Max var: %u. Number of vars: %u. Number of LHS vars: %u. Number of equations: %u\n", - _maxVar, _allVars.size(), _allLhsVars.size(), _equations.size() ); + _maxVar, + _allVars.size(), + _allLhsVars.size(), + _equations.size() ); _inputVars = Set::difference( _allVars, _allLhsVars ); _outputVars = Set::difference( _allVars, _allRhsVars ); diff --git a/src/input_parsers/BerkeleyNeuralNetwork.h b/src/input_parsers/BerkeleyNeuralNetwork.h index dc7c69b358..21c2c34067 100644 --- a/src/input_parsers/BerkeleyNeuralNetwork.h +++ b/src/input_parsers/BerkeleyNeuralNetwork.h @@ -18,9 +18,9 @@ #include "File.h" #include "MString.h" +#include "Map.h" #include "Set.h" #include "Vector.h" -#include "Map.h" #include #include @@ -73,8 +73,8 @@ class BerkeleyNeuralNetwork /* Maps from b to f variables, and vice-versa. */ - Map _bToF; - Map _fToB; + Map _bToF; + Map _fToB; /* All equations extracted from the file. diff --git a/src/input_parsers/BerkeleyParser.cpp b/src/input_parsers/BerkeleyParser.cpp index 071ea13e05..3c80969053 100644 --- a/src/input_parsers/BerkeleyParser.cpp +++ b/src/input_parsers/BerkeleyParser.cpp @@ -14,6 +14,7 @@ **/ #include "BerkeleyParser.h" + #include "FloatUtils.h" #include "InputQuery.h" #include "ReluConstraint.h" @@ -30,8 +31,7 @@ void BerkeleyParser::generateQuery( InputQuery &inputQuery ) // The total number of variables required for the encoding is computed as follows: // 1. One for every variable that's part of the query - unsigned numberOfVariables = - _berkeleyNeuralNetwork.getNumVariables(); + unsigned numberOfVariables = _berkeleyNeuralNetwork.getNumVariables(); printf( "Total number of Marabou variables: %u\n", numberOfVariables ); @@ -100,7 +100,9 @@ void BerkeleyParser::addAuxiliaryEquations( List &auxiliaryEquations ) addAuxiliaryEquation( fToB.first, fToB.second, auxiliaryEquations ); } -void BerkeleyParser::addAuxiliaryEquation( unsigned xf, unsigned xb, List &auxiliaryEquations ) +void BerkeleyParser::addAuxiliaryEquation( unsigned xf, + unsigned xb, + List &auxiliaryEquations ) { Set inputVariables = _berkeleyNeuralNetwork.getInputVariables(); diff --git a/src/input_parsers/InputParserError.h b/src/input_parsers/InputParserError.h index 4bac1bf895..15a9f5b73e 100644 --- a/src/input_parsers/InputParserError.h +++ b/src/input_parsers/InputParserError.h @@ -21,7 +21,7 @@ class InputParserError : public Error { public: - enum Code { + enum Code { VARIABLE_INDEX_OUT_OF_RANGE = 0, UNEXPECTED_INPUT = 1, FILE_DOESNT_EXIST = 2, @@ -30,12 +30,13 @@ class InputParserError : public Error HIDDEN_VARIABLE_DOESNT_EXIST_IN_NLR = 5, }; - InputParserError( InputParserError::Code code ) : Error( "InputParserError", (int)code ) - { - } + InputParserError( InputParserError::Code code ) + : Error( "InputParserError", (int)code ) + { + } InputParserError( InputParserError::Code code, const char *userMessage ) - : Error( "InputParserError", (int)code, userMessage ) + : Error( "InputParserError", (int)code, userMessage ) { } }; diff --git a/src/input_parsers/MpsParser.cpp b/src/input_parsers/MpsParser.cpp index 880db376bb..84125064a4 100644 --- a/src/input_parsers/MpsParser.cpp +++ b/src/input_parsers/MpsParser.cpp @@ -13,12 +13,14 @@ **/ +#include "MpsParser.h" + #include "File.h" #include "FloatUtils.h" #include "InputParserError.h" #include "InputQuery.h" #include "MStringf.h" -#include "MpsParser.h" + #include MpsParser::MpsParser( const String &path ) @@ -45,27 +47,27 @@ void MpsParser::parse( const String &path ) String line; while ( true ) - { + { line = file.readLine(); if ( line.contains( "COLUMNS" ) ) - break; + break; - parseRow( line ); - } + parseRow( line ); + } MPS_LOG( Stringf( "Number of rows parsed: %u", _numRows ).ascii() ); // Finished parsing rows, proceed to columns while ( true ) - { + { line = file.readLine(); if ( line.contains( "RHS" ) ) - break; + break; - parseColumn( line ); - } + parseColumn( line ); + } MPS_LOG( Stringf( "Number of variables detected: %u\n", _numVars ).ascii() ); @@ -78,7 +80,7 @@ void MpsParser::parse( const String &path ) break; parseRhs( line ); - } + } // The bounds section is optional, process it if it exists if ( line.contains( "BOUNDS" ) ) @@ -102,7 +104,7 @@ void MpsParser::parseRow( const String &line ) List tokens = line.tokenize( "\t\n " ); if ( tokens.size() != 2 ) - throw InputParserError( InputParserError::UNEXPECTED_INPUT, line.ascii() ); + throw InputParserError( InputParserError::UNEXPECTED_INPUT, line.ascii() ); auto it = tokens.begin(); String type = *it; @@ -140,7 +142,7 @@ void MpsParser::parseColumn( const String &line ) // Need an odd number of tokens: row name + pairs if ( tokens.size() % 2 == 0 ) - throw InputParserError( InputParserError::UNEXPECTED_INPUT, line.ascii() ); + throw InputParserError( InputParserError::UNEXPECTED_INPUT, line.ascii() ); // Variable name and index auto it = tokens.begin(); @@ -148,9 +150,9 @@ void MpsParser::parseColumn( const String &line ) ++it; if ( !_variableNameToIndex.exists( name ) ) { - _variableNameToIndex[name] = _numVars; - _variableIndexToName[_numVars] = name; - ++_numVars; + _variableNameToIndex[name] = _numVars; + _variableIndexToName[_numVars] = name; + ++_numVars; } unsigned varIndex = _variableNameToIndex[name]; @@ -173,8 +175,10 @@ void MpsParser::parseColumn( const String &line ) { // The pair describes a coefficient in an unknown equation (the objective function?) if ( coefficient != 0 ) - throw InputParserError( InputParserError::UNEXPECTED_INPUT, - Stringf( "Problematic pair: %s, %.2lf", equationName.ascii(), coefficient ).ascii() ); + throw InputParserError( + InputParserError::UNEXPECTED_INPUT, + Stringf( "Problematic pair: %s, %.2lf", equationName.ascii(), coefficient ) + .ascii() ); } } } @@ -185,7 +189,7 @@ void MpsParser::parseRhs( const String &line ) // Need an odd number of tokens: RHS + pairs if ( tokens.size() % 2 == 0 ) - throw InputParserError( InputParserError::UNEXPECTED_INPUT, line.ascii() ); + throw InputParserError( InputParserError::UNEXPECTED_INPUT, line.ascii() ); auto it = tokens.begin(); String name = *it; @@ -213,7 +217,7 @@ void MpsParser::parseBounds( const String &line ) List tokens = line.tokenize( "\t\n " ); if ( tokens.size() != 4 ) - throw InputParserError( InputParserError::UNEXPECTED_INPUT, line.ascii() ); + throw InputParserError( InputParserError::UNEXPECTED_INPUT, line.ascii() ); auto it = tokens.begin(); String type = *it; @@ -241,7 +245,7 @@ void MpsParser::parseBounds( const String &line ) // Lower bound if ( !_varToLowerBounds.exists( varIndex ) || ( _varToLowerBounds[varIndex] < scalar ) ) _varToLowerBounds[varIndex] = scalar; - } + } else if ( type == "FX" ) { // Upper and lower bound @@ -250,7 +254,7 @@ void MpsParser::parseBounds( const String &line ) if ( !_varToLowerBounds.exists( varIndex ) || ( _varToLowerBounds[varIndex] < scalar ) ) _varToLowerBounds[varIndex] = scalar; - } + } else { throw InputParserError( InputParserError::UNSUPPORTED_BOUND_TYPE, line.ascii() ); @@ -264,7 +268,7 @@ void MpsParser::setRemainingBounds() { if ( !_varToLowerBounds.exists( i ) && ( !_varToUpperBounds.exists( i ) || _varToUpperBounds[i] >= 0 ) ) - _varToLowerBounds[i] = 0; + _varToLowerBounds[i] = 0; } } @@ -330,7 +334,7 @@ void MpsParser::populateEquation( Equation &equation, unsigned index ) const const Map &coeffs( _equationIndexToCoefficients[index] ); for ( const auto &pair : coeffs ) - equation.addAddend( pair.second, pair.first ); + equation.addAddend( pair.second, pair.first ); switch ( _equationIndexToRowType[index] ) { diff --git a/src/input_parsers/MpsParser.h b/src/input_parsers/MpsParser.h index 0c939889c0..c77e024dd7 100644 --- a/src/input_parsers/MpsParser.h +++ b/src/input_parsers/MpsParser.h @@ -20,7 +20,7 @@ #include "Map.h" #include "Set.h" -#define MPS_LOG(x, ...) LOG(GlobalConfiguration::MPS_PARSER_LOGGING, "MpsParser: %s\n", x) +#define MPS_LOG( x, ... ) LOG( GlobalConfiguration::MPS_PARSER_LOGGING, "MpsParser: %s\n", x ) class InputQuery; class String; diff --git a/src/input_parsers/NetworkParser.cpp b/src/input_parsers/NetworkParser.cpp index 5caffd31d4..bfb80477f6 100644 --- a/src/input_parsers/NetworkParser.cpp +++ b/src/input_parsers/NetworkParser.cpp @@ -14,19 +14,20 @@ ** may be altered during parsing of a network. Once the network has been parsed ** they are then loaded into an InputQuery. ** Future parsers for individual network formats should extend this interface. -**/ + **/ #include "NetworkParser.h" -#include "Map.h" -#include "List.h" + +#include "Debug.h" #include "FloatUtils.h" #include "InputParserError.h" -#include "MString.h" #include "InputQuery.h" +#include "List.h" #include "MString.h" -#include "Set.h" #include "MStringf.h" -#include "Debug.h" +#include "Map.h" +#include "Set.h" + #include NetworkParser::NetworkParser() @@ -34,10 +35,10 @@ NetworkParser::NetworkParser() _numVars = 0; } -Variable NetworkParser::getNewVariable(){ - +Variable NetworkParser::getNewVariable() +{ _numVars += 1; - return _numVars-1; + return _numVars - 1; } void NetworkParser::addEquation( Equation &eq ) @@ -80,7 +81,7 @@ void NetworkParser::addAbsConstraint( Variable inputVar, Variable outputVar ) _absList.append( new AbsoluteValueConstraint( inputVar, outputVar ) ); } -void NetworkParser::getMarabouQuery( InputQuery& query ) +void NetworkParser::getMarabouQuery( InputQuery &query ) { query.setNumberOfVariables( _numVars ); @@ -103,39 +104,39 @@ void NetworkParser::getMarabouQuery( InputQuery& query ) query.addEquation( equation ); } - for ( ReluConstraint* constraintPtr : _reluList ) + for ( ReluConstraint *constraintPtr : _reluList ) { ReluConstraint constraint = *constraintPtr; ASSERT( constraint.getB() < _numVars && constraint.getF() < _numVars ); query.addPiecewiseLinearConstraint( constraintPtr ); } - for ( SigmoidConstraint* constraintPtr : _sigmoidList ) + for ( SigmoidConstraint *constraintPtr : _sigmoidList ) { SigmoidConstraint constraint = *constraintPtr; ASSERT( constraint.getB() < _numVars && constraint.getF() < _numVars ); query.addNonlinearConstraint( constraintPtr ); } - for ( MaxConstraint* constraintPtr : _maxList ) + for ( MaxConstraint *constraintPtr : _maxList ) { MaxConstraint constraint = *constraintPtr; ASSERT( constraint.getF() < _numVars ); for ( [[maybe_unused]] Variable var : constraint.getElements() ) { - ASSERT ( var < _numVars ); + ASSERT( var < _numVars ); } query.addPiecewiseLinearConstraint( constraintPtr ); } - for ( AbsoluteValueConstraint* constraintPtr : _absList ) + for ( AbsoluteValueConstraint *constraintPtr : _absList ) { AbsoluteValueConstraint constraint = *constraintPtr; ASSERT( constraint.getB() < _numVars && constraint.getF() < _numVars ); query.addPiecewiseLinearConstraint( constraintPtr ); } - for ( SignConstraint* constraintPtr : _signList ) + for ( SignConstraint *constraintPtr : _signList ) { SignConstraint constraint = *constraintPtr; ASSERT( constraint.getB() < _numVars && constraint.getF() < _numVars ); @@ -143,23 +144,23 @@ void NetworkParser::getMarabouQuery( InputQuery& query ) } // TODO check this last two - for ( std::pair lower : _lowerBounds ) + for ( std::pair lower : _lowerBounds ) { ASSERT( lower.first < _numVars ); - query.setLowerBound( lower.first,lower.second ); + query.setLowerBound( lower.first, lower.second ); } - for ( std::pair upper : _upperBounds ) + for ( std::pair upper : _upperBounds ) { ASSERT( upper.first < _numVars ); - query.setUpperBound( upper.first,upper.second ); + query.setUpperBound( upper.first, upper.second ); } } int NetworkParser::findEquationWithOutputVariable( Variable variable ) { int i = 0; - for ( Equation& equation : _equationList ) + for ( Equation &equation : _equationList ) { Equation::Addend outputAddend = equation._addends.back(); if ( variable == outputAddend._variable ) diff --git a/src/input_parsers/NetworkParser.h b/src/input_parsers/NetworkParser.h index 2d64d19091..e4304fe61f 100644 --- a/src/input_parsers/NetworkParser.h +++ b/src/input_parsers/NetworkParser.h @@ -19,23 +19,25 @@ #ifndef __NetworkParser_h__ #define __NetworkParser_h__ -#include "Map.h" -#include "List.h" -#include "Vector.h" +#include "DisjunctionConstraint.h" #include "Equation.h" #include "InputQuery.h" -#include "ReluConstraint.h" -#include "DisjunctionConstraint.h" +#include "List.h" +#include "Map.h" #include "MaxConstraint.h" +#include "NonlinearConstraint.h" #include "PiecewiseLinearConstraint.h" +#include "ReluConstraint.h" #include "SigmoidConstraint.h" #include "SignConstraint.h" -#include "NonlinearConstraint.h" +#include "Vector.h" + #include typedef unsigned int Variable; -class NetworkParser { +class NetworkParser +{ private: unsigned int _numVars; @@ -44,13 +46,13 @@ class NetworkParser { List _outputVars; Vector _equationList; - List _reluList; - List _sigmoidList; - List _maxList; - List _absList; - List _signList; - Map _lowerBounds; - Map _upperBounds; + List _reluList; + List _sigmoidList; + List _maxList; + List _absList; + List _signList; + Map _lowerBounds; + Map _upperBounds; NetworkParser(); void initNetwork(); @@ -65,7 +67,7 @@ class NetworkParser { void addAbsConstraint( Variable var1, Variable var2 ); Variable getNewVariable(); - void getMarabouQuery( InputQuery& query ); + void getMarabouQuery( InputQuery &query ); int findEquationWithOutputVariable( Variable variable ); }; diff --git a/src/input_parsers/OnnxParser.cpp b/src/input_parsers/OnnxParser.cpp index b79dac9fdd..7eacb65d7b 100644 --- a/src/input_parsers/OnnxParser.cpp +++ b/src/input_parsers/OnnxParser.cpp @@ -20,16 +20,18 @@ ** Likewise, this is why we store the shape data in a separate data structure ** rather than simply retrieving it when needed. ** - Node names are not unique, and do not necessarily even exist. -**/ + **/ #include "OnnxParser.h" + #include "FloatUtils.h" #include "InputParserError.h" #include "InputQuery.h" #include "MString.h" #include "ReluConstraint.h" -#include "onnx.proto3.pb.h" #include "TensorUtils.h" +#include "onnx.proto3.pb.h" + #include #include #include @@ -62,7 +64,7 @@ OnnxParser::OnnxParser( const String &path ) * * @param query The query object to be populated. */ -void OnnxParser::generateQuery( InputQuery& query ) +void OnnxParser::generateQuery( InputQuery &query ) { Set inputNames = readInputNames(); String outputName = readOutputName(); @@ -78,7 +80,9 @@ void OnnxParser::generateQuery( InputQuery& query ) * @param outputName The output node. Note that again this doesn't have to be an actual output of * the network, it can be an intermediate node. */ -void OnnxParser::generatePartialQuery( InputQuery& query, Set& inputNames, String& outputName ) +void OnnxParser::generatePartialQuery( InputQuery &query, + Set &inputNames, + String &outputName ) { validateUserInputNames( inputNames ); validateUserOutputNames( outputName ); @@ -89,9 +93,12 @@ void OnnxParser::generatePartialQuery( InputQuery& query, Set& inputName * Utilities * *************/ -void illTypedAttributeError( onnx::NodeProto &node, const onnx::AttributeProto& attr, onnx::AttributeProto_AttributeType expectedType ) +void illTypedAttributeError( onnx::NodeProto &node, + const onnx::AttributeProto &attr, + onnx::AttributeProto_AttributeType expectedType ) { - String errorMessage = Stringf( "Expected attribute %s on Onnx node of type %s to be of type %d but is actually of type %d", + String errorMessage = Stringf( + "Expected attribute %s on Onnx node of type %s to be of type %d but is actually of type %d", attr.name().c_str(), node.op_type().c_str(), expectedType, @@ -101,63 +108,78 @@ void illTypedAttributeError( onnx::NodeProto &node, const onnx::AttributeProto& void missingAttributeError( onnx::NodeProto &node, String attributeName ) { - String errorMessage = Stringf( "Onnx node of type %s is missing the expected attribute %s", node.op_type().c_str(), attributeName.ascii() ); + String errorMessage = Stringf( "Onnx node of type %s is missing the expected attribute %s", + node.op_type().c_str(), + attributeName.ascii() ); throw MarabouError( MarabouError::ONNX_PARSER_ERROR, errorMessage.ascii() ); } void unimplementedOperationError( onnx::NodeProto &node ) { - String errorMessage = Stringf( "Onnx '%s' operation not yet implemented for command line support. Should be relatively easy to add.", node.op_type().c_str() ) ; - throw MarabouError( MarabouError::ONNX_PARSER_ERROR, errorMessage.ascii() ) ; + String errorMessage = Stringf( "Onnx '%s' operation not yet implemented for command line " + "support. Should be relatively easy to add.", + node.op_type().c_str() ); + throw MarabouError( MarabouError::ONNX_PARSER_ERROR, errorMessage.ascii() ); } -void unimplementedAttributeError ( onnx::NodeProto &node, String attributeName ) +void unimplementedAttributeError( onnx::NodeProto &node, String attributeName ) { - String errorMessage = Stringf( "Onnx '%s' operation with non-default value for attribute '%s' not yet supported.", node.op_type().c_str(), attributeName.ascii() ) ; - throw MarabouError( MarabouError::ONNX_PARSER_ERROR, errorMessage.ascii() ) ; + String errorMessage = + Stringf( "Onnx '%s' operation with non-default value for attribute '%s' not yet supported.", + node.op_type().c_str(), + attributeName.ascii() ); + throw MarabouError( MarabouError::ONNX_PARSER_ERROR, errorMessage.ascii() ); } void unimplementedConstantTypeError( onnx::TensorProto_DataType type ) { - String errorMessage = Stringf( "Support for Onnx constants of type '%s' not yet implemented.", TensorProto_DataType_Name(type).c_str() ) ; - throw MarabouError( MarabouError::ONNX_PARSER_ERROR, errorMessage.ascii() ) ; + String errorMessage = Stringf( "Support for Onnx constants of type '%s' not yet implemented.", + TensorProto_DataType_Name( type ).c_str() ); + throw MarabouError( MarabouError::ONNX_PARSER_ERROR, errorMessage.ascii() ); } void unsupportedError( onnx::NodeProto &node ) { - String errorMessage = Stringf( "Onnx operation %s not currently supported by Marabou", node.op_type().c_str() ); + String errorMessage = + Stringf( "Onnx operation %s not currently supported by Marabou", node.op_type().c_str() ); throw MarabouError( MarabouError::ONNX_PARSER_ERROR, errorMessage.ascii() ); } -void unexpectedNegativeValue (int value, String location) +void unexpectedNegativeValue( int value, String location ) { - String errorMessage = Stringf( "Found unexpected negative value '%d' for '%s'", value, location.ascii() ); + String errorMessage = + Stringf( "Found unexpected negative value '%d' for '%s'", value, location.ascii() ); throw MarabouError( MarabouError::ONNX_PARSER_ERROR, errorMessage.ascii() ); } -void missingNodeError( String& missingNodeName ) +void missingNodeError( String &missingNodeName ) { - String errorMessage = Stringf( "Internal invariant violated: missing node '%s' not found", missingNodeName.ascii() ); - throw MarabouError( MarabouError::ONNX_PARSER_ERROR, errorMessage.ascii() ); + String errorMessage = Stringf( "Internal invariant violated: missing node '%s' not found", + missingNodeName.ascii() ); + throw MarabouError( MarabouError::ONNX_PARSER_ERROR, errorMessage.ascii() ); } -void checkTensorDataSourceIsInternal( const onnx::TensorProto& tensor ) +void checkTensorDataSourceIsInternal( const onnx::TensorProto &tensor ) { if ( tensor.data_location() == onnx::TensorProto_DataLocation_EXTERNAL ) { - String errorMessage = Stringf( "External data locations not yet implemented for command line Onnx support" ); + String errorMessage = + Stringf( "External data locations not yet implemented for command line Onnx support" ); throw MarabouError( MarabouError::ONNX_PARSER_ERROR, errorMessage.ascii() ); } } -void checkTensorDataType( const onnx::TensorProto& tensor, int32_t expectedDataType ) +void checkTensorDataType( const onnx::TensorProto &tensor, int32_t expectedDataType ) { int32_t actualDataType = tensor.data_type(); if ( actualDataType != expectedDataType ) { std::string actualName = onnx::TensorProto_DataType_Name( actualDataType ); std::string expectedName = onnx::TensorProto_DataType_Name( actualDataType ); - String errorMessage = Stringf( "Expected tensor '%s' to be of type %s but actually of type %s", expectedName.c_str(), actualName.c_str() ); + String errorMessage = + Stringf( "Expected tensor '%s' to be of type %s but actually of type %s", + expectedName.c_str(), + actualName.c_str() ); throw MarabouError( MarabouError::ONNX_PARSER_ERROR, errorMessage.ascii() ); } } @@ -170,7 +192,8 @@ TensorShape shapeOfInput( onnx::ValueInfoProto &input ) int size = dim.dim_value(); if ( size < 0 ) { - String errorMessage = Stringf( "Found input tensor in ONNX file with invalid size '%d'", size ); + String errorMessage = + Stringf( "Found input tensor in ONNX file with invalid size '%d'", size ); throw MarabouError( MarabouError::ONNX_PARSER_ERROR, errorMessage.ascii() ); } else if ( size == 0 ) @@ -213,7 +236,8 @@ TensorShape shapeOfConstant( const onnx::TensorProto &constant ) * old shape. * @return */ -TensorShape instantiateReshapeTemplate( TensorShape oldShape, Vector newShapeTemplate, bool allowZero ) +TensorShape +instantiateReshapeTemplate( TensorShape oldShape, Vector newShapeTemplate, bool allowZero ) { TensorShape newShape; int inferredIndex = -1; @@ -256,14 +280,16 @@ void checkEndianness() bool systemIsLittleEndian = *(char *)&num == 1; if ( !systemIsLittleEndian ) { - String errorMessage = "Support for Onnx files on non-little endian systems is not currently implemented on the command line"; + String errorMessage = "Support for Onnx files on non-little endian systems is not " + "currently implemented on the command line"; throw MarabouError( MarabouError::ONNX_PARSER_ERROR, errorMessage.ascii() ); } } -const onnx::AttributeProto* findAttribute( onnx::NodeProto& node, String name, onnx::AttributeProto_AttributeType expectedType ) +const onnx::AttributeProto * +findAttribute( onnx::NodeProto &node, String name, onnx::AttributeProto_AttributeType expectedType ) { - for ( const onnx::AttributeProto& attr : node.attribute() ) + for ( const onnx::AttributeProto &attr : node.attribute() ) { if ( attr.name() == name.ascii() ) { @@ -277,9 +303,10 @@ const onnx::AttributeProto* findAttribute( onnx::NodeProto& node, String name, o return nullptr; } -float getFloatAttribute( onnx::NodeProto& node, String name, float defaultValue ) +float getFloatAttribute( onnx::NodeProto &node, String name, float defaultValue ) { - const onnx::AttributeProto* attr = findAttribute( node, name, onnx::AttributeProto_AttributeType_FLOAT ); + const onnx::AttributeProto *attr = + findAttribute( node, name, onnx::AttributeProto_AttributeType_FLOAT ); if ( attr == nullptr ) { return defaultValue; @@ -287,9 +314,10 @@ float getFloatAttribute( onnx::NodeProto& node, String name, float defaultValue return attr->f(); } -String getStringAttribute( onnx::NodeProto& node, String name, String defaultValue ) +String getStringAttribute( onnx::NodeProto &node, String name, String defaultValue ) { - const onnx::AttributeProto* attr = findAttribute( node, name, onnx::AttributeProto_AttributeType_STRING ); + const onnx::AttributeProto *attr = + findAttribute( node, name, onnx::AttributeProto_AttributeType_STRING ); if ( attr == nullptr ) { return defaultValue; @@ -297,9 +325,10 @@ String getStringAttribute( onnx::NodeProto& node, String name, String defaultVal return attr->s(); } -int getIntAttribute( onnx::NodeProto& node, String name, int defaultValue ) +int getIntAttribute( onnx::NodeProto &node, String name, int defaultValue ) { - const onnx::AttributeProto* attr = findAttribute( node, name, onnx::AttributeProto_AttributeType_INT ); + const onnx::AttributeProto *attr = + findAttribute( node, name, onnx::AttributeProto_AttributeType_INT ); if ( attr == nullptr ) { return defaultValue; @@ -307,9 +336,10 @@ int getIntAttribute( onnx::NodeProto& node, String name, int defaultValue ) return attr->i(); } -const onnx::TensorProto& getTensorAttribute( onnx::NodeProto& node, String name ) +const onnx::TensorProto &getTensorAttribute( onnx::NodeProto &node, String name ) { - const onnx::AttributeProto* attr = findAttribute( node, name, onnx::AttributeProto_AttributeType_TENSOR ); + const onnx::AttributeProto *attr = + findAttribute( node, name, onnx::AttributeProto_AttributeType_TENSOR ); if ( attr == nullptr ) { missingAttributeError( node, name ); @@ -317,9 +347,10 @@ const onnx::TensorProto& getTensorAttribute( onnx::NodeProto& node, String name return attr->t(); } -Vector getIntsAttribute( onnx::NodeProto& node, String name, Vector& defaultValue ) +Vector getIntsAttribute( onnx::NodeProto &node, String name, Vector &defaultValue ) { - const onnx::AttributeProto* attr = findAttribute( node, name, onnx::AttributeProto_AttributeType_INTS ); + const onnx::AttributeProto *attr = + findAttribute( node, name, onnx::AttributeProto_AttributeType_INTS ); if ( attr == nullptr ) { return defaultValue; @@ -333,9 +364,11 @@ Vector getIntsAttribute( onnx::NodeProto& node, String name, Vector& d return result; } -Vector getNonNegativeIntsAttribute( onnx::NodeProto& node, String name, Vector& defaultValue ) +Vector +getNonNegativeIntsAttribute( onnx::NodeProto &node, String name, Vector &defaultValue ) { - const onnx::AttributeProto* attr = findAttribute( node, name, onnx::AttributeProto_AttributeType_INTS ); + const onnx::AttributeProto *attr = + findAttribute( node, name, onnx::AttributeProto_AttributeType_INTS ); if ( attr == nullptr ) { return defaultValue; @@ -347,21 +380,20 @@ Vector getNonNegativeIntsAttribute( onnx::NodeProto& node, String int value = attr->ints( i ); if ( value >= 0 ) { - result.append( (uint) value ); + result.append( (uint)value ); } else { - String location = Stringf("attribute '%s' on node '%s'", name.ascii(), node.name().c_str()); + String location = + Stringf( "attribute '%s' on node '%s'", name.ascii(), node.name().c_str() ); unexpectedNegativeValue( value, location ); } - } return result; } - -Vector getTensorFloatValues( const onnx::TensorProto& tensor, const TensorShape shape ) +Vector getTensorFloatValues( const onnx::TensorProto &tensor, const TensorShape shape ) { int size = tensorSize( shape ); std::string raw_data = tensor.raw_data(); @@ -369,11 +401,11 @@ Vector getTensorFloatValues( const onnx::TensorProto& tensor, const Tens if ( raw_data.size() != 0 ) { checkEndianness(); - const char* bytes = raw_data.c_str(); - const float* floats = reinterpret_cast( bytes ); + const char *bytes = raw_data.c_str(); + const float *floats = reinterpret_cast( bytes ); for ( int i = 0; i < size; i++ ) { - result.append( *(floats + i) ); + result.append( *( floats + i ) ); } } else @@ -386,7 +418,7 @@ Vector getTensorFloatValues( const onnx::TensorProto& tensor, const Tens return result; } -Vector getTensorIntValues( const onnx::TensorProto& tensor, const TensorShape shape ) +Vector getTensorIntValues( const onnx::TensorProto &tensor, const TensorShape shape ) { int size = tensorSize( shape ); std::string raw_data = tensor.raw_data(); @@ -394,11 +426,11 @@ Vector getTensorIntValues( const onnx::TensorProto& tensor, const TensorSha if ( raw_data.size() != 0 ) { checkEndianness(); - const char* bytes = raw_data.c_str(); - const int* ints = reinterpret_cast( bytes ); + const char *bytes = raw_data.c_str(); + const int *ints = reinterpret_cast( bytes ); for ( int i = 0; i < size; i++ ) { - int value = *(ints + i); + int value = *( ints + i ); result.append( value ); } } @@ -415,20 +447,22 @@ Vector getTensorIntValues( const onnx::TensorProto& tensor, const TensorSha bool OnnxParser::isConstantNode( String name ) { - return _constantIntTensors.exists( name ) - || _constantFloatTensors.exists( name ); + return _constantIntTensors.exists( name ) || _constantFloatTensors.exists( name ); } -void OnnxParser::insertConstant( String name, const onnx::TensorProto& tensor, const TensorShape shape ) +void OnnxParser::insertConstant( String name, + const onnx::TensorProto &tensor, + const TensorShape shape ) { checkTensorDataSourceIsInternal( tensor ); - onnx::TensorProto_DataType dataType = static_cast( tensor.data_type() ); - if( dataType == onnx::TensorProto_DataType_INT64 ) + onnx::TensorProto_DataType dataType = + static_cast( tensor.data_type() ); + if ( dataType == onnx::TensorProto_DataType_INT64 ) { _constantIntTensors.insert( name, getTensorIntValues( tensor, shape ) ); } - else if( dataType == onnx::TensorProto_DataType_FLOAT) + else if ( dataType == onnx::TensorProto_DataType_FLOAT ) { _constantFloatTensors.insert( name, getTensorFloatValues( tensor, shape ) ); } @@ -448,7 +482,7 @@ void OnnxParser::transferValues( String oldName, String newName ) { _constantIntTensors.insert( newName, _constantIntTensors[oldName] ); } - else if ( _constantFloatTensors.exists( oldName )) + else if ( _constantFloatTensors.exists( oldName ) ) { _constantFloatTensors.insert( newName, _constantFloatTensors[oldName] ); } @@ -462,11 +496,11 @@ void OnnxParser::transferValues( String oldName, String newName ) * Private methods * *******************/ -void OnnxParser::validateUserInputNames( Set& inputNames ) +void OnnxParser::validateUserInputNames( Set &inputNames ) { // Collate all input nodes Set allInputNames; - for ( const onnx::ValueInfoProto& node : _network.input() ) + for ( const onnx::ValueInfoProto &node : _network.input() ) { const std::string name = node.name(); if ( isConstantNode( name ) ) @@ -474,7 +508,9 @@ void OnnxParser::validateUserInputNames( Set& inputNames ) if ( allInputNames.exists( name ) ) { - String errorMessage = Stringf( "Input nodes in Onnx network must have a unique name but found duplicate name '%s'", name.c_str() ); + String errorMessage = Stringf( + "Input nodes in Onnx network must have a unique name but found duplicate name '%s'", + name.c_str() ); throw MarabouError( MarabouError::ONNX_PARSER_ERROR, errorMessage.ascii() ); } else @@ -506,7 +542,7 @@ void OnnxParser::validateUserOutputNames( String &outputName ) } String errorMessage = Stringf( "Output %s not found in graph!", outputName.ascii() ); - throw MarabouError( MarabouError::ONNX_PARSER_ERROR, errorMessage.ascii() ); + throw MarabouError( MarabouError::ONNX_PARSER_ERROR, errorMessage.ascii() ); } Set OnnxParser::readInputNames() @@ -535,7 +571,8 @@ String OnnxParser::readOutputName() if ( _network.output().size() > 1 ) { String message = "Your model has multiple outputs defined\n"; - message += "Please specify the name of the output you want to consider using the 'outputName' argument\n"; + message += "Please specify the name of the output you want to consider using the " + "'outputName' argument\n"; message += "Possible options:"; for ( auto output : _network.output() ) { @@ -566,12 +603,14 @@ void OnnxParser::initializeShapeAndConstantMaps() } // Initialise constants - for ( const onnx::TensorProto& constant : _network.initializer() ) + for ( const onnx::TensorProto &constant : _network.initializer() ) { String constantName = constant.name(); if ( isConstantNode( constantName ) ) { - String errorMessage = Stringf( "Initializers in Onnx network must have a unique name but found duplicate name '%s'", constantName.ascii() ); + String errorMessage = Stringf( "Initializers in Onnx network must have a unique name " + "but found duplicate name '%s'", + constantName.ascii() ); throw MarabouError( MarabouError::ONNX_PARSER_ERROR, errorMessage.ascii() ); } else @@ -592,7 +631,7 @@ void OnnxParser::validateAllInputsAndOutputsFound() String errorMessage = "These input variables could not be found:"; for ( String inputName : _inputNames ) { - if ( !_varMap.exists( inputName) ) + if ( !_varMap.exists( inputName ) ) { String space = " "; errorMessage += space + inputName; @@ -616,7 +655,7 @@ void OnnxParser::validateAllInputsAndOutputsFound() * @param outputName The names of the output node to end at. * @param query The query in which to store the generated constraints. */ -void OnnxParser::processGraph( Set &inputNames, String &outputName, InputQuery& query ) +void OnnxParser::processGraph( Set &inputNames, String &outputName, InputQuery &query ) { _inputNames = inputNames; _outputName = outputName; @@ -654,7 +693,7 @@ void OnnxParser::processNode( String &nodeName, bool makeEquations ) List nodes = getNodesWithOutput( nodeName ); ASSERT( nodes.size() == 1 ); - onnx::NodeProto& node = nodes.front(); + onnx::NodeProto &node = nodes.front(); // First recursively process the input nodes. // This ensures that shapes and values of a node's inputs have been computed first. @@ -736,7 +775,8 @@ Set OnnxParser::getInputsToNode( onnx::NodeProto &node ) void OnnxParser::makeMarabouEquations( onnx::NodeProto &node, bool makeEquations ) { auto nodeType = node.op_type().c_str(); - ONNX_LOG( Stringf( "Processing node '%s' of type '%s'", node.name().c_str(), nodeType ).ascii() ); + ONNX_LOG( + Stringf( "Processing node '%s' of type '%s'", node.name().c_str(), nodeType ).ascii() ); if ( strcmp( nodeType, "Constant" ) == 0 ) { @@ -814,14 +854,14 @@ void OnnxParser::makeMarabouEquations( onnx::NodeProto &node, bool makeEquations * * @param node The ONNX node */ -void OnnxParser::constant( onnx::NodeProto& node ) +void OnnxParser::constant( onnx::NodeProto &node ) { String outputNodeName = node.output()[0]; - const onnx::TensorProto& value = getTensorAttribute( node, "value" ); + const onnx::TensorProto &value = getTensorAttribute( node, "value" ); const TensorShape shape = shapeOfConstant( value ); _shapeMap[outputNodeName] = shape; - insertConstant(outputNodeName, value, shape); + insertConstant( outputNodeName, value, shape ); } /** @@ -830,7 +870,7 @@ void OnnxParser::constant( onnx::NodeProto& node ) * * @param node The ONNX node */ -void OnnxParser::identity( onnx::NodeProto& node ) +void OnnxParser::identity( onnx::NodeProto &node ) { String outputNodeName = node.output()[0]; String inputNodeName = node.input()[0]; @@ -846,9 +886,10 @@ void OnnxParser::identity( onnx::NodeProto& node ) * * @param node The ONNX node */ -void OnnxParser::cast( onnx::NodeProto& node ) +void OnnxParser::cast( onnx::NodeProto &node ) { - // See https://github.com/NeuralNetworkVerification/Marabou/blob/76b8eaf23518ca468c2cf05b742e3b4c858a64c3/maraboupy/MarabouNetworkONNX.py#L294 + // See + // https://github.com/NeuralNetworkVerification/Marabou/blob/76b8eaf23518ca468c2cf05b742e3b4c858a64c3/maraboupy/MarabouNetworkONNX.py#L294 // for reference implementation unimplementedOperationError( node ); } @@ -859,7 +900,7 @@ void OnnxParser::cast( onnx::NodeProto& node ) * * @param node The ONNX node */ -void OnnxParser::reshape( onnx::NodeProto& node ) +void OnnxParser::reshape( onnx::NodeProto &node ) { // Assume first input is array to be reshaped, second input is the new shape array String inputNodeName = node.input()[0]; @@ -884,7 +925,7 @@ void OnnxParser::reshape( onnx::NodeProto& node ) * * @param node The ONNX node */ -void OnnxParser::flatten( onnx::NodeProto& node ) +void OnnxParser::flatten( onnx::NodeProto &node ) { String outputNodeName = node.output()[0]; String inputNodeName = node.input()[0]; @@ -910,7 +951,7 @@ void OnnxParser::flatten( onnx::NodeProto& node ) // Transfer constants/variables _shapeMap[outputNodeName] = outputShape; - transferValues ( inputNodeName, outputNodeName ); + transferValues( inputNodeName, outputNodeName ); } /** @@ -919,7 +960,7 @@ void OnnxParser::flatten( onnx::NodeProto& node ) * * @param node The ONNX node */ -void OnnxParser::transpose( onnx::NodeProto& node ) +void OnnxParser::transpose( onnx::NodeProto &node ) { String inputNodeName = node.input()[0]; String outputNodeName = node.output()[0]; @@ -938,17 +979,19 @@ void OnnxParser::transpose( onnx::NodeProto& node ) if ( _varMap.exists( inputNodeName ) ) { Vector inputVars = _varMap[inputNodeName]; - _varMap[outputNodeName] = transposeTensor(inputVars, inputShape, perm); + _varMap[outputNodeName] = transposeTensor( inputVars, inputShape, perm ); } else if ( _constantIntTensors.exists( inputNodeName ) ) { Vector inputConstant = _constantIntTensors[inputNodeName]; - _constantIntTensors.insert( outputNodeName, transposeTensor(inputConstant, inputShape, perm) ); + _constantIntTensors.insert( outputNodeName, + transposeTensor( inputConstant, inputShape, perm ) ); } - else if ( _constantFloatTensors.exists( inputNodeName )) + else if ( _constantFloatTensors.exists( inputNodeName ) ) { Vector inputConstant = _constantFloatTensors[inputNodeName]; - _constantFloatTensors.insert( outputNodeName, transposeTensor(inputConstant, inputShape, perm) ); + _constantFloatTensors.insert( outputNodeName, + transposeTensor( inputConstant, inputShape, perm ) ); } else { @@ -961,7 +1004,7 @@ void OnnxParser::transpose( onnx::NodeProto& node ) * Implements https://github.com/onnx/onnx/blob/master/docs/Operators.md#batchnormalization. * @param node The ONNX node */ -void OnnxParser::batchNormEquations( onnx::NodeProto& node, bool makeEquations ) +void OnnxParser::batchNormEquations( onnx::NodeProto &node, bool makeEquations ) { String outputNodeName = node.output()[0]; String inputNodeName = node.input()[0]; @@ -969,9 +1012,9 @@ void OnnxParser::batchNormEquations( onnx::NodeProto& node, bool makeEquations ) TensorShape inputShape = _shapeMap[inputNodeName]; ASSERT( inputShape.size() >= 2 ); - unsigned int batchSize = inputShape.get(0); + unsigned int batchSize = inputShape.get( 0 ); unsigned int batchLength = tensorSize( inputShape ) / batchSize; - unsigned int numberOfChannels = inputShape.get(1); + unsigned int numberOfChannels = inputShape.get( 1 ); unsigned int channelLength = batchLength / numberOfChannels; @@ -992,20 +1035,20 @@ void OnnxParser::batchNormEquations( onnx::NodeProto& node, bool makeEquations ) Vector inputMeans = _constantFloatTensors[inputMeansName]; Vector inputVariances = _constantFloatTensors[inputVariancesName]; - ASSERT ( scales.size() == numberOfChannels ); - ASSERT ( biases.size() == numberOfChannels ); - ASSERT ( inputMeans.size() == numberOfChannels ); - ASSERT ( inputVariances.size() == numberOfChannels ); + ASSERT( scales.size() == numberOfChannels ); + ASSERT( biases.size() == numberOfChannels ); + ASSERT( inputMeans.size() == numberOfChannels ); + ASSERT( inputVariances.size() == numberOfChannels ); // Get variables Vector inputVars = _varMap[inputNodeName]; Vector outputVars = makeNodeVariables( outputNodeName, false ); - ASSERT ( inputVars.size() == tensorSize(inputShape) ); - ASSERT ( outputVars.size() == tensorSize(outputShape) ); + ASSERT( inputVars.size() == tensorSize( inputShape ) ); + ASSERT( outputVars.size() == tensorSize( outputShape ) ); for ( unsigned int i = 0; i < inputVars.size(); i++ ) { - unsigned int channel = (i % batchLength) / channelLength; + unsigned int channel = ( i % batchLength ) / channelLength; double scale = scales[channel]; double bias = biases[channel]; double inputMean = inputMeans[channel]; @@ -1026,7 +1069,7 @@ void OnnxParser::batchNormEquations( onnx::NodeProto& node, bool makeEquations ) * @param node ONNX node representing the MaxPool operation * @param makeEquations True if we need to create new variables and add new Relus */ -void OnnxParser::maxPoolEquations( onnx::NodeProto& node, [[maybe_unused]] bool makeEquations ) +void OnnxParser::maxPoolEquations( onnx::NodeProto &node, [[maybe_unused]] bool makeEquations ) { String inputNodeName = node.input()[0]; String outputNodeName = node.output()[0]; @@ -1035,8 +1078,11 @@ void OnnxParser::maxPoolEquations( onnx::NodeProto& node, [[maybe_unused]] bool TensorShape inputShape = _shapeMap[inputNodeName]; if ( inputShape.size() != 4 ) { - String errorMessage = Stringf( "Currently the Onnx '%s' operation with inputs of dimensions not equal to '%d'.", node.op_type().c_str(), inputShape.size() ) ; - throw MarabouError( MarabouError::ONNX_PARSER_ERROR, errorMessage.ascii() ) ; + String errorMessage = Stringf( + "Currently the Onnx '%s' operation with inputs of dimensions not equal to '%d'.", + node.op_type().c_str(), + inputShape.size() ); + throw MarabouError( MarabouError::ONNX_PARSER_ERROR, errorMessage.ascii() ); } int widthIndex = inputShape.size() - 2; int heightIndex = inputShape.size() - 1; @@ -1053,11 +1099,12 @@ void OnnxParser::maxPoolEquations( onnx::NodeProto& node, [[maybe_unused]] bool // Get ceil_mode int defaultCeilMode = 0; - int ceilMode = getIntAttribute(node, "ceil_mode", defaultCeilMode); + int ceilMode = getIntAttribute( node, "ceil_mode", defaultCeilMode ); // Get dilations - Vector defaultDilations = {1,1}; - Vector dilations = getNonNegativeIntsAttribute( node, "dilations", defaultDilations ); + Vector defaultDilations = { 1, 1 }; + Vector dilations = + getNonNegativeIntsAttribute( node, "dilations", defaultDilations ); for ( auto d : dilations ) { if ( d != 1 ) @@ -1068,15 +1115,19 @@ void OnnxParser::maxPoolEquations( onnx::NodeProto& node, [[maybe_unused]] bool // Get the kernel shape (required) TensorShape defaultKernelShape = { 1, 1 }; - TensorShape kernelShape = getNonNegativeIntsAttribute(node, "kernel_shape", defaultKernelShape); + TensorShape kernelShape = + getNonNegativeIntsAttribute( node, "kernel_shape", defaultKernelShape ); // Get the pads Vector defaultPads = { 0, 0, 0, 0 }; - Vector pads = getNonNegativeIntsAttribute(node, "pads", defaultPads); + Vector pads = getNonNegativeIntsAttribute( node, "pads", defaultPads ); if ( pads.size() == 0 ) { - String errorMessage = Stringf( "Unexpected padding length '%d' for the Onnx '%s' operation.", node.op_type().c_str(), pads.size() ) ; - throw MarabouError( MarabouError::ONNX_PARSER_ERROR, errorMessage.ascii() ) ; + String errorMessage = + Stringf( "Unexpected padding length '%d' for the Onnx '%s' operation.", + node.op_type().c_str(), + pads.size() ); + throw MarabouError( MarabouError::ONNX_PARSER_ERROR, errorMessage.ascii() ); } int padWidth = pads[0] + pads[1]; int padHeight = pads[2] + pads[3]; @@ -1084,30 +1135,36 @@ void OnnxParser::maxPoolEquations( onnx::NodeProto& node, [[maybe_unused]] bool // Get storage order int defaultStorageOrder = 0; int storageOrder = getIntAttribute( node, "storage_order", defaultStorageOrder ); - if( storageOrder != defaultStorageOrder ) + if ( storageOrder != defaultStorageOrder ) { unimplementedAttributeError( node, "storage_order" ); } // Get strides Vector defaultStrides = { 1, 1 }; - Vector strides = getNonNegativeIntsAttribute(node, "strides", defaultStrides); + Vector strides = getNonNegativeIntsAttribute( node, "strides", defaultStrides ); // Calculate the outputs shape TensorShape outputShape = Vector( inputShape ); - float unroundedOutputWidth = (((float) (inputWidth + padWidth - ((kernelShape[0] - 1) * dilations[0] + 1))) / ((float) strides[0])) + 1; - float unroundedOutputHeight = (((float) (inputHeight + padHeight - ((kernelShape[1] - 1) * dilations[1] + 1))) / ((float) strides[1])) + 1; + float unroundedOutputWidth = + ( ( (float)( inputWidth + padWidth - ( ( kernelShape[0] - 1 ) * dilations[0] + 1 ) ) ) / + ( (float)strides[0] ) ) + + 1; + float unroundedOutputHeight = + ( ( (float)( inputHeight + padHeight - ( ( kernelShape[1] - 1 ) * dilations[1] + 1 ) ) ) / + ( (float)strides[1] ) ) + + 1; if ( ceilMode == 0 ) { - outputShape[widthIndex] = (int) std::floor(unroundedOutputWidth); - outputShape[heightIndex] = (int) std::floor(unroundedOutputHeight); + outputShape[widthIndex] = (int)std::floor( unroundedOutputWidth ); + outputShape[heightIndex] = (int)std::floor( unroundedOutputHeight ); } else { - outputShape[widthIndex] = (int) std::ceil(unroundedOutputWidth); - outputShape[heightIndex] = (int) std::ceil(unroundedOutputHeight); + outputShape[widthIndex] = (int)std::ceil( unroundedOutputWidth ); + outputShape[heightIndex] = (int)std::ceil( unroundedOutputHeight ); } _shapeMap[outputNodeName] = outputShape; @@ -1117,31 +1174,32 @@ void OnnxParser::maxPoolEquations( onnx::NodeProto& node, [[maybe_unused]] bool // Make equations Vector inputVars = _varMap[inputNodeName]; Vector outputVars = makeNodeVariables( outputNodeName, false ); - for (TensorIndex i = 0; i < outputShape[widthIndex]; i++) + for ( TensorIndex i = 0; i < outputShape[widthIndex]; i++ ) { - for (TensorIndex j = 0; j < outputShape[heightIndex]; j++) + for ( TensorIndex j = 0; j < outputShape[heightIndex]; j++ ) { - TensorIndex diStart = strides[0]*i; - TensorIndex diEnd = std::min(diStart + kernelShape[0], inputWidth); - TensorIndex djStart = strides[1]*j; - TensorIndex djEnd = std::min(djStart + kernelShape[1], inputHeight); + TensorIndex diStart = strides[0] * i; + TensorIndex diEnd = std::min( diStart + kernelShape[0], inputWidth ); + TensorIndex djStart = strides[1] * j; + TensorIndex djEnd = std::min( djStart + kernelShape[1], inputHeight ); - for (TensorIndex k = 0; k < outputShape[1]; k++) + for ( TensorIndex k = 0; k < outputShape[1]; k++ ) { - TensorIndices outputVarIndices = {0, k, i, j}; - Variable outputVar = tensorLookup(outputVars, outputShape, outputVarIndices); + TensorIndices outputVarIndices = { 0, k, i, j }; + Variable outputVar = tensorLookup( outputVars, outputShape, outputVarIndices ); Set maxInputVars = Set(); - for (TensorIndex di = diStart; di < diEnd; di++) + for ( TensorIndex di = diStart; di < diEnd; di++ ) { - for (TensorIndex dj = djStart; dj < djEnd; dj++) + for ( TensorIndex dj = djStart; dj < djEnd; dj++ ) { TensorIndices maxInputVarIndices = { 0, k, di, dj }; - Variable maxInputVar = tensorLookup(inputVars, inputShape, maxInputVarIndices); - maxInputVars.insert(maxInputVar); + Variable maxInputVar = + tensorLookup( inputVars, inputShape, maxInputVarIndices ); + maxInputVars.insert( maxInputVar ); } } - addMaxConstraint(outputVar, maxInputVars); + addMaxConstraint( outputVar, maxInputVars ); } } } @@ -1155,7 +1213,7 @@ void OnnxParser::maxPoolEquations( onnx::NodeProto& node, [[maybe_unused]] bool * @param node ONNX node representing the operation * @param makeEquations True if we need to create new variables */ -void OnnxParser::convEquations( onnx::NodeProto& node, [[maybe_unused]] bool makeEquations ) +void OnnxParser::convEquations( onnx::NodeProto &node, [[maybe_unused]] bool makeEquations ) { String outputNodeName = node.output()[0]; @@ -1176,22 +1234,22 @@ void OnnxParser::convEquations( onnx::NodeProto& node, [[maybe_unused]] bool mak unsigned int filterHeight = filterShape[3]; // The number of channels should match between input variable and filters - ASSERT ( inputChannels == filterChannels ); + ASSERT( inputChannels == filterChannels ); // Extract convolution stride information - Vector defaultStrides = {1, 1}; - Vector strides = getNonNegativeIntsAttribute(node, "strides", defaultStrides); + Vector defaultStrides = { 1, 1 }; + Vector strides = getNonNegativeIntsAttribute( node, "strides", defaultStrides ); unsigned int strideWidth = strides[0]; unsigned int strideHeight = strides[1]; // Extract the padding information String defaultAutoPad = "NOTSET"; - String autoPad = getStringAttribute( node, "auto_pad" ,defaultAutoPad ); + String autoPad = getStringAttribute( node, "auto_pad", defaultAutoPad ); unsigned int padLeft, padBottom, padRight, padTop; if ( autoPad == "NOTSET" ) { - Vector defaultPads = {0, 0, 0, 0}; - Vector pads = getNonNegativeIntsAttribute(node, "pads", defaultPads); + Vector defaultPads = { 0, 0, 0, 0 }; + Vector pads = getNonNegativeIntsAttribute( node, "pads", defaultPads ); padLeft = pads[0]; padBottom = pads[1]; padRight = pads[2]; @@ -1212,18 +1270,23 @@ void OnnxParser::convEquations( onnx::NodeProto& node, [[maybe_unused]] bool mak { bool padFrontPreferentially = autoPad == "SAME_LOWER"; - Padding horizontalPadding = calculatePaddingNeeded( inputWidth, filterWidth, strideWidth, padFrontPreferentially ); + Padding horizontalPadding = + calculatePaddingNeeded( inputWidth, filterWidth, strideWidth, padFrontPreferentially ); padLeft = horizontalPadding.padFront; padRight = horizontalPadding.padBack; - Padding verticalPadding = calculatePaddingNeeded( inputHeight, filterHeight, strideHeight, padFrontPreferentially ); + Padding verticalPadding = calculatePaddingNeeded( + inputHeight, filterHeight, strideHeight, padFrontPreferentially ); padBottom = verticalPadding.padFront; padTop = verticalPadding.padBack; } else { - String errorMessage = Stringf( "Onnx '%s' operation has an unsupported value '%s' for attribute 'auto_pad'.", node.op_type().c_str(), autoPad.ascii() ) ; - throw MarabouError( MarabouError::ONNX_PARSER_ERROR, errorMessage.ascii() ) ; + String errorMessage = + Stringf( "Onnx '%s' operation has an unsupported value '%s' for attribute 'auto_pad'.", + node.op_type().c_str(), + autoPad.ascii() ); + throw MarabouError( MarabouError::ONNX_PARSER_ERROR, errorMessage.ascii() ); } // Extract the group information (not supported/used) @@ -1235,8 +1298,9 @@ void OnnxParser::convEquations( onnx::NodeProto& node, [[maybe_unused]] bool mak } // Extract the dilations information (not supported/used) - Vector defaultDilations = {1,1}; - Vector dilations = getNonNegativeIntsAttribute( node, "dilations", defaultDilations ); + Vector defaultDilations = { 1, 1 }; + Vector dilations = + getNonNegativeIntsAttribute( node, "dilations", defaultDilations ); for ( auto d : dilations ) { if ( d != 1 ) @@ -1246,13 +1310,13 @@ void OnnxParser::convEquations( onnx::NodeProto& node, [[maybe_unused]] bool mak } // Compute output shape - unsigned int outWidth = (inputWidth - filterWidth + padLeft + padRight) / strideWidth + 1; - unsigned int outHeight = (inputHeight - filterHeight + padBottom + padTop) / strideHeight + 1; + unsigned int outWidth = ( inputWidth - filterWidth + padLeft + padRight ) / strideWidth + 1; + unsigned int outHeight = ( inputHeight - filterHeight + padBottom + padTop ) / strideHeight + 1; unsigned int outChannels = numberOfFilters; - TensorShape outputShape = {inputShape[0], outChannels, outWidth, outHeight}; + TensorShape outputShape = { inputShape[0], outChannels, outWidth, outHeight }; _shapeMap[outputNodeName] = outputShape; - if (!makeEquations) + if ( !makeEquations ) return; // Generate equations @@ -1273,7 +1337,7 @@ void OnnxParser::convEquations( onnx::NodeProto& node, [[maybe_unused]] bool mak { for ( unsigned int i = 0; i < numberOfFilters; i++ ) { - biases.append(0); + biases.append( 0 ); } } @@ -1282,7 +1346,8 @@ void OnnxParser::convEquations( onnx::NodeProto& node, [[maybe_unused]] bool mak { for ( TensorIndex j = 0; j < outHeight; j++ ) { - for ( TensorIndex k = 0; k < outChannels; k++ ) // Out_channel corresponds to filter number + for ( TensorIndex k = 0; k < outChannels; k++ ) // Out_channel corresponds to filter + // number { Equation e = Equation(); @@ -1294,14 +1359,16 @@ void OnnxParser::convEquations( onnx::NodeProto& node, [[maybe_unused]] bool mak { for ( TensorIndex dk = 0; dk < filterChannels; dk++ ) { - TensorIndex wIndex = strideWidth*i + di - padLeft; - TensorIndex hIndex = strideHeight*j + dj - padBottom; - // No need for checking greater than 0 because unsigned ints wrap around. + TensorIndex wIndex = strideWidth * i + di - padLeft; + TensorIndex hIndex = strideHeight * j + dj - padBottom; + // No need for checking greater than 0 because unsigned ints wrap + // around. if ( hIndex < inputHeight && wIndex < inputWidth ) { - TensorIndices inputVarIndices = {0, dk, wIndex, hIndex}; - Variable inputVar = tensorLookup( inputVars, inputShape, inputVarIndices ); - TensorIndices weightIndices = {k, dk, di, dj}; + TensorIndices inputVarIndices = { 0, dk, wIndex, hIndex }; + Variable inputVar = + tensorLookup( inputVars, inputShape, inputVarIndices ); + TensorIndices weightIndices = { k, dk, di, dj }; double weight = tensorLookup( filter, filterShape, weightIndices ); e.addAddend( weight, inputVar ); } @@ -1310,7 +1377,7 @@ void OnnxParser::convEquations( onnx::NodeProto& node, [[maybe_unused]] bool mak } // Add output variable - TensorIndices outputVarIndices = {0, k, i, j}; + TensorIndices outputVarIndices = { 0, k, i, j }; Variable outputVar = tensorLookup( outputVars, outputShape, outputVarIndices ); e.addAddend( -1, outputVar ); e.setScalar( -biases[k] ); @@ -1328,7 +1395,7 @@ void OnnxParser::convEquations( onnx::NodeProto& node, [[maybe_unused]] bool mak * @param node ONNX node representing the operation * @param makeEquations True if we need to create new variables */ -void OnnxParser::gemmEquations( onnx::NodeProto& node, bool makeEquations ) +void OnnxParser::gemmEquations( onnx::NodeProto &node, bool makeEquations ) { String outputNodeName = node.output()[0]; @@ -1341,8 +1408,8 @@ void OnnxParser::gemmEquations( onnx::NodeProto& node, bool makeEquations ) TensorShape input2Shape = _shapeMap[input2NodeName]; TensorShape biasShape = _shapeMap[biasNodeName]; - ASSERT ( input1Shape.size() == 2 ); - ASSERT ( input2Shape.size() == 2 ); + ASSERT( input1Shape.size() == 2 ); + ASSERT( input2Shape.size() == 2 ); // Transpose first two inputs if needed, // and save scaling parameters alpha and beta if set. @@ -1350,14 +1417,16 @@ void OnnxParser::gemmEquations( onnx::NodeProto& node, bool makeEquations ) int transB = getIntAttribute( node, "transB", 0 ); Permutation reversePerm = { 1, 0 }; - TensorShape finalInput1Shape = transA != 0 ? transposeVector( input1Shape, reversePerm ) : input1Shape; - TensorShape finalInput2Shape = transB != 0 ? transposeVector( input2Shape, reversePerm ) : input2Shape; + TensorShape finalInput1Shape = + transA != 0 ? transposeVector( input1Shape, reversePerm ) : input1Shape; + TensorShape finalInput2Shape = + transB != 0 ? transposeVector( input2Shape, reversePerm ) : input2Shape; ASSERT( finalInput1Shape[1] == finalInput2Shape[0] ); - TensorShape outputShape = {finalInput1Shape[0], finalInput2Shape[1]}; + TensorShape outputShape = { finalInput1Shape[0], finalInput2Shape[1] }; _shapeMap[outputNodeName] = outputShape; - if( !makeEquations) + if ( !makeEquations ) return; double alpha = getFloatAttribute( node, "alpha", 1.0 ); @@ -1389,17 +1458,17 @@ void OnnxParser::gemmEquations( onnx::NodeProto& node, bool makeEquations ) Equation e = Equation(); for ( TensorIndex k = 0; k < finalInput1Shape[1]; k++ ) { - double coefficient = alpha * tensorLookup( matrix, finalInput2Shape, {k, j} ); - Variable inputVariable = tensorLookup( inputVariables, finalInput1Shape, {i, k} ); - e.addAddend(coefficient, inputVariable); + double coefficient = alpha * tensorLookup( matrix, finalInput2Shape, { k, j } ); + Variable inputVariable = tensorLookup( inputVariables, finalInput1Shape, { i, k } ); + e.addAddend( coefficient, inputVariable ); } // Set the bias - TensorIndices biasIndices = broadcastIndex( biasShape, outputShape, {i, j}); - double bias = beta * tensorLookup( biases, biasShape, biasIndices); - e.setScalar(-bias); + TensorIndices biasIndices = broadcastIndex( biasShape, outputShape, { i, j } ); + double bias = beta * tensorLookup( biases, biasShape, biasIndices ); + e.setScalar( -bias ); // Put output variable as the last addend - Variable outputVariable = tensorLookup( outputVariables, outputShape, {i, j} ); + Variable outputVariable = tensorLookup( outputVariables, outputShape, { i, j } ); e.addAddend( -1, outputVariable ); addEquation( e ); } @@ -1413,7 +1482,7 @@ void OnnxParser::gemmEquations( onnx::NodeProto& node, bool makeEquations ) * @param node ONNX node representing the Relu operation * @param makeEquations True if we need to create new variables and add new Relus */ -void OnnxParser::reluEquations( onnx::NodeProto& node, bool makeEquations ) +void OnnxParser::reluEquations( onnx::NodeProto &node, bool makeEquations ) { String outputNodeName = node.output()[0]; String inputNodeName = node.input()[0]; @@ -1423,9 +1492,9 @@ void OnnxParser::reluEquations( onnx::NodeProto& node, bool makeEquations ) return; // Get variables - Vector inputVars = _varMap[inputNodeName]; + Vector inputVars = _varMap[inputNodeName]; Vector outputVars = makeNodeVariables( outputNodeName, false ); - ASSERT ( inputVars.size() == outputVars.size() ); + ASSERT( inputVars.size() == outputVars.size() ); // Generate equations for ( PackedTensorIndices i = 0; i < inputVars.size(); i++ ) @@ -1445,7 +1514,10 @@ void OnnxParser::reluEquations( onnx::NodeProto& node, bool makeEquations ) * @param node ONNX node representing the Add operation * @param makeEquations True if we need to create new variables and write Marabou equations */ -void OnnxParser::scaleAndAddEquations( onnx::NodeProto& node, bool makeEquations, double coefficient1, double coefficient2 ) +void OnnxParser::scaleAndAddEquations( onnx::NodeProto &node, + bool makeEquations, + double coefficient1, + double coefficient2 ) { String outputName = node.output()[0]; String input1Name = node.input()[0]; @@ -1469,7 +1541,8 @@ void OnnxParser::scaleAndAddEquations( onnx::NodeProto& node, bool makeEquations // No new variables are needed, we could just store the output. if ( input1IsConstant && input2IsConstant ) { - String errorMessage = "Addition of constant tensors not yet supported for command-line Onnx files"; + String errorMessage = + "Addition of constant tensors not yet supported for command-line Onnx files"; throw MarabouError( MarabouError::ONNX_PARSER_ERROR, errorMessage.ascii() ); } @@ -1480,9 +1553,11 @@ void OnnxParser::scaleAndAddEquations( onnx::NodeProto& node, bool makeEquations Vector outputVariables = makeNodeVariables( outputName, false ); Vector input1Variables = _varMap[input1Name]; Vector input2Variables = _varMap[input2Name]; - if ( input1Variables.size() != input2Variables.size() || input2Variables.size() != outputVariables.size() ) + if ( input1Variables.size() != input2Variables.size() || + input2Variables.size() != outputVariables.size() ) { - String errorMessage = "Broadcast support for addition of two non-constant nodes not yet supported for command-line ONNX files"; + String errorMessage = "Broadcast support for addition of two non-constant nodes not " + "yet supported for command-line ONNX files"; throw MarabouError( MarabouError::ONNX_PARSER_ERROR, errorMessage.ascii() ); } @@ -1516,22 +1591,27 @@ void OnnxParser::scaleAndAddEquations( onnx::NodeProto& node, bool makeEquations // Adjust equations to incorporate the constant addition unsigned int numberOfEquationsChanged = 0; unsigned int numberOfOutputVariables = tensorSize( outputShape ); - for ( PackedTensorIndices i = 0; i < numberOfOutputVariables; i++) + for ( PackedTensorIndices i = 0; i < numberOfOutputVariables; i++ ) { TensorIndices outputIndices = unpackIndex( outputShape, i ); - TensorIndices inputVariableIndices = broadcastIndex( inputVariablesShape, outputShape, outputIndices ); - Variable inputVariable = tensorLookup(inputVariables, inputVariablesShape, inputVariableIndices); + TensorIndices inputVariableIndices = + broadcastIndex( inputVariablesShape, outputShape, outputIndices ); + Variable inputVariable = + tensorLookup( inputVariables, inputVariablesShape, inputVariableIndices ); int equationIndex = findEquationWithOutputVariable( inputVariable ); if ( equationIndex != -1 ) { - TensorIndices inputConstantIndices = broadcastIndex( inputConstantsShape, outputShape, outputIndices ); - double inputConstant = tensorLookup( inputConstants, inputConstantsShape, inputConstantIndices ); + TensorIndices inputConstantIndices = + broadcastIndex( inputConstantsShape, outputShape, outputIndices ); + double inputConstant = + tensorLookup( inputConstants, inputConstantsShape, inputConstantIndices ); Equation equation = _equationList[equationIndex]; double currentVariableCoefficient = equation.getCoefficient( inputVariable ); - equation.setCoefficient( inputVariable, variableCoefficient * currentVariableCoefficient ); + equation.setCoefficient( inputVariable, + variableCoefficient * currentVariableCoefficient ); equation.setScalar( equation._scalar - constantCoefficient * inputConstant ); _equationList[equationIndex] = equation; @@ -1549,14 +1629,14 @@ void OnnxParser::scaleAndAddEquations( onnx::NodeProto& node, bool makeEquations { // Otherwise, assert no equations were changed, // and we need to create new equations - ASSERT ( numberOfEquationsChanged == 0 ); + ASSERT( numberOfEquationsChanged == 0 ); Vector outputVariables = makeNodeVariables( outputName, false ); for ( PackedTensorIndices i = 0; i < outputVariables.size(); i++ ) { Equation e = Equation(); e.addAddend( variableCoefficient, inputVariables[i] ); e.addAddend( -1, outputVariables[i] ); - e.setScalar( -constantCoefficient*inputConstants[i] ); + e.setScalar( -constantCoefficient * inputConstants[i] ); addEquation( e ); } } @@ -1585,11 +1665,11 @@ void OnnxParser::matMulEquations( onnx::NodeProto &node, bool makeEquations ) // Calculate the output shape TensorShape outputShape; - for ( unsigned int i = 0; i < input1Shape.size() - 1; i++) + for ( unsigned int i = 0; i < input1Shape.size() - 1; i++ ) { outputShape.append( input1Shape[i] ); } - for ( unsigned int i = 1; i < input2Shape.size(); i++) + for ( unsigned int i = 1; i < input2Shape.size(); i++ ) { outputShape.append( input2Shape[i] ); } @@ -1603,10 +1683,12 @@ void OnnxParser::matMulEquations( onnx::NodeProto &node, bool makeEquations ) bool input1IsConstant = isConstantNode( input1Name ); bool input2IsConstant = isConstantNode( input2Name ); - //If both inputs are constant, than the output is constant as well, and we don't need new variables or equations + // If both inputs are constant, than the output is constant as well, and we don't need new + // variables or equations if ( input1IsConstant && input2IsConstant ) { - String errorMessage = "Matrix multiplication of constant tensors not yet implemented for command-line Onnx files"; + String errorMessage = "Matrix multiplication of constant tensors not yet implemented for " + "command-line Onnx files"; throw MarabouError( MarabouError::ONNX_PARSER_ERROR, errorMessage.ascii() ); } @@ -1652,19 +1734,19 @@ void OnnxParser::matMulEquations( onnx::NodeProto &node, bool makeEquations ) Variable variable; if ( input1IsConstant ) { - constant = tensorLookup( constants, {d1, d2}, {i, k} ); - variable = tensorLookup( variables, {d2, d3}, {k, j} ); + constant = tensorLookup( constants, { d1, d2 }, { i, k } ); + variable = tensorLookup( variables, { d2, d3 }, { k, j } ); } else { - constant = tensorLookup( constants, {d2, d3}, {k, j} ); - variable = tensorLookup( variables, {d1, d2}, {i, k} ); + constant = tensorLookup( constants, { d2, d3 }, { k, j } ); + variable = tensorLookup( variables, { d1, d2 }, { i, k } ); } e.addAddend( constant, variable ); } // Put output variable as the last addend - Variable outputVariable = tensorLookup( outputVariables, outputShape, {i , j} ); + Variable outputVariable = tensorLookup( outputVariables, outputShape, { i, j } ); e.addAddend( -1, outputVariable ); e.setScalar( 0.0 ); addEquation( e ); @@ -1679,13 +1761,13 @@ void OnnxParser::matMulEquations( onnx::NodeProto &node, bool makeEquations ) Variable variable; if ( input1IsConstant ) { - constant = tensorLookup( constants, {d1, d2}, {i, k} ); + constant = tensorLookup( constants, { d1, d2 }, { i, k } ); variable = variables[k]; } else { constant = constants[k]; - variable = tensorLookup( variables, {d1, d2}, {i, k} ); + variable = tensorLookup( variables, { d1, d2 }, { i, k } ); } e.addAddend( constant, variable ); } @@ -1712,11 +1794,11 @@ void OnnxParser::sigmoidEquations( onnx::NodeProto &node, bool makeEquations ) String inputNodeName = node.input()[0]; _shapeMap[outputNodeName] = _shapeMap[inputNodeName]; - if( !makeEquations ) + if ( !makeEquations ) return; // Get variables - Vector inputVars = _varMap[inputNodeName]; + Vector inputVars = _varMap[inputNodeName]; Vector outputVars = makeNodeVariables( outputNodeName, false ); ASSERT( inputVars.size() == outputVars.size() ); @@ -1749,12 +1831,12 @@ void OnnxParser::tanhEquations( onnx::NodeProto &node, bool makeEquations ) return; // Get variables - Vector inputVars = _varMap[inputName]; + Vector inputVars = _varMap[inputName]; Vector outputVars = makeNodeVariables( outputName, false ); ASSERT( inputVars.size() == outputVars.size() ); // Generate equations - for( uint i = 0; i < outputVars.size(); i++ ) + for ( uint i = 0; i < outputVars.size(); i++ ) { // tanh(x) = 2 * sigmoid(2x) - 1 Variable inputVar = inputVars[i]; @@ -1768,7 +1850,7 @@ void OnnxParser::tanhEquations( onnx::NodeProto &node, bool makeEquations ) e1.setScalar( 0.0 ); addEquation( e1 ); - addSigmoid(firstAffine, sigmoidOutput); + addSigmoid( firstAffine, sigmoidOutput ); Equation e2; e2.addAddend( 2.0, sigmoidOutput ); diff --git a/src/input_parsers/OnnxParser.h b/src/input_parsers/OnnxParser.h index 22e08119c1..34fd367d5a 100644 --- a/src/input_parsers/OnnxParser.h +++ b/src/input_parsers/OnnxParser.h @@ -15,30 +15,30 @@ #ifndef __OnnxParser_h__ #define __OnnxParser_h__ -#include "onnx.proto3.pb.h" -#include "Map.h" +#include "InputQuery.h" #include "List.h" -#include "Vector.h" -#include "Set.h" #include "MString.h" -#include "InputQuery.h" +#include "Map.h" #include "NetworkParser.h" +#include "Set.h" #include "TensorUtils.h" +#include "Vector.h" +#include "onnx.proto3.pb.h" -#define ONNX_LOG(x, ...) LOG(GlobalConfiguration::ONNX_PARSER_LOGGING, "OnnxParser: %s\n", x) +#define ONNX_LOG( x, ... ) LOG( GlobalConfiguration::ONNX_PARSER_LOGGING, "OnnxParser: %s\n", x ) class OnnxParser : public NetworkParser { public: - OnnxParser( const String& path ); + OnnxParser( const String &path ); void generateQuery( InputQuery &inputQuery ); - void generatePartialQuery( InputQuery &inputQuery , Set &inputNames, String &outputName ); + void + generatePartialQuery( InputQuery &inputQuery, Set &inputNames, String &outputName ); private: - // Settings // onnx::GraphProto _network; @@ -56,40 +56,43 @@ class OnnxParser : public NetworkParser // Methods // - void readNetwork( const String& path ); + void readNetwork( const String &path ); Set readInputNames(); String readOutputName(); void initializeShapeAndConstantMaps(); - void validateUserInputNames( Set& inputNames) ; - void validateUserOutputNames( String& outputName ); + void validateUserInputNames( Set &inputNames ); + void validateUserOutputNames( String &outputName ); void validateAllInputsAndOutputsFound(); - void processGraph( Set& inputNames, String& outputName , InputQuery &inputQuery ); - void processNode( String& nodeName, bool makeEquations ); - void makeMarabouEquations ( onnx::NodeProto& node, bool makeEquations ); - Set getInputsToNode( onnx::NodeProto& node ); - List getNodesWithOutput( String& nodeName ); - Vector makeNodeVariables ( String& nodeName, bool isInput ); + void processGraph( Set &inputNames, String &outputName, InputQuery &inputQuery ); + void processNode( String &nodeName, bool makeEquations ); + void makeMarabouEquations( onnx::NodeProto &node, bool makeEquations ); + Set getInputsToNode( onnx::NodeProto &node ); + List getNodesWithOutput( String &nodeName ); + Vector makeNodeVariables( String &nodeName, bool isInput ); bool isConstantNode( String name ); - void transferValues ( String oldName, String newName ); - void insertConstant( String name, const onnx::TensorProto& tensor, TensorShape shape ); - - void constant( onnx::NodeProto& node ); - void identity( onnx::NodeProto& node ); - void cast( onnx::NodeProto& node ); - void reshape( onnx::NodeProto& node ); - void flatten( onnx::NodeProto& node ); - void transpose( onnx::NodeProto& node ); - void batchNormEquations( onnx::NodeProto& node, bool makeEquations ); - void maxPoolEquations( onnx::NodeProto& node, bool makeEquations ); - void convEquations( onnx::NodeProto& node, bool makeEquations ); - void gemmEquations( onnx::NodeProto& node, bool makeEquations ); - void scaleAndAddEquations( onnx::NodeProto& node, bool makeEquations, double coefficient1, double coefficient2 ); - void matMulEquations( onnx::NodeProto& node, bool makeEquations ); - void reluEquations( onnx::NodeProto& node, bool makeEquations ); - void sigmoidEquations( onnx::NodeProto& node, bool makeEquations ); - void tanhEquations( onnx::NodeProto& node, bool makeEquations ); + void transferValues( String oldName, String newName ); + void insertConstant( String name, const onnx::TensorProto &tensor, TensorShape shape ); + + void constant( onnx::NodeProto &node ); + void identity( onnx::NodeProto &node ); + void cast( onnx::NodeProto &node ); + void reshape( onnx::NodeProto &node ); + void flatten( onnx::NodeProto &node ); + void transpose( onnx::NodeProto &node ); + void batchNormEquations( onnx::NodeProto &node, bool makeEquations ); + void maxPoolEquations( onnx::NodeProto &node, bool makeEquations ); + void convEquations( onnx::NodeProto &node, bool makeEquations ); + void gemmEquations( onnx::NodeProto &node, bool makeEquations ); + void scaleAndAddEquations( onnx::NodeProto &node, + bool makeEquations, + double coefficient1, + double coefficient2 ); + void matMulEquations( onnx::NodeProto &node, bool makeEquations ); + void reluEquations( onnx::NodeProto &node, bool makeEquations ); + void sigmoidEquations( onnx::NodeProto &node, bool makeEquations ); + void tanhEquations( onnx::NodeProto &node, bool makeEquations ); }; #endif // __OnnxParser_h__ diff --git a/src/input_parsers/PropertyParser.cpp b/src/input_parsers/PropertyParser.cpp index aacf1d0834..01403141e8 100644 --- a/src/input_parsers/PropertyParser.cpp +++ b/src/input_parsers/PropertyParser.cpp @@ -13,11 +13,12 @@ **/ +#include "PropertyParser.h" + #include "Debug.h" #include "File.h" #include "InputParserError.h" #include "MStringf.h" -#include "PropertyParser.h" static double extractScalar( const String &token ) { @@ -25,8 +26,8 @@ static double extractScalar( const String &token ) double value = std::stod( token.ascii(), &end ); if ( end != token.length() ) { - throw InputParserError( InputParserError::UNEXPECTED_INPUT, Stringf( "%s not a scalar", - token.ascii() ).ascii() ); + throw InputParserError( InputParserError::UNEXPECTED_INPUT, + Stringf( "%s not a scalar", token.ascii() ).ascii() ); } return value; } @@ -35,7 +36,8 @@ void PropertyParser::parse( const String &propertyFilePath, InputQuery &inputQue { if ( !File::exists( propertyFilePath ) ) { - printf( "Error: the specified property file (%s) doesn't exist!\n", propertyFilePath.ascii() ); + printf( "Error: the specified property file (%s) doesn't exist!\n", + propertyFilePath.ascii() ); throw InputParserError( InputParserError::FILE_DOESNT_EXIST, propertyFilePath.ascii() ); } @@ -47,7 +49,7 @@ void PropertyParser::parse( const String &propertyFilePath, InputQuery &inputQue while ( true ) { String line = propertyFile.readLine().trim(); - if ( line.substring(0,2) != "//" ) + if ( line.substring( 0, 2 ) != "//" ) { processSingleLine( line, inputQuery ); } @@ -80,7 +82,7 @@ void PropertyParser::processSingleLine( const String &line, InputQuery &inputQue if ( tokens.size() == 3 ) { // Special case: add as a bound - String token = (*it).trim(); + String token = ( *it ).trim(); bool inputVariable = token.contains( "x" ); bool outputVariable = token.contains( "y" ); @@ -88,9 +90,12 @@ void PropertyParser::processSingleLine( const String &line, InputQuery &inputQue // Make sure that we have identified precisely one kind of variable unsigned variableKindSanity = 0; - if ( inputVariable ) ++variableKindSanity; - if ( outputVariable ) ++variableKindSanity; - if ( hiddenVariable ) ++variableKindSanity; + if ( inputVariable ) + ++variableKindSanity; + if ( outputVariable ) + ++variableKindSanity; + if ( hiddenVariable ) + ++variableKindSanity; if ( variableKindSanity != 1 ) throw InputParserError( InputParserError::UNEXPECTED_INPUT, token.ascii() ); @@ -181,7 +186,7 @@ void PropertyParser::processSingleLine( const String &line, InputQuery &inputQue while ( it != tokens.rend() ) { - String token = (*it).trim(); + String token = ( *it ).trim(); bool inputVariable = token.contains( "x" ); bool outputVariable = token.contains( "y" ); diff --git a/src/input_parsers/TensorUtils.cpp b/src/input_parsers/TensorUtils.cpp index b5be4e8b7b..81402fe1b0 100644 --- a/src/input_parsers/TensorUtils.cpp +++ b/src/input_parsers/TensorUtils.cpp @@ -10,14 +10,15 @@ ** directory for licensing information.\endverbatim ** ** Utilities for working with tensors while parsing networks. -**/ + **/ #include "TensorUtils.h" + #include TensorIndices unpackIndex( TensorShape shape, PackedTensorIndices packedIndex ) { - ASSERT ( packedIndex < tensorSize( shape ) ); + ASSERT( packedIndex < tensorSize( shape ) ); TensorIndices indices; int currentIndex = packedIndex; @@ -25,13 +26,13 @@ TensorIndices unpackIndex( TensorShape shape, PackedTensorIndices packedIndex ) { int dimension = shape[i]; int index = currentIndex % dimension; - currentIndex = (currentIndex - index) / dimension; + currentIndex = ( currentIndex - index ) / dimension; indices.insertHead( index ); } return indices; } -PackedTensorIndices packIndex ( TensorShape shape, TensorIndices indices ) +PackedTensorIndices packIndex( TensorShape shape, TensorIndices indices ) { ASSERT( shape.size() == indices.size() ); @@ -39,11 +40,11 @@ PackedTensorIndices packIndex ( TensorShape shape, TensorIndices indices ) unsigned int index = 0; for ( unsigned int i = shape.size(); i-- > 0; ) { - ASSERT ( indices[i] <= shape[i] ); - index += sizeSoFar*indices[i]; + ASSERT( indices[i] <= shape[i] ); + index += sizeSoFar * indices[i]; sizeSoFar *= shape[i]; } - ASSERT( tensorSize ( shape ) == sizeSoFar ); + ASSERT( tensorSize( shape ) == sizeSoFar ); return index; } @@ -65,10 +66,10 @@ TensorShape getMultidirectionalBroadcastShape( TensorShape shape1, TensorShape s auto it2 = shape2.rbegin(); while ( it1 != shape1.rend() || it2 != shape2.rend() ) { - int d1 = it1 == shape1.rend() ? 1 : *(it1++); - int d2 = it2 == shape2.rend() ? 1 : *(it2++); + int d1 = it1 == shape1.rend() ? 1 : *( it1++ ); + int d2 = it2 == shape2.rend() ? 1 : *( it2++ ); - ASSERT ( d1 == d2 || d2 == 1 || d1 == 1 ); + ASSERT( d1 == d2 || d2 == 1 || d1 == 1 ); int d; if ( d1 == d2 || d2 == 1 ) @@ -89,9 +90,11 @@ TensorShape getMultidirectionalBroadcastShape( TensorShape shape1, TensorShape s * @brief Broadcasts the provided indices into those into the current tensor shape * from indices in the desired broadcast shape. */ -TensorIndices broadcastIndex ( TensorShape currentShape, TensorShape broadcastShape, TensorIndices broadcastIndices ) +TensorIndices broadcastIndex( TensorShape currentShape, + TensorShape broadcastShape, + TensorIndices broadcastIndices ) { - ASSERT ( broadcastIndices.size() == broadcastShape.size() ); + ASSERT( broadcastIndices.size() == broadcastShape.size() ); int dimOffset = broadcastShape.size() - currentShape.size(); TensorIndices result; @@ -100,7 +103,7 @@ TensorIndices broadcastIndex ( TensorShape currentShape, TensorShape broadcastSh int cd = currentShape[i - dimOffset]; int bd = broadcastShape[i]; - ASSERT ( cd == 1 || cd == bd ); + ASSERT( cd == 1 || cd == bd ); if ( cd == bd ) { @@ -108,18 +111,20 @@ TensorIndices broadcastIndex ( TensorShape currentShape, TensorShape broadcastSh } else { - result.append ( 0 ); + result.append( 0 ); } } return result; } -Padding::Padding ( int padFront, int padBack ) +Padding::Padding( int padFront, int padBack ) : padFront( padFront ) , padBack( padBack ) -{} +{ +} -Padding calculatePaddingNeeded( int inputSize, int filterSize, int stride, bool padFrontPreferentially ) +Padding +calculatePaddingNeeded( int inputSize, int filterSize, int stride, bool padFrontPreferentially ) { int overrun = inputSize % stride; int paddingNeeded; @@ -135,11 +140,11 @@ Padding calculatePaddingNeeded( int inputSize, int filterSize, int stride, bool const int halfPaddingRem = paddingNeeded % 2; if ( padFrontPreferentially ) { - return Padding ( halfPaddingQuot + halfPaddingRem, halfPaddingQuot ); + return Padding( halfPaddingQuot + halfPaddingRem, halfPaddingQuot ); } else { - return Padding ( halfPaddingQuot, halfPaddingQuot + halfPaddingRem ); + return Padding( halfPaddingQuot, halfPaddingQuot + halfPaddingRem ); } } @@ -148,7 +153,7 @@ Permutation reversePermutation( unsigned int size ) Permutation result; for ( unsigned int i = size - 1; i-- > 0; ) { - result.append(i); + result.append( i ); } return result; } diff --git a/src/input_parsers/TensorUtils.h b/src/input_parsers/TensorUtils.h index 36d8e1fdc6..b28badf4da 100644 --- a/src/input_parsers/TensorUtils.h +++ b/src/input_parsers/TensorUtils.h @@ -16,11 +16,12 @@ #define __TensorUtils_h__ #include "Debug.h" -#include "Vector.h" #include "MString.h" +#include "Vector.h" /** - * @brief Represents the dimensions of a tensor, e.g. [10,3,2] is a 3D tensor of dimensions 10 x 3 x 2. + * @brief Represents the dimensions of a tensor, e.g. [10,3,2] is a 3D tensor of dimensions 10 x 3 + * x 2. */ typedef Vector TensorShape; @@ -46,22 +47,20 @@ typedef Vector Permutation; TensorIndices unpackIndex( TensorShape shape, PackedTensorIndices packedIndex ); -PackedTensorIndices packIndex ( TensorShape shape, TensorIndices indices ); +PackedTensorIndices packIndex( TensorShape shape, TensorIndices indices ); -template -T tensorLookup( Vector tensor, TensorShape shape, TensorIndices indices) +template T tensorLookup( Vector tensor, TensorShape shape, TensorIndices indices ) { - return tensor[ packIndex( shape, indices ) ]; + return tensor[packIndex( shape, indices )]; } -template -Vector transposeVector ( Vector values, Permutation permutation ) +template Vector transposeVector( Vector values, Permutation permutation ) { Vector result; for ( unsigned int i : permutation ) { ASSERT( i < values.size() ); - result.append(values[i]); + result.append( values[i] ); } return result; } @@ -71,7 +70,7 @@ Vector transposeTensor( Vector tensor, TensorShape shape, Permutation perm { // NOTE this implementation is *very* inefficient. Eventually we might want to // switch to a similar implementation as NumPy arrays with internal strides etc. - ASSERT ( shape.size() == permutation.size() ); + ASSERT( shape.size() == permutation.size() ); TensorShape transposedShape = transposeVector( shape, permutation ); Vector result; for ( PackedTensorIndices rawOutputIndex = 0; rawOutputIndex < tensor.size(); rawOutputIndex++ ) @@ -89,19 +88,22 @@ unsigned int tensorSize( TensorShape shape ); // See https://github.com/onnx/onnx/blob/main/docs/Broadcasting.md#multidirectional-broadcasting TensorShape getMultidirectionalBroadcastShape( TensorShape shape1, TensorShape shape2 ); -TensorIndices broadcastIndex ( TensorShape currentShape, TensorShape broadcastShape, TensorIndices broadcastIndices ); +TensorIndices broadcastIndex( TensorShape currentShape, + TensorShape broadcastShape, + TensorIndices broadcastIndices ); Permutation reversePermutation( unsigned int size ); struct Padding { - public: - int padFront; - int padBack; +public: + int padFront; + int padBack; - Padding ( int padFront, int padBack ); + Padding( int padFront, int padBack ); }; -Padding calculatePaddingNeeded( int inputSize, int filterSize, int stride, bool padFrontPreferentially ); +Padding +calculatePaddingNeeded( int inputSize, int filterSize, int stride, bool padFrontPreferentially ); #endif // __TensorUtils_h__ \ No newline at end of file diff --git a/src/input_parsers/VnnLibParser.cpp b/src/input_parsers/VnnLibParser.cpp index 52b3f0a733..634656af5d 100644 --- a/src/input_parsers/VnnLibParser.cpp +++ b/src/input_parsers/VnnLibParser.cpp @@ -13,12 +13,14 @@ **/ -#include +#include "VnnLibParser.h" + +#include "DisjunctionConstraint.h" #include "Equation.h" #include "File.h" #include "InputParserError.h" -#include "VnnLibParser.h" -#include "DisjunctionConstraint.h" + +#include static double extractScalar( const String &token ) { @@ -26,8 +28,8 @@ static double extractScalar( const String &token ) double value = std::stod( token.ascii(), &end ); if ( end != token.length() ) { - throw InputParserError( InputParserError::UNEXPECTED_INPUT, Stringf( "%s not a scalar", - token.ascii() ).ascii() ); + throw InputParserError( InputParserError::UNEXPECTED_INPUT, + Stringf( "%s not a scalar", token.ascii() ).ascii() ); } return value; } @@ -36,8 +38,8 @@ static String readVnnlibFile( const String &vnnlibFilePath ) { if ( !File::exists( vnnlibFilePath ) ) { - std::cout << "Error: the specified property file " - << vnnlibFilePath.ascii() << " doesn't exist!" << std::endl; + std::cout << "Error: the specified property file " << vnnlibFilePath.ascii() + << " doesn't exist!" << std::endl; throw InputParserError( InputParserError::FILE_DOESNT_EXIST, vnnlibFilePath.ascii() ); } @@ -79,15 +81,13 @@ void VnnLibParser::parseVnnlib( const String &vnnlibContent, InputQuery &inputQu { std::regex re( R"(\(|\)|[\w\-\\.]+|<=|>=|\+|-|\*)" ); - auto tokens_begin = std::cregex_token_iterator( vnnlibContent.ascii(), - vnnlibContent.ascii() - + vnnlibContent.length(), re ); + auto tokens_begin = std::cregex_token_iterator( + vnnlibContent.ascii(), vnnlibContent.ascii() + vnnlibContent.length(), re ); auto tokens_end = std::cregex_token_iterator(); Vector all_tokens; - for ( std::cregex_token_iterator it = tokens_begin; - it != tokens_end; ++it ) + for ( std::cregex_token_iterator it = tokens_begin; it != tokens_end; ++it ) { auto match = *it; auto match_str = String( match.str().c_str() ); @@ -102,7 +102,7 @@ int VnnLibParser::parseScript( const Vector &tokens, InputQuery &inputQu { int index = 0; - while ( (unsigned) index < tokens.size() ) + while ( (unsigned)index < tokens.size() ) { ASSERT( tokens[index] == "(" ) index = parseCommand( index + 1, tokens, inputQuery ); @@ -134,7 +134,9 @@ int VnnLibParser::parseCommand( int index, const Vector &tokens, InputQu return index; } -int VnnLibParser::parseDeclareConst( int index, const Vector &tokens, InputQuery &inputQuery ) +int VnnLibParser::parseDeclareConst( int index, + const Vector &tokens, + InputQuery &inputQuery ) { const String &varName = tokens[index]; const String &varType = tokens[++index]; @@ -142,7 +144,8 @@ int VnnLibParser::parseDeclareConst( int index, const Vector &tokens, In if ( varType != "Real" ) { - throw InputParserError( InputParserError::UNEXPECTED_INPUT, "Does not support variable types other than 'Real'" ); + throw InputParserError( InputParserError::UNEXPECTED_INPUT, + "Does not support variable types other than 'Real'" ); } List varTokens = varName.tokenize( "_" ); @@ -168,7 +171,8 @@ int VnnLibParser::parseDeclareConst( int index, const Vector &tokens, In { if ( varIdx >= inputQuery.getNumInputVariables() ) { - throw InputParserError( InputParserError::VARIABLE_INDEX_OUT_OF_RANGE, varName.ascii() ); + throw InputParserError( InputParserError::VARIABLE_INDEX_OUT_OF_RANGE, + varName.ascii() ); } _varMap.insert( varName, inputQuery.inputVariableByIndex( varIdx ) ); @@ -177,7 +181,8 @@ int VnnLibParser::parseDeclareConst( int index, const Vector &tokens, In { if ( varIdx >= inputQuery.getNumOutputVariables() ) { - throw InputParserError( InputParserError::VARIABLE_INDEX_OUT_OF_RANGE, varName.ascii() ); + throw InputParserError( InputParserError::VARIABLE_INDEX_OUT_OF_RANGE, + varName.ascii() ); } _varMap.insert( varName, inputQuery.outputVariableByIndex( varIdx ) ); @@ -215,8 +220,9 @@ int VnnLibParser::parseAssert( int index, const Vector &tokens, InputQue } else if ( eq._scalar < 0 ) { - throw InputParserError( InputParserError::UNEXPECTED_INPUT, - Stringf( "Illegal vnnlib constraint: 0 < %f", eq._scalar ).ascii() ); + throw InputParserError( + InputParserError::UNEXPECTED_INPUT, + Stringf( "Illegal vnnlib constraint: 0 < %f", eq._scalar ).ascii() ); } else { @@ -282,7 +288,9 @@ int VnnLibParser::parseAssert( int index, const Vector &tokens, InputQue return index; } -int VnnLibParser::parseCondition( int index, const Vector &tokens, List &equations ) +int VnnLibParser::parseCondition( int index, + const Vector &tokens, + List &equations ) { const String &op = tokens[index]; @@ -353,7 +361,9 @@ int VnnLibParser::parseTerm( int index, const Vector &tokens, Term &term return index; } -int VnnLibParser::parseComplexTerm( int index, const Vector &tokens, VnnLibParser::Term &term ) +int VnnLibParser::parseComplexTerm( int index, + const Vector &tokens, + VnnLibParser::Term &term ) { while ( tokens[index] != ")" ) { @@ -366,7 +376,8 @@ int VnnLibParser::parseComplexTerm( int index, const Vector &tokens, Vnn return index; } -double VnnLibParser::processAddConstraint( const VnnLibParser::Term &term, Equation &equation, bool isRhs ) +double +VnnLibParser::processAddConstraint( const VnnLibParser::Term &term, Equation &equation, bool isRhs ) { ASSERT( term._type == Term::TermType::ADD ) @@ -387,7 +398,9 @@ double VnnLibParser::processAddConstraint( const VnnLibParser::Term &term, Equat { if ( arg._args.size() == 2 ) { - throw InputParserError( InputParserError::UNEXPECTED_INPUT, "Using VNN-LIB operator '-' as a sub-term of '+' is allowed with only one argument" ); + throw InputParserError( InputParserError::UNEXPECTED_INPUT, + "Using VNN-LIB operator '-' as a sub-term of '+' is " + "allowed with only one argument" ); } const Term &subArg = arg._args.first(); @@ -401,25 +414,29 @@ double VnnLibParser::processAddConstraint( const VnnLibParser::Term &term, Equat } else { - throw InputParserError( InputParserError::UNEXPECTED_INPUT, "Unsupported argument for VNN-LIB operator '+'" ); + throw InputParserError( InputParserError::UNEXPECTED_INPUT, + "Unsupported argument for VNN-LIB operator '+'" ); } } else { - throw InputParserError( InputParserError::UNEXPECTED_INPUT, "Unsupported argument for VNN-LIB operator '+'" ); + throw InputParserError( InputParserError::UNEXPECTED_INPUT, + "Unsupported argument for VNN-LIB operator '+'" ); } } return scalar; } -double VnnLibParser::processSubConstraint( const VnnLibParser::Term &term, Equation &equation, bool isRhs ) +double +VnnLibParser::processSubConstraint( const VnnLibParser::Term &term, Equation &equation, bool isRhs ) { ASSERT( term._type == Term::TermType::SUB ) if ( term._args.empty() || term._args.size() > 2 ) { - throw InputParserError( InputParserError::UNEXPECTED_INPUT, "'-' VNN-LIB operation supports only one or two arguments" ); + throw InputParserError( InputParserError::UNEXPECTED_INPUT, + "'-' VNN-LIB operation supports only one or two arguments" ); } double scalar = 0; @@ -437,7 +454,8 @@ double VnnLibParser::processSubConstraint( const VnnLibParser::Term &term, Equat } else { - throw InputParserError( InputParserError::UNEXPECTED_INPUT, "Unsupported argument for VNN-LIB operator '-'" ); + throw InputParserError( InputParserError::UNEXPECTED_INPUT, + "Unsupported argument for VNN-LIB operator '-'" ); } if ( term._args.size() == 2 ) @@ -454,14 +472,16 @@ double VnnLibParser::processSubConstraint( const VnnLibParser::Term &term, Equat } else { - throw InputParserError( InputParserError::UNEXPECTED_INPUT, "Unsupported argument for VNN-LIB operator '-'" ); + throw InputParserError( InputParserError::UNEXPECTED_INPUT, + "Unsupported argument for VNN-LIB operator '-'" ); } } return scalar; } -double VnnLibParser::processMulConstraint( const VnnLibParser::Term &term, Equation &equation, bool isRhs ) +double +VnnLibParser::processMulConstraint( const VnnLibParser::Term &term, Equation &equation, bool isRhs ) { ASSERT( term._type == Term::TermType::MUL ) @@ -480,7 +500,9 @@ double VnnLibParser::processMulConstraint( const VnnLibParser::Term &term, Equat { if ( varExists ) { - throw InputParserError( InputParserError::UNEXPECTED_INPUT, "No support for using VNN-LIB operator '*' on more than one variable" ); + throw InputParserError( + InputParserError::UNEXPECTED_INPUT, + "No support for using VNN-LIB operator '*' on more than one variable" ); } varExists = true; @@ -490,7 +512,9 @@ double VnnLibParser::processMulConstraint( const VnnLibParser::Term &term, Equat { if ( arg._args.size() == 2 ) { - throw InputParserError( InputParserError::UNEXPECTED_INPUT, "Using VNN-LIB operator '-' as a sub-term of '*' is allowed with only one argument" ); + throw InputParserError( InputParserError::UNEXPECTED_INPUT, + "Using VNN-LIB operator '-' as a sub-term of '*' is " + "allowed with only one argument" ); } const Term &subArg = arg._args.first(); @@ -502,7 +526,9 @@ double VnnLibParser::processMulConstraint( const VnnLibParser::Term &term, Equat { if ( varExists ) { - throw InputParserError( InputParserError::UNEXPECTED_INPUT, "No support for using VNN-LIB operator '*' on more than one variable" ); + throw InputParserError( + InputParserError::UNEXPECTED_INPUT, + "No support for using VNN-LIB operator '*' on more than one variable" ); } varExists = true; @@ -511,12 +537,14 @@ double VnnLibParser::processMulConstraint( const VnnLibParser::Term &term, Equat } else { - throw InputParserError( InputParserError::UNEXPECTED_INPUT, "Unsupported argument for VNN-LIB operator '*'" ); + throw InputParserError( InputParserError::UNEXPECTED_INPUT, + "Unsupported argument for VNN-LIB operator '*'" ); } } else { - throw InputParserError( InputParserError::UNEXPECTED_INPUT, "Unsupported argument for VNN-LIB operator '*'" ); + throw InputParserError( InputParserError::UNEXPECTED_INPUT, + "Unsupported argument for VNN-LIB operator '*'" ); } } @@ -531,7 +559,8 @@ double VnnLibParser::processMulConstraint( const VnnLibParser::Term &term, Equat return ( -coefficient ) * scalar; } -Equation VnnLibParser::processLeConstraint( const VnnLibParser::Term &arg1, const VnnLibParser::Term &arg2 ) +Equation VnnLibParser::processLeConstraint( const VnnLibParser::Term &arg1, + const VnnLibParser::Term &arg2 ) { Equation equation( Equation::EquationType::LE ); double scalar = 0; @@ -583,5 +612,3 @@ Equation VnnLibParser::processLeConstraint( const VnnLibParser::Term &arg1, cons equation.setScalar( scalar ); return equation; } - - diff --git a/src/input_parsers/VnnLibParser.h b/src/input_parsers/VnnLibParser.h index 73b6c61663..2b53e575c8 100644 --- a/src/input_parsers/VnnLibParser.h +++ b/src/input_parsers/VnnLibParser.h @@ -17,8 +17,8 @@ #define _VnnLibParser_h_ #include "InputQuery.h" -#include "Map.h" #include "MString.h" +#include "Map.h" #include "Vector.h" class VnnLibParser @@ -30,8 +30,7 @@ class VnnLibParser class Term { public: - enum TermType - { + enum TermType { CONST, VARIABLE, ADD, @@ -62,14 +61,16 @@ class VnnLibParser int parseComplexTerm( int index, const Vector &tokens, VnnLibParser::Term &term ); - double processAddConstraint( const VnnLibParser::Term &term, Equation &equation, bool isRhs = false ); + double + processAddConstraint( const VnnLibParser::Term &term, Equation &equation, bool isRhs = false ); - double processSubConstraint( const VnnLibParser::Term &term, Equation &equation, bool isRhs = false ); + double + processSubConstraint( const VnnLibParser::Term &term, Equation &equation, bool isRhs = false ); - double processMulConstraint( const VnnLibParser::Term &term, Equation &equation, bool isRhs = false ); + double + processMulConstraint( const VnnLibParser::Term &term, Equation &equation, bool isRhs = false ); Equation processLeConstraint( const VnnLibParser::Term &arg1, const VnnLibParser::Term &arg2 ); - }; #endif //_VnnLibParser_h_ diff --git a/src/input_parsers/acas_example/main.cpp b/src/input_parsers/acas_example/main.cpp index fb788422aa..36c0362bfd 100644 --- a/src/input_parsers/acas_example/main.cpp +++ b/src/input_parsers/acas_example/main.cpp @@ -13,15 +13,15 @@ **/ -#include - #include "AcasParser.h" #include "Engine.h" #include "FloatUtils.h" #include "GlobalConfiguration.h" #include "InputQuery.h" -#include "Preprocessor.h" #include "MarabouError.h" +#include "Preprocessor.h" + +#include int main() { @@ -61,7 +61,7 @@ int main() // unsigned variable = acasParser.getOutputVariable( 0 ); // inputQuery.setLowerBound( variable, 0.5 ); - // Feed the query to the engine + // Feed the query to the engine Engine engine; bool preprocess = engine.processInputQuery( inputQuery ); diff --git a/src/input_parsers/berkeley_example/main.cpp b/src/input_parsers/berkeley_example/main.cpp index 4bb54b4121..f335ab3b3d 100644 --- a/src/input_parsers/berkeley_example/main.cpp +++ b/src/input_parsers/berkeley_example/main.cpp @@ -13,15 +13,15 @@ **/ -#include - #include "BerkeleyParser.h" #include "Engine.h" #include "FloatUtils.h" #include "GlobalConfiguration.h" #include "InputQuery.h" -#include "Preprocessor.h" #include "MarabouError.h" +#include "Preprocessor.h" + +#include int main() { diff --git a/src/input_parsers/mps_example/main.cpp b/src/input_parsers/mps_example/main.cpp index bf856773f4..decce265b3 100644 --- a/src/input_parsers/mps_example/main.cpp +++ b/src/input_parsers/mps_example/main.cpp @@ -18,13 +18,14 @@ #include "Engine.h" #include "InputQuery.h" #include "MpsParser.h" + #include int main( int argc, char *argv[] ) { if ( argc != 2 ) { - printf( "Error: please provide an mps file\n"); + printf( "Error: please provide an mps file\n" ); return 0; } diff --git a/src/input_parsers/onnx_example/main.cpp b/src/input_parsers/onnx_example/main.cpp index a0708969a1..012067098e 100644 --- a/src/input_parsers/onnx_example/main.cpp +++ b/src/input_parsers/onnx_example/main.cpp @@ -14,6 +14,7 @@ #include "Engine.h" #include "InputQuery.h" #include "OnnxParser.h" + #include int main( int argc, char *argv[] ) diff --git a/src/input_parsers/tests/Test_OnnxParser.h b/src/input_parsers/tests/Test_OnnxParser.h index 720d11719e..f8e59bb8bb 100644 --- a/src/input_parsers/tests/Test_OnnxParser.h +++ b/src/input_parsers/tests/Test_OnnxParser.h @@ -13,51 +13,51 @@ ** Unit tests for the OnnxParser class. **/ -#include - #include "Engine.h" #include "InputQuery.h" #include "OnnxParser.h" + +#include #include class OnnxParserTestSuite : public CxxTest::TestSuite { - public: - const double DELTA = 0.0001; +public: + const double DELTA = 0.0001; - void run_test(String name, Vector inputValues, Vector expectedOutputValues) - { - // Extract an input query from the network - InputQuery inputQuery; + void run_test( String name, Vector inputValues, Vector expectedOutputValues ) + { + // Extract an input query from the network + InputQuery inputQuery; - String networkPath = Stringf("%s/%s.onnx", RESOURCES_DIR "/onnx/layer-zoo", name.ascii()); - OnnxParser onnxParser ( networkPath ); - TS_ASSERT_THROWS_NOTHING( onnxParser.generateQuery( inputQuery ) ); + String networkPath = Stringf( "%s/%s.onnx", RESOURCES_DIR "/onnx/layer-zoo", name.ascii() ); + OnnxParser onnxParser( networkPath ); + TS_ASSERT_THROWS_NOTHING( onnxParser.generateQuery( inputQuery ) ); - TS_ASSERT ( inputValues.size() == inputQuery.getNumInputVariables() ); - TS_ASSERT ( expectedOutputValues.size() == inputQuery.getNumOutputVariables() ); + TS_ASSERT( inputValues.size() == inputQuery.getNumInputVariables() ); + TS_ASSERT( expectedOutputValues.size() == inputQuery.getNumOutputVariables() ); - for ( unsigned int i = 0; i < inputValues.size(); i++ ) - { - unsigned int inputVariable = inputQuery.inputVariableByIndex(i); - inputQuery.setLowerBound(inputVariable, inputValues[i]); - inputQuery.setUpperBound(inputVariable, inputValues[i]); - } + for ( unsigned int i = 0; i < inputValues.size(); i++ ) + { + unsigned int inputVariable = inputQuery.inputVariableByIndex( i ); + inputQuery.setLowerBound( inputVariable, inputValues[i] ); + inputQuery.setUpperBound( inputVariable, inputValues[i] ); + } - Engine engine; - TS_ASSERT_THROWS_NOTHING( engine.processInputQuery( inputQuery ) ); - TS_ASSERT_THROWS_NOTHING( engine.solve() ); - engine.extractSolution( inputQuery ); + Engine engine; + TS_ASSERT_THROWS_NOTHING( engine.processInputQuery( inputQuery ) ); + TS_ASSERT_THROWS_NOTHING( engine.solve() ); + engine.extractSolution( inputQuery ); - for ( unsigned int i = 0; i < expectedOutputValues.size(); ++i ) - { - unsigned int outputVariable = inputQuery.outputVariableByIndex( i ); - double actualOutputValue = inputQuery.getSolutionValue( outputVariable ); - double expectedOutputValue = expectedOutputValues[i]; + for ( unsigned int i = 0; i < expectedOutputValues.size(); ++i ) + { + unsigned int outputVariable = inputQuery.outputVariableByIndex( i ); + double actualOutputValue = inputQuery.getSolutionValue( outputVariable ); + double expectedOutputValue = expectedOutputValues[i]; - TS_ASSERT_DELTA( actualOutputValue, expectedOutputValue, DELTA ); - } + TS_ASSERT_DELTA( actualOutputValue, expectedOutputValue, DELTA ); } + } // Disabled due to https://github.com/NeuralNetworkVerification/Marabou/issues/637 // Constant nodes are tested anyway as part of the other networks which require @@ -77,199 +77,124 @@ class OnnxParserTestSuite : public CxxTest::TestSuite void test_identity() { - Vector input = { - 0, 0.5, - 1, 1.5 - }; - Vector output = { - 0, 0.5, - 1, 1.5 - }; - run_test("identity", input, output); + Vector input = { 0, 0.5, 1, 1.5 }; + Vector output = { 0, 0.5, 1, 1.5 }; + run_test( "identity", input, output ); } void test_reshape() { - Vector input = { - 0, 0.5, - 1, 1.5 - }; - Vector output = { - 0, - 0.5, - 1, - 1.5 - }; - run_test("reshape", input, output); + Vector input = { 0, 0.5, 1, 1.5 }; + Vector output = { 0, 0.5, 1, 1.5 }; + run_test( "reshape", input, output ); } void test_reshape_with_dimension_inference() { - Vector input = { - 0, 0.5, - 1, 1.5 - }; - Vector output = { - 0, - 0.5, - 1, - 1.5 - }; - run_test("reshape_with_dimension_inference", input, output); + Vector input = { 0, 0.5, 1, 1.5 }; + Vector output = { 0, 0.5, 1, 1.5 }; + run_test( "reshape_with_dimension_inference", input, output ); } void test_flatten() { - Vector input = { - 0, 0.5, - 1, 1.5, + Vector input = { 0, 0.5, 1, 1.5, - -1, -3, - -4, 0.0 - }; - Vector output = { - 0, 0.5, 1, 1.5, - -1, -3, -4, 0.0 - }; - run_test("flatten", input, output); + -1, -3, -4, 0.0 }; + Vector output = { 0, 0.5, 1, 1.5, -1, -3, -4, 0.0 }; + run_test( "flatten", input, output ); } void test_transpose() { - Vector input = { - 0, 1, -2, - 0.5, 1.5, -3 - }; - Vector output = { - 0, 0.5, - 1, 1.5, - -2, -3 - }; - run_test("transpose", input, output); + Vector input = { 0, 1, -2, 0.5, 1.5, -3 }; + Vector output = { 0, 0.5, 1, 1.5, -2, -3 }; + run_test( "transpose", input, output ); } // Reference implementation for batch normalisation - double batchnorm_fn(double input, double epsilon, double scale, double bias, double mean, double variance) + double batchnorm_fn( double input, + double epsilon, + double scale, + double bias, + double mean, + double variance ) { - return (input - mean) / sqrt(variance + epsilon) * scale + bias; + return ( input - mean ) / sqrt( variance + epsilon ) * scale + bias; } void test_batch_normalization() { double eps = 1e-05; - Vector input = { - 0, 1, - 2, 3, - 4, 5 - }; + Vector input = { 0, 1, 2, 3, 4, 5 }; Vector output = { - batchnorm_fn(0, eps, 0.5, 0, 5, 0.5), batchnorm_fn(1, eps, 0.5, 0, 5, 0.5), - batchnorm_fn(2, eps, 1, 1, 6, 0.5), batchnorm_fn(3, eps, 1, 1, 6, 0.5), - batchnorm_fn(4, eps, 2, 0, 7, 0.5), batchnorm_fn(5, eps, 2, 0, 7, 0.5), + batchnorm_fn( 0, eps, 0.5, 0, 5, 0.5 ), batchnorm_fn( 1, eps, 0.5, 0, 5, 0.5 ), + batchnorm_fn( 2, eps, 1, 1, 6, 0.5 ), batchnorm_fn( 3, eps, 1, 1, 6, 0.5 ), + batchnorm_fn( 4, eps, 2, 0, 7, 0.5 ), batchnorm_fn( 5, eps, 2, 0, 7, 0.5 ), }; - run_test("batchnorm", input, output); + run_test( "batchnorm", input, output ); } void test_maxpool() { // Taken from https://github.com/onnx/onnx/blob/main/docs/Operators.md#maxpool Vector input = { - 1, 2, 3, 4, - 5, 6, 7, 8, - 9, 10, 11, 12, - 13, 14, 15, 16, + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, }; - Vector output = { - 11, 12, - 15, 16 - }; - run_test("maxpool", input, output); + Vector output = { 11, 12, 15, 16 }; + run_test( "maxpool", input, output ); } void test_conv() { // Taken from https://github.com/onnx/onnx/blob/main/docs/Operators.md#Conv Vector input = { - 0.0, 1.0, 2.0, 3.0, 4.0, - 5.0, 6.0, 7.0, 8.0, 9.0, - 10.0, 11.0, 12.0, 13.0, 14.0, - 15.0, 16.0, 17.0, 18.0, 19.0, - 20.0, 21.0, 22.0, 23.0, 24.0, + 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, + 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0, }; Vector output = { - 12.0, 21.0, 27.0, 33.0, 24.0, - 33.0, 54.0, 63.0, 72.0, 51.0, - 63.0, 99.0, 108.0, 117.0, 81.0, - 93.0, 144.0, 153.0, 162.0, 111.0, - 72.0, 111.0, 117.0, 123.0, 84.0, + 12.0, 21.0, 27.0, 33.0, 24.0, 33.0, 54.0, 63.0, 72.0, 51.0, 63.0, 99.0, 108.0, + 117.0, 81.0, 93.0, 144.0, 153.0, 162.0, 111.0, 72.0, 111.0, 117.0, 123.0, 84.0, }; - run_test("conv", input, output); + run_test( "conv", input, output ); } void test_gemm() { // 0.25 * input * [[0.5, 1.0], [1.0, 2.0]]^T + 0.5 * [3, 4.5] - Vector input = { - 0.0, 1.0, - 2.0, 3.0 - }; - Vector output = { - 1.75, 2.75, - 2.5, 4.5 - }; - run_test("gemm", input, output); + Vector input = { 0.0, 1.0, 2.0, 3.0 }; + Vector output = { 1.75, 2.75, 2.5, 4.5 }; + run_test( "gemm", input, output ); } void test_relu() { - Vector input = { - -2.0, 0.0, - 0.1, 3.0 - }; - Vector output = { - 0, 0, - 0.1, 3 - }; - run_test("relu", input, output); + Vector input = { -2.0, 0.0, 0.1, 3.0 }; + Vector output = { 0, 0, 0.1, 3 }; + run_test( "relu", input, output ); } void test_add() { - Vector input = { - -2.0, 0.0, - 0.1, 3.0 - }; - Vector output = { - -1.5, 1, - 1.6, 5 - }; - run_test("add", input, output); + Vector input = { -2.0, 0.0, 0.1, 3.0 }; + Vector output = { -1.5, 1, 1.6, 5 }; + run_test( "add", input, output ); } void test_sub() { - Vector input = { - -2.0, 0.0, - 0.1, 3.0 - }; - Vector output = { - -2.5, -1, - -1.4, 1 - }; - run_test("sub", input, output); + Vector input = { -2.0, 0.0, 0.1, 3.0 }; + Vector output = { -2.5, -1, -1.4, 1 }; + run_test( "sub", input, output ); } void test_matmul() { Vector input = { - -2, 0, 1, - 1.5, 2, 3, - }; - Vector output = { - -1, -3, - 0, -1.25 + -2, 0, 1, 1.5, 2, 3, }; - run_test("matmul", input, output); + Vector output = { -1, -3, 0, -1.25 }; + run_test( "matmul", input, output ); } double sigmoid_fn( double value ) @@ -295,7 +220,7 @@ class OnnxParserTestSuite : public CxxTest::TestSuite double tanh_fn( double value ) { - return (exp( 2 * value ) - 1) / (exp( 2 * value ) - 1); + return ( exp( 2 * value ) - 1 ) / ( exp( 2 * value ) - 1 ); } // Disabled as there appears to be a bug in Marabou main. diff --git a/src/input_parsers/tests/Test_VnnLibParser.h b/src/input_parsers/tests/Test_VnnLibParser.h index 24b749f93c..e861b34fc1 100644 --- a/src/input_parsers/tests/Test_VnnLibParser.h +++ b/src/input_parsers/tests/Test_VnnLibParser.h @@ -12,12 +12,12 @@ ** Unit tests for the VnnLibParser class. **/ -#include - #include "Engine.h" #include "InputQuery.h" #include "OnnxParser.h" #include "VnnLibParser.h" + +#include #include class VnnLibParserTestSuite : public CxxTest::TestSuite @@ -25,8 +25,10 @@ class VnnLibParserTestSuite : public CxxTest::TestSuite public: void test_nano_vnncomp() { - String filename = Stringf( "%s/%s", RESOURCES_DIR "/onnx/vnnlib/", "test_nano_vnncomp.vnnlib" ); - String onnxFilename = Stringf( "%s/%s", RESOURCES_DIR "/onnx/vnnlib/", "test_nano_vnncomp.onnx" ); + String filename = + Stringf( "%s/%s", RESOURCES_DIR "/onnx/vnnlib/", "test_nano_vnncomp.vnnlib" ); + String onnxFilename = + Stringf( "%s/%s", RESOURCES_DIR "/onnx/vnnlib/", "test_nano_vnncomp.onnx" ); InputQuery inputQuery; @@ -48,8 +50,10 @@ class VnnLibParserTestSuite : public CxxTest::TestSuite void test_tiny_vnncomp() { - String filename = Stringf( "%s/%s", RESOURCES_DIR "/onnx/vnnlib/", "test_tiny_vnncomp.vnnlib" ); - String onnxFilename = Stringf( "%s/%s", RESOURCES_DIR "/onnx/vnnlib/", "test_tiny_vnncomp.onnx" ); + String filename = + Stringf( "%s/%s", RESOURCES_DIR "/onnx/vnnlib/", "test_tiny_vnncomp.vnnlib" ); + String onnxFilename = + Stringf( "%s/%s", RESOURCES_DIR "/onnx/vnnlib/", "test_tiny_vnncomp.onnx" ); InputQuery inputQuery; @@ -61,7 +65,8 @@ class VnnLibParserTestSuite : public CxxTest::TestSuite unsigned int inputVar = inputQuery.inputVariableByIndex( 0 ); unsigned int outputVar = inputQuery.outputVariableByIndex( 0 ); - auto *disjunction = ( DisjunctionConstraint * ) ( inputQuery.getPiecewiseLinearConstraints().back() ); + auto *disjunction = + (DisjunctionConstraint *)( inputQuery.getPiecewiseLinearConstraints().back() ); const auto &caseSplits = disjunction->getCaseSplits(); const auto &caseSplitsIter = caseSplits.begin(); auto boundsIter = ( *caseSplitsIter ).getBoundTightenings().begin(); @@ -80,8 +85,10 @@ class VnnLibParserTestSuite : public CxxTest::TestSuite void test_small_vnncomp() { - String filename = Stringf( "%s/%s", RESOURCES_DIR "/onnx/vnnlib/", "test_small_vnncomp.vnnlib" ); - String onnxFilename = Stringf( "%s/%s", RESOURCES_DIR "/onnx/vnnlib/", "test_small_vnncomp.onnx" ); + String filename = + Stringf( "%s/%s", RESOURCES_DIR "/onnx/vnnlib/", "test_small_vnncomp.vnnlib" ); + String onnxFilename = + Stringf( "%s/%s", RESOURCES_DIR "/onnx/vnnlib/", "test_small_vnncomp.onnx" ); InputQuery inputQuery; Equation testEq = Equation( Equation::EquationType::LE ); @@ -94,7 +101,8 @@ class VnnLibParserTestSuite : public CxxTest::TestSuite unsigned int inputVar = inputQuery.inputVariableByIndex( 0 ); unsigned int outputVar = inputQuery.outputVariableByIndex( 0 ); - auto *disjunction = ( DisjunctionConstraint * ) ( inputQuery.getPiecewiseLinearConstraints().back() ); + auto *disjunction = + (DisjunctionConstraint *)( inputQuery.getPiecewiseLinearConstraints().back() ); const auto &caseSplits = disjunction->getCaseSplits(); const auto &caseSplitsIter = caseSplits.begin(); auto boundsIter = ( *caseSplitsIter ).getBoundTightenings().begin(); @@ -113,8 +121,10 @@ class VnnLibParserTestSuite : public CxxTest::TestSuite void test_sat_vnncomp() { - String filename = Stringf( "%s/%s", RESOURCES_DIR "/onnx/vnnlib/", "test_prop_vnncomp.vnnlib" ); - String onnxFilename = Stringf( "%s/%s", RESOURCES_DIR "/onnx/vnnlib/", "test_sat_vnncomp.onnx" ); + String filename = + Stringf( "%s/%s", RESOURCES_DIR "/onnx/vnnlib/", "test_prop_vnncomp.vnnlib" ); + String onnxFilename = + Stringf( "%s/%s", RESOURCES_DIR "/onnx/vnnlib/", "test_sat_vnncomp.onnx" ); InputQuery inputQuery; Equation testEq = Equation( Equation::EquationType::LE ); @@ -133,14 +143,19 @@ class VnnLibParserTestSuite : public CxxTest::TestSuite unsigned int input3 = inputQuery.inputVariableByIndex( 3 ); unsigned int input4 = inputQuery.inputVariableByIndex( 4 ); - TS_ASSERT( lowerBounds.exists( input0 ) && lowerBounds.get( input0 ) == -0.30353115613746867 ) - TS_ASSERT( upperBounds.exists( input0 ) && upperBounds.get( input0 ) == -0.29855281193475053 ) + TS_ASSERT( lowerBounds.exists( input0 ) && + lowerBounds.get( input0 ) == -0.30353115613746867 ) + TS_ASSERT( upperBounds.exists( input0 ) && + upperBounds.get( input0 ) == -0.29855281193475053 ) - TS_ASSERT( lowerBounds.exists( input1 ) && lowerBounds.get( input1 ) == -0.009549296585513092 ) - TS_ASSERT( upperBounds.exists( input1 ) && upperBounds.get( input1 ) == 0.009549296585513092 ) + TS_ASSERT( lowerBounds.exists( input1 ) && + lowerBounds.get( input1 ) == -0.009549296585513092 ) + TS_ASSERT( upperBounds.exists( input1 ) && + upperBounds.get( input1 ) == 0.009549296585513092 ) TS_ASSERT( lowerBounds.exists( input2 ) && lowerBounds.get( input2 ) == 0.4933803235848431 ) - TS_ASSERT( upperBounds.exists( input2 ) && upperBounds.get( input2 ) == 0.49999999998567607 ) + TS_ASSERT( upperBounds.exists( input2 ) && + upperBounds.get( input2 ) == 0.49999999998567607 ) TS_ASSERT( lowerBounds.exists( input3 ) && lowerBounds.get( input3 ) == 0.3 ) TS_ASSERT( upperBounds.exists( input3 ) && upperBounds.get( input3 ) == 0.5 ) @@ -189,8 +204,10 @@ class VnnLibParserTestSuite : public CxxTest::TestSuite void test_unsat_vnncomp() { - String filename = Stringf( "%s/%s", RESOURCES_DIR "/onnx/vnnlib/", "test_prop_vnncomp.vnnlib" ); - String onnxFilename = Stringf( "%s/%s", RESOURCES_DIR "/onnx/vnnlib/", "test_unsat_vnncomp.onnx" ); + String filename = + Stringf( "%s/%s", RESOURCES_DIR "/onnx/vnnlib/", "test_prop_vnncomp.vnnlib" ); + String onnxFilename = + Stringf( "%s/%s", RESOURCES_DIR "/onnx/vnnlib/", "test_unsat_vnncomp.onnx" ); InputQuery inputQuery; Equation testEq = Equation( Equation::EquationType::LE ); @@ -209,14 +226,19 @@ class VnnLibParserTestSuite : public CxxTest::TestSuite unsigned int input3 = inputQuery.inputVariableByIndex( 3 ); unsigned int input4 = inputQuery.inputVariableByIndex( 4 ); - TS_ASSERT( lowerBounds.exists( input0 ) && lowerBounds.get( input0 ) == -0.30353115613746867 ) - TS_ASSERT( upperBounds.exists( input0 ) && upperBounds.get( input0 ) == -0.29855281193475053 ) + TS_ASSERT( lowerBounds.exists( input0 ) && + lowerBounds.get( input0 ) == -0.30353115613746867 ) + TS_ASSERT( upperBounds.exists( input0 ) && + upperBounds.get( input0 ) == -0.29855281193475053 ) - TS_ASSERT( lowerBounds.exists( input1 ) && lowerBounds.get( input1 ) == -0.009549296585513092 ) - TS_ASSERT( upperBounds.exists( input1 ) && upperBounds.get( input1 ) == 0.009549296585513092 ) + TS_ASSERT( lowerBounds.exists( input1 ) && + lowerBounds.get( input1 ) == -0.009549296585513092 ) + TS_ASSERT( upperBounds.exists( input1 ) && + upperBounds.get( input1 ) == 0.009549296585513092 ) TS_ASSERT( lowerBounds.exists( input2 ) && lowerBounds.get( input2 ) == 0.4933803235848431 ) - TS_ASSERT( upperBounds.exists( input2 ) && upperBounds.get( input2 ) == 0.49999999998567607 ) + TS_ASSERT( upperBounds.exists( input2 ) && + upperBounds.get( input2 ) == 0.49999999998567607 ) TS_ASSERT( lowerBounds.exists( input3 ) && lowerBounds.get( input3 ) == 0.3 ) TS_ASSERT( upperBounds.exists( input3 ) && upperBounds.get( input3 ) == 0.5 ) @@ -265,8 +287,10 @@ class VnnLibParserTestSuite : public CxxTest::TestSuite void test_add_const() { - String filename = Stringf( "%s/%s", RESOURCES_DIR "/onnx/vnnlib/", "test_add_const.vnnlib" ); - String onnxFilename = Stringf( "%s/%s", RESOURCES_DIR "/onnx/vnnlib/", "test_nano_vnncomp.onnx" ); + String filename = + Stringf( "%s/%s", RESOURCES_DIR "/onnx/vnnlib/", "test_add_const.vnnlib" ); + String onnxFilename = + Stringf( "%s/%s", RESOURCES_DIR "/onnx/vnnlib/", "test_nano_vnncomp.onnx" ); InputQuery inputQuery; Equation testEq = Equation( Equation::EquationType::LE ); @@ -285,13 +309,13 @@ class VnnLibParserTestSuite : public CxxTest::TestSuite TS_ASSERT( lowerBounds.exists( inputVar ) && lowerBounds.get( inputVar ) == 0 ) TS_ASSERT( upperBounds.exists( inputVar ) && upperBounds.get( inputVar ) == 1 ) TS_ASSERT( lowerBounds.exists( outputVar ) && lowerBounds.get( outputVar ) == 0 ) - } void test_add_var() { String filename = Stringf( "%s/%s", RESOURCES_DIR "/onnx/vnnlib/", "test_add_var.vnnlib" ); - String onnxFilename = Stringf( "%s/%s", RESOURCES_DIR "/onnx/vnnlib/", "test_sat_vnncomp.onnx" ); + String onnxFilename = + Stringf( "%s/%s", RESOURCES_DIR "/onnx/vnnlib/", "test_sat_vnncomp.onnx" ); InputQuery inputQuery; Equation testEq = Equation( Equation::EquationType::LE ); @@ -310,14 +334,19 @@ class VnnLibParserTestSuite : public CxxTest::TestSuite unsigned int input3 = inputQuery.inputVariableByIndex( 3 ); unsigned int input4 = inputQuery.inputVariableByIndex( 4 ); - TS_ASSERT( lowerBounds.exists( input0 ) && lowerBounds.get( input0 ) == -0.30353115613746867 ) - TS_ASSERT( upperBounds.exists( input0 ) && upperBounds.get( input0 ) == -0.29855281193475053 ) + TS_ASSERT( lowerBounds.exists( input0 ) && + lowerBounds.get( input0 ) == -0.30353115613746867 ) + TS_ASSERT( upperBounds.exists( input0 ) && + upperBounds.get( input0 ) == -0.29855281193475053 ) - TS_ASSERT( lowerBounds.exists( input1 ) && lowerBounds.get( input1 ) == -0.009549296585513092 ) - TS_ASSERT( upperBounds.exists( input1 ) && upperBounds.get( input1 ) == 0.009549296585513092 ) + TS_ASSERT( lowerBounds.exists( input1 ) && + lowerBounds.get( input1 ) == -0.009549296585513092 ) + TS_ASSERT( upperBounds.exists( input1 ) && + upperBounds.get( input1 ) == 0.009549296585513092 ) TS_ASSERT( lowerBounds.exists( input2 ) && lowerBounds.get( input2 ) == 0.4933803235848431 ) - TS_ASSERT( upperBounds.exists( input2 ) && upperBounds.get( input2 ) == 0.49999999998567607 ) + TS_ASSERT( upperBounds.exists( input2 ) && + upperBounds.get( input2 ) == 0.49999999998567607 ) TS_ASSERT( lowerBounds.exists( input3 ) && lowerBounds.get( input3 ) == 0.3 ) TS_ASSERT( upperBounds.exists( input3 ) && upperBounds.get( input3 ) == 0.5 ) @@ -344,8 +373,10 @@ class VnnLibParserTestSuite : public CxxTest::TestSuite void test_sub_const() { - String filename = Stringf( "%s/%s", RESOURCES_DIR "/onnx/vnnlib/", "test_sub_const.vnnlib" ); - String onnxFilename = Stringf( "%s/%s", RESOURCES_DIR "/onnx/vnnlib/", "test_nano_vnncomp.onnx" ); + String filename = + Stringf( "%s/%s", RESOURCES_DIR "/onnx/vnnlib/", "test_sub_const.vnnlib" ); + String onnxFilename = + Stringf( "%s/%s", RESOURCES_DIR "/onnx/vnnlib/", "test_nano_vnncomp.onnx" ); InputQuery inputQuery; Equation testEq = Equation( Equation::EquationType::LE ); @@ -369,7 +400,8 @@ class VnnLibParserTestSuite : public CxxTest::TestSuite void test_sub_var() { String filename = Stringf( "%s/%s", RESOURCES_DIR "/onnx/vnnlib/", "test_sub_var.vnnlib" ); - String onnxFilename = Stringf( "%s/%s", RESOURCES_DIR "/onnx/vnnlib/", "test_sat_vnncomp.onnx" ); + String onnxFilename = + Stringf( "%s/%s", RESOURCES_DIR "/onnx/vnnlib/", "test_sat_vnncomp.onnx" ); InputQuery inputQuery; Equation testEq = Equation( Equation::EquationType::LE ); @@ -388,14 +420,19 @@ class VnnLibParserTestSuite : public CxxTest::TestSuite unsigned int input3 = inputQuery.inputVariableByIndex( 3 ); unsigned int input4 = inputQuery.inputVariableByIndex( 4 ); - TS_ASSERT( lowerBounds.exists( input0 ) && lowerBounds.get( input0 ) == -0.30353115613746867 ) - TS_ASSERT( upperBounds.exists( input0 ) && upperBounds.get( input0 ) == -0.29855281193475053 ) + TS_ASSERT( lowerBounds.exists( input0 ) && + lowerBounds.get( input0 ) == -0.30353115613746867 ) + TS_ASSERT( upperBounds.exists( input0 ) && + upperBounds.get( input0 ) == -0.29855281193475053 ) - TS_ASSERT( lowerBounds.exists( input1 ) && lowerBounds.get( input1 ) == -0.009549296585513092 ) - TS_ASSERT( upperBounds.exists( input1 ) && upperBounds.get( input1 ) == 0.009549296585513092 ) + TS_ASSERT( lowerBounds.exists( input1 ) && + lowerBounds.get( input1 ) == -0.009549296585513092 ) + TS_ASSERT( upperBounds.exists( input1 ) && + upperBounds.get( input1 ) == 0.009549296585513092 ) TS_ASSERT( lowerBounds.exists( input2 ) && lowerBounds.get( input2 ) == 0.4933803235848431 ) - TS_ASSERT( upperBounds.exists( input2 ) && upperBounds.get( input2 ) == 0.49999999998567607 ) + TS_ASSERT( upperBounds.exists( input2 ) && + upperBounds.get( input2 ) == 0.49999999998567607 ) TS_ASSERT( lowerBounds.exists( input3 ) && lowerBounds.get( input3 ) == 0.3 ) TS_ASSERT( upperBounds.exists( input3 ) && upperBounds.get( input3 ) == 0.5 ) @@ -422,8 +459,10 @@ class VnnLibParserTestSuite : public CxxTest::TestSuite void test_mul_var_const() { - String filename = Stringf( "%s/%s", RESOURCES_DIR "/onnx/vnnlib/", "test_mul_var_const.vnnlib" ); - String onnxFilename = Stringf( "%s/%s", RESOURCES_DIR "/onnx/vnnlib/", "test_nano_vnncomp.onnx" ); + String filename = + Stringf( "%s/%s", RESOURCES_DIR "/onnx/vnnlib/", "test_mul_var_const.vnnlib" ); + String onnxFilename = + Stringf( "%s/%s", RESOURCES_DIR "/onnx/vnnlib/", "test_nano_vnncomp.onnx" ); InputQuery inputQuery; Equation testEq = Equation( Equation::EquationType::LE ); diff --git a/src/nlr/DeepPolyAbsoluteValueElement.cpp b/src/nlr/DeepPolyAbsoluteValueElement.cpp index 9f05005b93..864a390130 100644 --- a/src/nlr/DeepPolyAbsoluteValueElement.cpp +++ b/src/nlr/DeepPolyAbsoluteValueElement.cpp @@ -14,6 +14,7 @@ **/ #include "DeepPolyAbsoluteValueElement.h" + #include "FloatUtils.h" namespace NLR { @@ -30,8 +31,8 @@ DeepPolyAbsoluteValueElement::~DeepPolyAbsoluteValueElement() freeMemoryIfNeeded(); } -void DeepPolyAbsoluteValueElement::execute( const Map - &deepPolyElementsBefore ) +void DeepPolyAbsoluteValueElement::execute( + const Map &deepPolyElementsBefore ) { log( "Executing..." ); ASSERT( hasPredecessor() ); @@ -42,12 +43,9 @@ void DeepPolyAbsoluteValueElement::execute( const MapgetActivationSources( i ).begin() ); - DeepPolyElement *predecessor = - deepPolyElementsBefore[sourceIndex._layer]; - double sourceLb = predecessor->getLowerBound - ( sourceIndex._neuron ); - double sourceUb = predecessor->getUpperBound - ( sourceIndex._neuron ); + DeepPolyElement *predecessor = deepPolyElementsBefore[sourceIndex._layer]; + double sourceLb = predecessor->getLowerBound( sourceIndex._neuron ); + double sourceUb = predecessor->getUpperBound( sourceIndex._neuron ); if ( !FloatUtils::isNegative( sourceLb ) ) { @@ -89,18 +87,25 @@ void DeepPolyAbsoluteValueElement::execute( const MapgetLayerIndex() ) ); @@ -112,12 +117,9 @@ void DeepPolyAbsoluteValueElement::symbolicBoundInTermsOfPredecessor */ for ( unsigned i = 0; i < _size; ++i ) { - NeuronIndex sourceIndex = *( _layer-> - getActivationSources( i ).begin() ); + NeuronIndex sourceIndex = *( _layer->getActivationSources( i ).begin() ); unsigned sourceNeuronIndex = sourceIndex._neuron; - DEBUG({ - ASSERT( predecessor->getLayerIndex() == sourceIndex._layer ); - }); + DEBUG( { ASSERT( predecessor->getLayerIndex() == sourceIndex._layer ); } ); /* Take symbolic upper bound as an example. Suppose the symbolic upper bound of the j-th neuron in the @@ -150,7 +152,8 @@ void DeepPolyAbsoluteValueElement::symbolicBoundInTermsOfPredecessor { symbolicLbInTermsOfPredecessor[newIndex] += weightLb * coeffLb; symbolicLowerBias[j] += weightLb * lowerBias; - } else + } + else { symbolicLbInTermsOfPredecessor[newIndex] += weightLb * coeffUb; symbolicLowerBias[j] += weightLb * upperBias; @@ -162,7 +165,8 @@ void DeepPolyAbsoluteValueElement::symbolicBoundInTermsOfPredecessor { symbolicUbInTermsOfPredecessor[newIndex] += weightUb * coeffUb; symbolicUpperBias[j] += weightUb * upperBias; - } else + } + else { symbolicUbInTermsOfPredecessor[newIndex] += weightUb * coeffLb; symbolicUpperBias[j] += weightUb * lowerBias; diff --git a/src/nlr/DeepPolyAbsoluteValueElement.h b/src/nlr/DeepPolyAbsoluteValueElement.h index af23e146d5..7ca2809e0a 100644 --- a/src/nlr/DeepPolyAbsoluteValueElement.h +++ b/src/nlr/DeepPolyAbsoluteValueElement.h @@ -20,6 +20,7 @@ #include "Layer.h" #include "MStringf.h" #include "NLRError.h" + #include namespace NLR { @@ -30,17 +31,18 @@ class DeepPolyAbsoluteValueElement : public DeepPolyElement DeepPolyAbsoluteValueElement( Layer *layer ); ~DeepPolyAbsoluteValueElement(); - void execute( const Map - &deepPolyElementsBefore ); + void execute( const Map &deepPolyElementsBefore ); - void symbolicBoundInTermsOfPredecessor - ( const double *symbolicLb, const double*symbolicUb, double - *symbolicLowerBias, double *symbolicUpperBias, double - *symbolicLbInTermsOfPredecessor, double *symbolicUbInTermsOfPredecessor, - unsigned targetLayerSize, DeepPolyElement *predecessor ); + void symbolicBoundInTermsOfPredecessor( const double *symbolicLb, + const double *symbolicUb, + double *symbolicLowerBias, + double *symbolicUpperBias, + double *symbolicLbInTermsOfPredecessor, + double *symbolicUbInTermsOfPredecessor, + unsigned targetLayerSize, + DeepPolyElement *predecessor ); private: - void allocateMemory(); void freeMemoryIfNeeded(); void log( const String &message ); diff --git a/src/nlr/DeepPolyAnalysis.cpp b/src/nlr/DeepPolyAnalysis.cpp index e4db93c4cf..2507791c6d 100644 --- a/src/nlr/DeepPolyAnalysis.cpp +++ b/src/nlr/DeepPolyAnalysis.cpp @@ -13,24 +13,25 @@ **/ -#include "Debug.h" #include "DeepPolyAnalysis.h" + +#include "Debug.h" #include "DeepPolyAbsoluteValueElement.h" -#include "DeepPolyInputElement.h" #include "DeepPolyBilinearElement.h" +#include "DeepPolyInputElement.h" #include "DeepPolyLeakyReLUElement.h" #include "DeepPolyMaxPoolElement.h" -#include "DeepPolyWeightedSumElement.h" #include "DeepPolyReLUElement.h" #include "DeepPolyRoundElement.h" #include "DeepPolySigmoidElement.h" #include "DeepPolySignElement.h" #include "DeepPolySoftmaxElement.h" +#include "DeepPolyWeightedSumElement.h" #include "FloatUtils.h" #include "InfeasibleQueryException.h" #include "Layer.h" -#include "MatrixMultiplication.h" #include "MStringf.h" +#include "MatrixMultiplication.h" #include "NLRError.h" #include "TimeUtils.h" @@ -121,9 +122,9 @@ void DeepPolyAnalysis::freeMemoryIfNeeded() void DeepPolyAnalysis::run() { struct timespec deepPolyStart; - (void) deepPolyStart; + (void)deepPolyStart; struct timespec deepPolyEnd; - (void) deepPolyEnd; + (void)deepPolyEnd; deepPolyStart = TimeUtils::sampleMicro(); @@ -151,21 +152,25 @@ void DeepPolyAnalysis::run() if ( layer->getLb( j ) < lb ) { log( Stringf( "Neuron %u_%u lower-bound updated from %f to %f", - index, j, layer->getLb( j ), lb ) ); + index, + j, + layer->getLb( j ), + lb ) ); layer->setLb( j, lb ); - _layerOwner->receiveTighterBound - ( Tightening( layer->neuronToVariable( j ), - lb, Tightening::LB ) ); + _layerOwner->receiveTighterBound( + Tightening( layer->neuronToVariable( j ), lb, Tightening::LB ) ); } double ub = deepPolyElement->getUpperBound( j ); if ( layer->getUb( j ) > ub ) { log( Stringf( "Neuron %u_%u upper-bound updated from %f to %f", - index, j, layer->getUb( j ), ub ) ); + index, + j, + layer->getUb( j ), + ub ) ); layer->setUb( j, ub ); - _layerOwner->receiveTighterBound - ( Tightening( layer->neuronToVariable( j ), - ub, Tightening::UB ) ); + _layerOwner->receiveTighterBound( + Tightening( layer->neuronToVariable( j ), ub, Tightening::UB ) ); } } log( Stringf( "Running deeppoly analysis for layer %u - done", index ) ); @@ -175,21 +180,21 @@ void DeepPolyAnalysis::run() void DeepPolyAnalysis::allocateMemory() { freeMemoryIfNeeded(); - _work1SymbolicLb= new double[_maxLayerSize * _maxLayerSize]; - _work1SymbolicUb= new double[_maxLayerSize * _maxLayerSize]; - _work2SymbolicLb= new double[_maxLayerSize * _maxLayerSize]; - _work2SymbolicUb= new double[_maxLayerSize * _maxLayerSize]; + _work1SymbolicLb = new double[_maxLayerSize * _maxLayerSize]; + _work1SymbolicUb = new double[_maxLayerSize * _maxLayerSize]; + _work2SymbolicLb = new double[_maxLayerSize * _maxLayerSize]; + _work2SymbolicUb = new double[_maxLayerSize * _maxLayerSize]; - _workSymbolicLowerBias = new double[_maxLayerSize]; - _workSymbolicUpperBias = new double[_maxLayerSize]; + _workSymbolicLowerBias = new double[_maxLayerSize]; + _workSymbolicUpperBias = new double[_maxLayerSize]; - std::fill_n( _work1SymbolicLb, _maxLayerSize * _maxLayerSize, 0 ); - std::fill_n( _work1SymbolicUb, _maxLayerSize * _maxLayerSize, 0 ); - std::fill_n( _work2SymbolicLb, _maxLayerSize * _maxLayerSize, 0 ); - std::fill_n( _work2SymbolicUb, _maxLayerSize * _maxLayerSize, 0 ); + std::fill_n( _work1SymbolicLb, _maxLayerSize * _maxLayerSize, 0 ); + std::fill_n( _work1SymbolicUb, _maxLayerSize * _maxLayerSize, 0 ); + std::fill_n( _work2SymbolicLb, _maxLayerSize * _maxLayerSize, 0 ); + std::fill_n( _work2SymbolicUb, _maxLayerSize * _maxLayerSize, 0 ); - std::fill_n( _workSymbolicLowerBias, _maxLayerSize, 0 ); - std::fill_n( _workSymbolicUpperBias, _maxLayerSize, 0 ); + std::fill_n( _workSymbolicLowerBias, _maxLayerSize, 0 ); + std::fill_n( _workSymbolicUpperBias, _maxLayerSize, 0 ); } DeepPolyElement *DeepPolyAnalysis::createDeepPolyElement( Layer *layer ) @@ -202,33 +207,34 @@ DeepPolyElement *DeepPolyAnalysis::createDeepPolyElement( Layer *layer ) { deepPolyElement = new DeepPolyWeightedSumElement( layer ); // Weighted sum layers need working memory for back substitution - deepPolyElement->setWorkingMemory( _work1SymbolicLb, _work1SymbolicUb, - _work2SymbolicLb, _work2SymbolicUb, + deepPolyElement->setWorkingMemory( _work1SymbolicLb, + _work1SymbolicUb, + _work2SymbolicLb, + _work2SymbolicUb, _workSymbolicLowerBias, _workSymbolicUpperBias ); } - else if ( type == Layer::RELU ) + else if ( type == Layer::RELU ) deepPolyElement = new DeepPolyReLUElement( layer ); - else if ( type == Layer::ROUND ) - deepPolyElement = new DeepPolyRoundElement( layer ); - else if ( type == Layer::LEAKY_RELU ) + else if ( type == Layer::ROUND ) + deepPolyElement = new DeepPolyRoundElement( layer ); + else if ( type == Layer::LEAKY_RELU ) deepPolyElement = new DeepPolyLeakyReLUElement( layer ); - else if ( type == Layer::SIGN ) + else if ( type == Layer::SIGN ) deepPolyElement = new DeepPolySignElement( layer ); - else if ( type == Layer::ABSOLUTE_VALUE ) + else if ( type == Layer::ABSOLUTE_VALUE ) deepPolyElement = new DeepPolyAbsoluteValueElement( layer ); - else if ( type == Layer::MAX ) + else if ( type == Layer::MAX ) deepPolyElement = new DeepPolyMaxPoolElement( layer ); else if ( type == Layer::SIGMOID ) deepPolyElement = new DeepPolySigmoidElement( layer ); else if ( type == Layer::SOFTMAX ) deepPolyElement = new DeepPolySoftmaxElement( layer, _maxLayerSize ); else if ( type == Layer::BILINEAR ) - deepPolyElement = new DeepPolyBilinearElement( layer ); + deepPolyElement = new DeepPolyBilinearElement( layer ); else throw NLRError( NLRError::LAYER_TYPE_NOT_SUPPORTED, - Stringf( "Layer %u not yet supported", - layer->getLayerType() ).ascii() ); + Stringf( "Layer %u not yet supported", layer->getLayerType() ).ascii() ); return deepPolyElement; } diff --git a/src/nlr/DeepPolyAnalysis.h b/src/nlr/DeepPolyAnalysis.h index c614aa303f..2e03f9d0c0 100644 --- a/src/nlr/DeepPolyAnalysis.h +++ b/src/nlr/DeepPolyAnalysis.h @@ -20,6 +20,7 @@ #include "Layer.h" #include "LayerOwner.h" #include "Map.h" + #include namespace NLR { @@ -27,7 +28,6 @@ namespace NLR { class DeepPolyAnalysis { public: - DeepPolyAnalysis( LayerOwner *layerOwner ); ~DeepPolyAnalysis(); @@ -44,12 +44,12 @@ class DeepPolyAnalysis /* Working memory for the abstract elements to execute */ - double * _work1SymbolicLb; - double * _work1SymbolicUb; - double * _work2SymbolicLb; - double * _work2SymbolicUb; - double * _workSymbolicLowerBias; - double * _workSymbolicUpperBias; + double *_work1SymbolicLb; + double *_work1SymbolicUb; + double *_work2SymbolicLb; + double *_work2SymbolicUb; + double *_workSymbolicLowerBias; + double *_workSymbolicUpperBias; unsigned _maxLayerSize; diff --git a/src/nlr/DeepPolyElement.cpp b/src/nlr/DeepPolyElement.cpp index e9cdc31c15..ccd451324a 100644 --- a/src/nlr/DeepPolyElement.cpp +++ b/src/nlr/DeepPolyElement.cpp @@ -32,8 +32,7 @@ DeepPolyElement::DeepPolyElement() , _work2SymbolicLb( NULL ) , _work2SymbolicUb( NULL ) , _workSymbolicLowerBias( NULL ) - , _workSymbolicUpperBias( NULL ) -{}; + , _workSymbolicUpperBias( NULL ){}; unsigned DeepPolyElement::getSize() const { diff --git a/src/nlr/DeepPolyElement.h b/src/nlr/DeepPolyElement.h index 581880b380..077d175f73 100644 --- a/src/nlr/DeepPolyElement.h +++ b/src/nlr/DeepPolyElement.h @@ -17,9 +17,10 @@ #define __DeepPolyElement_h__ #include "Layer.h" -#include "Map.h" #include "MStringf.h" +#include "Map.h" #include "NLRError.h" + #include namespace NLR { @@ -32,19 +33,21 @@ class DeepPolyElement // execute the abstract layer based on the abstract layers topologically // before it. - virtual void execute( const Map - &deepPolyElementsBefore ) = 0; + virtual void execute( const Map &deepPolyElementsBefore ) = 0; /* Given the symbolic bounds of some layer Y (of size layerSize) in terms of this layer, add (to the last four arugment) the symbolic bounds of layer Y in terms of an immediate predecessor of this layer. */ - virtual void symbolicBoundInTermsOfPredecessor - ( const double *symbolicLb, const double*symbolicUb, double - *symbolicLowerBias, double *symbolicUpperBias, double - *symbolicLbInTermsOfPredecessor, double *symbolicUbInTermsOfPredecessor, - unsigned targetLayerSize, DeepPolyElement *predecessor ) = 0; + virtual void symbolicBoundInTermsOfPredecessor( const double *symbolicLb, + const double *symbolicUb, + double *symbolicLowerBias, + double *symbolicUpperBias, + double *symbolicLbInTermsOfPredecessor, + double *symbolicUbInTermsOfPredecessor, + unsigned targetLayerSize, + DeepPolyElement *predecessor ) = 0; /* Returns whether this abstract element has a predecessor. @@ -66,8 +69,10 @@ class DeepPolyElement double getLowerBound( unsigned index ) const; double getUpperBound( unsigned index ) const; - void setWorkingMemory( double *work1SymbolicLb, double *work1SymbolicUb, - double *work2SymbolicLb, double *work2SymbolicUb, + void setWorkingMemory( double *work1SymbolicLb, + double *work1SymbolicUb, + double *work2SymbolicLb, + double *work2SymbolicUb, double *workSymbolicLowerBias, double *workSymbolicUpperBias ); @@ -91,12 +96,12 @@ class DeepPolyElement double *_lb; double *_ub; - double * _work1SymbolicLb; - double * _work1SymbolicUb; - double * _work2SymbolicLb; - double * _work2SymbolicUb; - double * _workSymbolicLowerBias; - double * _workSymbolicUpperBias; + double *_work1SymbolicLb; + double *_work1SymbolicUb; + double *_work2SymbolicLb; + double *_work2SymbolicUb; + double *_workSymbolicLowerBias; + double *_workSymbolicUpperBias; void allocateMemory(); void freeMemoryIfNeeded(); diff --git a/src/nlr/DeepPolyInputElement.cpp b/src/nlr/DeepPolyInputElement.cpp index 9a3c4324e7..d9fa64673e 100644 --- a/src/nlr/DeepPolyInputElement.cpp +++ b/src/nlr/DeepPolyInputElement.cpp @@ -13,8 +13,9 @@ **/ -#include "Debug.h" #include "DeepPolyInputElement.h" + +#include "Debug.h" #include "FloatUtils.h" #include "NLRError.h" @@ -46,9 +47,14 @@ void DeepPolyInputElement::execute( const Map & ) log( "Executing - done" ); } -void DeepPolyInputElement::symbolicBoundInTermsOfPredecessor -( const double *, const double *, double *, double *, double *, double *, - unsigned, DeepPolyElement * ) +void DeepPolyInputElement::symbolicBoundInTermsOfPredecessor( const double *, + const double *, + double *, + double *, + double *, + double *, + unsigned, + DeepPolyElement * ) { // Input layer should not have a predecessor ASSERT( false ); diff --git a/src/nlr/DeepPolyInputElement.h b/src/nlr/DeepPolyInputElement.h index b5a38d9393..9152e93157 100644 --- a/src/nlr/DeepPolyInputElement.h +++ b/src/nlr/DeepPolyInputElement.h @@ -20,6 +20,7 @@ #include "Layer.h" #include "MStringf.h" #include "NLRError.h" + #include namespace NLR { @@ -30,14 +31,16 @@ class DeepPolyInputElement : public DeepPolyElement DeepPolyInputElement( Layer *layer ); ~DeepPolyInputElement(); - void execute( const Map - &deepPolyElementsBefore ); + void execute( const Map &deepPolyElementsBefore ); - void symbolicBoundInTermsOfPredecessor - ( const double *symbolicLb, const double*symbolicUb, double - *symbolicLowerBias, double *symbolicUpperBias, double - *symbolicLbInTermsOfPredecessor, double *symbolicUbInTermsOfPredecessor, - unsigned targetLayerSize, DeepPolyElement *predecessor ); + void symbolicBoundInTermsOfPredecessor( const double *symbolicLb, + const double *symbolicUb, + double *symbolicLowerBias, + double *symbolicUpperBias, + double *symbolicLbInTermsOfPredecessor, + double *symbolicUbInTermsOfPredecessor, + unsigned targetLayerSize, + DeepPolyElement *predecessor ); private: void log( const String &message ); diff --git a/src/nlr/DeepPolyLeakyReLUElement.cpp b/src/nlr/DeepPolyLeakyReLUElement.cpp index 8f8de47645..9d73ed6d40 100644 --- a/src/nlr/DeepPolyLeakyReLUElement.cpp +++ b/src/nlr/DeepPolyLeakyReLUElement.cpp @@ -1,4 +1,4 @@ - /********************* */ +/********************* */ /*! \file DeepPolyLeakyReLUElement.cpp ** \verbatim ** Top contributors (to current version): @@ -14,6 +14,7 @@ **/ #include "DeepPolyLeakyReLUElement.h" + #include "FloatUtils.h" namespace NLR { @@ -33,8 +34,8 @@ DeepPolyLeakyReLUElement::~DeepPolyLeakyReLUElement() freeMemoryIfNeeded(); } -void DeepPolyLeakyReLUElement::execute( const Map - &deepPolyElementsBefore ) +void DeepPolyLeakyReLUElement::execute( + const Map &deepPolyElementsBefore ) { log( "Executing..." ); ASSERT( hasPredecessor() ); @@ -45,12 +46,9 @@ void DeepPolyLeakyReLUElement::execute( const Map for ( unsigned i = 0; i < _size; ++i ) { NeuronIndex sourceIndex = *( _layer->getActivationSources( i ).begin() ); - DeepPolyElement *predecessor = - deepPolyElementsBefore[sourceIndex._layer]; - double sourceLb = predecessor->getLowerBound - ( sourceIndex._neuron ); - double sourceUb = predecessor->getUpperBound - ( sourceIndex._neuron ); + DeepPolyElement *predecessor = deepPolyElementsBefore[sourceIndex._layer]; + double sourceLb = predecessor->getLowerBound( sourceIndex._neuron ); + double sourceUb = predecessor->getUpperBound( sourceIndex._neuron ); if ( !FloatUtils::isNegative( sourceLb ) ) { @@ -84,7 +82,7 @@ void DeepPolyLeakyReLUElement::execute( const Map // Symbolic upper bound: x_f <= (x_b - l) * u / ( u - l) // Concrete upper bound: x_f <= ub_b double width = sourceUb - sourceLb; - double coeff = (sourceUb - _slope * sourceLb) / width; + double coeff = ( sourceUb - _slope * sourceLb ) / width; if ( _slope <= 1 ) { @@ -137,18 +135,25 @@ void DeepPolyLeakyReLUElement::execute( const Map } } log( Stringf( "Neuron%u LB: %f b + %f, UB: %f b + %f", - i, _symbolicLb[i], _symbolicLowerBias[i], - _symbolicUb[i], _symbolicUpperBias[i] ) ); + i, + _symbolicLb[i], + _symbolicLowerBias[i], + _symbolicUb[i], + _symbolicUpperBias[i] ) ); log( Stringf( "Neuron%u LB: %f, UB: %f", i, _lb[i], _ub[i] ) ); } log( "Executing - done" ); } -void DeepPolyLeakyReLUElement::symbolicBoundInTermsOfPredecessor -( const double *symbolicLb, const double*symbolicUb, double - *symbolicLowerBias, double *symbolicUpperBias, double - *symbolicLbInTermsOfPredecessor, double *symbolicUbInTermsOfPredecessor, - unsigned targetLayerSize, DeepPolyElement *predecessor ) +void DeepPolyLeakyReLUElement::symbolicBoundInTermsOfPredecessor( + const double *symbolicLb, + const double *symbolicUb, + double *symbolicLowerBias, + double *symbolicUpperBias, + double *symbolicLbInTermsOfPredecessor, + double *symbolicUbInTermsOfPredecessor, + unsigned targetLayerSize, + DeepPolyElement *predecessor ) { log( Stringf( "Computing symbolic bounds with respect to layer %u...", predecessor->getLayerIndex() ) ); @@ -160,12 +165,9 @@ void DeepPolyLeakyReLUElement::symbolicBoundInTermsOfPredecessor */ for ( unsigned i = 0; i < _size; ++i ) { - NeuronIndex sourceIndex = *( _layer-> - getActivationSources( i ).begin() ); + NeuronIndex sourceIndex = *( _layer->getActivationSources( i ).begin() ); unsigned sourceNeuronIndex = sourceIndex._neuron; - DEBUG({ - ASSERT( predecessor->getLayerIndex() == sourceIndex._layer ); - }); + DEBUG( { ASSERT( predecessor->getLayerIndex() == sourceIndex._layer ); } ); /* Take symbolic upper bound as an example. @@ -199,7 +201,8 @@ void DeepPolyLeakyReLUElement::symbolicBoundInTermsOfPredecessor { symbolicLbInTermsOfPredecessor[newIndex] += weightLb * coeffLb; symbolicLowerBias[j] += weightLb * lowerBias; - } else + } + else { symbolicLbInTermsOfPredecessor[newIndex] += weightLb * coeffUb; symbolicLowerBias[j] += weightLb * upperBias; @@ -211,7 +214,8 @@ void DeepPolyLeakyReLUElement::symbolicBoundInTermsOfPredecessor { symbolicUbInTermsOfPredecessor[newIndex] += weightUb * coeffUb; symbolicUpperBias[j] += weightUb * upperBias; - } else + } + else { symbolicUbInTermsOfPredecessor[newIndex] += weightUb * coeffLb; symbolicUpperBias[j] += weightUb * lowerBias; diff --git a/src/nlr/DeepPolyLeakyReLUElement.h b/src/nlr/DeepPolyLeakyReLUElement.h index 01c3407439..f15a710e47 100644 --- a/src/nlr/DeepPolyLeakyReLUElement.h +++ b/src/nlr/DeepPolyLeakyReLUElement.h @@ -20,6 +20,7 @@ #include "Layer.h" #include "MStringf.h" #include "NLRError.h" + #include namespace NLR { @@ -30,14 +31,16 @@ class DeepPolyLeakyReLUElement : public DeepPolyElement DeepPolyLeakyReLUElement( Layer *layer ); ~DeepPolyLeakyReLUElement(); - void execute( const Map - &deepPolyElementsBefore ); + void execute( const Map &deepPolyElementsBefore ); - void symbolicBoundInTermsOfPredecessor - ( const double *symbolicLb, const double*symbolicUb, double - *symbolicLowerBias, double *symbolicUpperBias, double - *symbolicLbInTermsOfPredecessor, double *symbolicUbInTermsOfPredecessor, - unsigned targetLayerSize, DeepPolyElement *predecessor ); + void symbolicBoundInTermsOfPredecessor( const double *symbolicLb, + const double *symbolicUb, + double *symbolicLowerBias, + double *symbolicUpperBias, + double *symbolicLbInTermsOfPredecessor, + double *symbolicUbInTermsOfPredecessor, + unsigned targetLayerSize, + DeepPolyElement *predecessor ); private: double _slope; diff --git a/src/nlr/DeepPolyMaxPoolElement.cpp b/src/nlr/DeepPolyMaxPoolElement.cpp index fd47da1c41..22b5547d9b 100644 --- a/src/nlr/DeepPolyMaxPoolElement.cpp +++ b/src/nlr/DeepPolyMaxPoolElement.cpp @@ -14,6 +14,7 @@ **/ #include "DeepPolyMaxPoolElement.h" + #include "FloatUtils.h" namespace NLR { @@ -30,8 +31,8 @@ DeepPolyMaxPoolElement::~DeepPolyMaxPoolElement() freeMemoryIfNeeded(); } -void DeepPolyMaxPoolElement::execute( const Map - &deepPolyElementsBefore ) +void DeepPolyMaxPoolElement::execute( + const Map &deepPolyElementsBefore ) { log( "Executing..." ); ASSERT( hasPredecessor() ); @@ -52,13 +53,10 @@ void DeepPolyMaxPoolElement::execute( const Map Map sourceUbs; for ( const auto &sourceIndex : sources ) { - DeepPolyElement *predecessor = - deepPolyElementsBefore[sourceIndex._layer]; - double sourceLb = predecessor->getLowerBound - ( sourceIndex._neuron ); + DeepPolyElement *predecessor = deepPolyElementsBefore[sourceIndex._layer]; + double sourceLb = predecessor->getLowerBound( sourceIndex._neuron ); sourceLbs[sourceIndex] = sourceLb; - double sourceUb = predecessor->getUpperBound - ( sourceIndex._neuron ); + double sourceUb = predecessor->getUpperBound( sourceIndex._neuron ); sourceUbs[sourceIndex] = sourceUb; if ( maxLowerBound < sourceLb ) @@ -88,7 +86,9 @@ void DeepPolyMaxPoolElement::execute( const Map if ( phaseFixed ) { log( Stringf( "Neuron %u_%u fixed to Neuron %u_%u", - _layerIndex, i, indexOfMaxLowerBound._layer, + _layerIndex, + i, + indexOfMaxLowerBound._layer, indexOfMaxLowerBound._neuron ) ); // Phase fixed // Symbolic bound: x_b <= x_f <= x_b @@ -99,8 +99,7 @@ void DeepPolyMaxPoolElement::execute( const Map } else { - log( Stringf( "Neuron %u_%u not fixed", - _layerIndex, i ) ); + log( Stringf( "Neuron %u_%u not fixed", _layerIndex, i ) ); // MaxPool not fixed // Symbolic bounds: x_b <= x_f <= maxUpperBound // Concrete bounds: lb_b <= x_f <= maxUpperBound @@ -114,20 +113,22 @@ void DeepPolyMaxPoolElement::execute( const Map log( "Executing - done" ); } -void DeepPolyMaxPoolElement::symbolicBoundInTermsOfPredecessor -( const double *symbolicLb, const double*symbolicUb, double - *symbolicLowerBias, double *symbolicUpperBias, double - *symbolicLbInTermsOfPredecessor, double *symbolicUbInTermsOfPredecessor, - unsigned targetLayerSize, DeepPolyElement *predecessor ) +void DeepPolyMaxPoolElement::symbolicBoundInTermsOfPredecessor( + const double *symbolicLb, + const double *symbolicUb, + double *symbolicLowerBias, + double *symbolicUpperBias, + double *symbolicLbInTermsOfPredecessor, + double *symbolicUbInTermsOfPredecessor, + unsigned targetLayerSize, + DeepPolyElement *predecessor ) { log( Stringf( "Computing symbolic bounds with respect to layer %u...", predecessor->getLayerIndex() ) ); unsigned predecessorSize = predecessor->getSize(); - std::fill_n( symbolicLbInTermsOfPredecessor, targetLayerSize * - predecessorSize, 0 ); - std::fill_n( symbolicUbInTermsOfPredecessor, targetLayerSize * - predecessorSize, 0 ); + std::fill_n( symbolicLbInTermsOfPredecessor, targetLayerSize * predecessorSize, 0 ); + std::fill_n( symbolicUbInTermsOfPredecessor, targetLayerSize * predecessorSize, 0 ); /* We have the symbolic bound of the target layer in terms of the @@ -136,11 +137,10 @@ void DeepPolyMaxPoolElement::symbolicBoundInTermsOfPredecessor */ for ( unsigned i = 0; i < _size; ++i ) { - DEBUG({ - NeuronIndex sourceIndex = *( _layer-> - getActivationSources( i ).begin() ); - ASSERT( predecessor->getLayerIndex() == sourceIndex._layer ); - }); + DEBUG( { + NeuronIndex sourceIndex = *( _layer->getActivationSources( i ).begin() ); + ASSERT( predecessor->getLayerIndex() == sourceIndex._layer ); + } ); /* Take symbolic upper bound as an example. @@ -159,11 +159,11 @@ void DeepPolyMaxPoolElement::symbolicBoundInTermsOfPredecessor // b_sourceIndex <= f_i <= maxUpperBound NeuronIndex sourceNeuronIndex = _sourceIndexForSymbolicBounds[i]; ASSERT( sourceNeuronIndex._layer == predecessor->getLayerIndex() ); - unsigned sourceIndex = sourceNeuronIndex._neuron; + unsigned sourceIndex = sourceNeuronIndex._neuron; ASSERT( sourceIndex < predecessorSize ); // coeffLb = 1 // lowerBias = 0 - bool phaseFixed = _phaseFixed[i]; + bool phaseFixed = _phaseFixed[i]; double coeffUb = phaseFixed ? 1 : 0; double upperBias = phaseFixed ? 0 : _ub[i]; @@ -180,14 +180,12 @@ void DeepPolyMaxPoolElement::symbolicBoundInTermsOfPredecessor double weightLb = symbolicLb[indexInOldSymbolicBound]; if ( weightLb >= 0 ) { - symbolicLbInTermsOfPredecessor[indexInNewSymbolicBound] += - weightLb; + symbolicLbInTermsOfPredecessor[indexInNewSymbolicBound] += weightLb; // symbolicLowerBias[j] += weightLb * lowerBias; } else { - symbolicLbInTermsOfPredecessor[indexInNewSymbolicBound] += - weightLb * coeffUb; + symbolicLbInTermsOfPredecessor[indexInNewSymbolicBound] += weightLb * coeffUb; symbolicLowerBias[j] += weightLb * upperBias; } @@ -195,14 +193,13 @@ void DeepPolyMaxPoolElement::symbolicBoundInTermsOfPredecessor double weightUb = symbolicUb[indexInOldSymbolicBound]; if ( weightUb >= 0 ) { - symbolicUbInTermsOfPredecessor[indexInNewSymbolicBound] += - weightUb * coeffUb; + symbolicUbInTermsOfPredecessor[indexInNewSymbolicBound] += weightUb * coeffUb; symbolicUpperBias[j] += weightUb * upperBias; - } else + } + else { - symbolicUbInTermsOfPredecessor[indexInNewSymbolicBound] += - weightUb; - //symbolicUpperBias[j] += weightUb * lowerBias; + symbolicUbInTermsOfPredecessor[indexInNewSymbolicBound] += weightUb; + // symbolicUpperBias[j] += weightUb * lowerBias; } } } diff --git a/src/nlr/DeepPolyMaxPoolElement.h b/src/nlr/DeepPolyMaxPoolElement.h index b2eb68719e..f7db26a9a3 100644 --- a/src/nlr/DeepPolyMaxPoolElement.h +++ b/src/nlr/DeepPolyMaxPoolElement.h @@ -19,10 +19,10 @@ #include "DeepPolyElement.h" #include "Layer.h" #include "MStringf.h" +#include "Map.h" #include "NLRError.h" -#include -#include "Map.h" +#include namespace NLR { @@ -32,17 +32,18 @@ class DeepPolyMaxPoolElement : public DeepPolyElement DeepPolyMaxPoolElement( Layer *layer ); ~DeepPolyMaxPoolElement(); - void execute( const Map - &deepPolyElementsBefore ); + void execute( const Map &deepPolyElementsBefore ); - void symbolicBoundInTermsOfPredecessor - ( const double *symbolicLb, const double*symbolicUb, double - *symbolicLowerBias, double *symbolicUpperBias, double - *symbolicLbInTermsOfPredecessor, double *symbolicUbInTermsOfPredecessor, - unsigned targetLayerSize, DeepPolyElement *predecessor ); + void symbolicBoundInTermsOfPredecessor( const double *symbolicLb, + const double *symbolicUb, + double *symbolicLowerBias, + double *symbolicUpperBias, + double *symbolicLbInTermsOfPredecessor, + double *symbolicUbInTermsOfPredecessor, + unsigned targetLayerSize, + DeepPolyElement *predecessor ); private: - /* The index of the source variable used in the symbolic bounds. */ diff --git a/src/nlr/DeepPolyReLUElement.cpp b/src/nlr/DeepPolyReLUElement.cpp index ce2fa0f060..aca82d8f8b 100644 --- a/src/nlr/DeepPolyReLUElement.cpp +++ b/src/nlr/DeepPolyReLUElement.cpp @@ -1,4 +1,4 @@ - /********************* */ +/********************* */ /*! \file DeepPolyReLUElement.cpp ** \verbatim ** Top contributors (to current version): @@ -14,6 +14,7 @@ **/ #include "DeepPolyReLUElement.h" + #include "FloatUtils.h" namespace NLR { @@ -30,8 +31,7 @@ DeepPolyReLUElement::~DeepPolyReLUElement() freeMemoryIfNeeded(); } -void DeepPolyReLUElement::execute( const Map - &deepPolyElementsBefore ) +void DeepPolyReLUElement::execute( const Map &deepPolyElementsBefore ) { log( "Executing..." ); ASSERT( hasPredecessor() ); @@ -42,12 +42,9 @@ void DeepPolyReLUElement::execute( const Map for ( unsigned i = 0; i < _size; ++i ) { NeuronIndex sourceIndex = *( _layer->getActivationSources( i ).begin() ); - DeepPolyElement *predecessor = - deepPolyElementsBefore[sourceIndex._layer]; - double sourceLb = predecessor->getLowerBound - ( sourceIndex._neuron ); - double sourceUb = predecessor->getUpperBound - ( sourceIndex._neuron ); + DeepPolyElement *predecessor = deepPolyElementsBefore[sourceIndex._layer]; + double sourceLb = predecessor->getLowerBound( sourceIndex._neuron ); + double sourceUb = predecessor->getUpperBound( sourceIndex._neuron ); if ( !FloatUtils::isNegative( sourceLb ) ) { @@ -110,18 +107,24 @@ void DeepPolyReLUElement::execute( const Map } } log( Stringf( "Neuron%u LB: %f b + %f, UB: %f b + %f", - i, _symbolicLb[i], _symbolicLowerBias[i], - _symbolicUb[i], _symbolicUpperBias[i] ) ); + i, + _symbolicLb[i], + _symbolicLowerBias[i], + _symbolicUb[i], + _symbolicUpperBias[i] ) ); log( Stringf( "Neuron%u LB: %f, UB: %f", i, _lb[i], _ub[i] ) ); } log( "Executing - done" ); } -void DeepPolyReLUElement::symbolicBoundInTermsOfPredecessor -( const double *symbolicLb, const double*symbolicUb, double - *symbolicLowerBias, double *symbolicUpperBias, double - *symbolicLbInTermsOfPredecessor, double *symbolicUbInTermsOfPredecessor, - unsigned targetLayerSize, DeepPolyElement *predecessor ) +void DeepPolyReLUElement::symbolicBoundInTermsOfPredecessor( const double *symbolicLb, + const double *symbolicUb, + double *symbolicLowerBias, + double *symbolicUpperBias, + double *symbolicLbInTermsOfPredecessor, + double *symbolicUbInTermsOfPredecessor, + unsigned targetLayerSize, + DeepPolyElement *predecessor ) { log( Stringf( "Computing symbolic bounds with respect to layer %u...", predecessor->getLayerIndex() ) ); @@ -133,12 +136,9 @@ void DeepPolyReLUElement::symbolicBoundInTermsOfPredecessor */ for ( unsigned i = 0; i < _size; ++i ) { - NeuronIndex sourceIndex = *( _layer-> - getActivationSources( i ).begin() ); + NeuronIndex sourceIndex = *( _layer->getActivationSources( i ).begin() ); unsigned sourceNeuronIndex = sourceIndex._neuron; - DEBUG({ - ASSERT( predecessor->getLayerIndex() == sourceIndex._layer ); - }); + DEBUG( { ASSERT( predecessor->getLayerIndex() == sourceIndex._layer ); } ); /* Take symbolic upper bound as an example. @@ -172,7 +172,8 @@ void DeepPolyReLUElement::symbolicBoundInTermsOfPredecessor { symbolicLbInTermsOfPredecessor[newIndex] += weightLb * coeffLb; symbolicLowerBias[j] += weightLb * lowerBias; - } else + } + else { symbolicLbInTermsOfPredecessor[newIndex] += weightLb * coeffUb; symbolicLowerBias[j] += weightLb * upperBias; @@ -184,7 +185,8 @@ void DeepPolyReLUElement::symbolicBoundInTermsOfPredecessor { symbolicUbInTermsOfPredecessor[newIndex] += weightUb * coeffUb; symbolicUpperBias[j] += weightUb * upperBias; - } else + } + else { symbolicUbInTermsOfPredecessor[newIndex] += weightUb * coeffLb; symbolicUpperBias[j] += weightUb * lowerBias; diff --git a/src/nlr/DeepPolyReLUElement.h b/src/nlr/DeepPolyReLUElement.h index d679d305e5..d58c78812e 100644 --- a/src/nlr/DeepPolyReLUElement.h +++ b/src/nlr/DeepPolyReLUElement.h @@ -20,6 +20,7 @@ #include "Layer.h" #include "MStringf.h" #include "NLRError.h" + #include namespace NLR { @@ -30,17 +31,18 @@ class DeepPolyReLUElement : public DeepPolyElement DeepPolyReLUElement( Layer *layer ); ~DeepPolyReLUElement(); - void execute( const Map - &deepPolyElementsBefore ); + void execute( const Map &deepPolyElementsBefore ); - void symbolicBoundInTermsOfPredecessor - ( const double *symbolicLb, const double*symbolicUb, double - *symbolicLowerBias, double *symbolicUpperBias, double - *symbolicLbInTermsOfPredecessor, double *symbolicUbInTermsOfPredecessor, - unsigned targetLayerSize, DeepPolyElement *predecessor ); + void symbolicBoundInTermsOfPredecessor( const double *symbolicLb, + const double *symbolicUb, + double *symbolicLowerBias, + double *symbolicUpperBias, + double *symbolicLbInTermsOfPredecessor, + double *symbolicUbInTermsOfPredecessor, + unsigned targetLayerSize, + DeepPolyElement *predecessor ); private: - void allocateMemory(); void freeMemoryIfNeeded(); void log( const String &message ); diff --git a/src/nlr/DeepPolySigmoidElement.cpp b/src/nlr/DeepPolySigmoidElement.cpp index 71e8b4d178..86a915e88c 100644 --- a/src/nlr/DeepPolySigmoidElement.cpp +++ b/src/nlr/DeepPolySigmoidElement.cpp @@ -1,4 +1,4 @@ - /********************* */ +/********************* */ /*! \file DeepPolySigmoidElement.cpp ** \verbatim ** Top contributors (to current version): @@ -14,6 +14,7 @@ **/ #include "DeepPolySigmoidElement.h" + #include "FloatUtils.h" #include "SigmoidConstraint.h" @@ -31,8 +32,8 @@ DeepPolySigmoidElement::~DeepPolySigmoidElement() freeMemoryIfNeeded(); } -void DeepPolySigmoidElement::execute( const Map - &deepPolyElementsBefore ) +void DeepPolySigmoidElement::execute( + const Map &deepPolyElementsBefore ) { log( "Executing..." ); ASSERT( hasPredecessor() ); @@ -43,12 +44,9 @@ void DeepPolySigmoidElement::execute( const Map for ( unsigned i = 0; i < _size; ++i ) { NeuronIndex sourceIndex = *( _layer->getActivationSources( i ).begin() ); - DeepPolyElement *predecessor = - deepPolyElementsBefore[sourceIndex._layer]; - double sourceLb = predecessor->getLowerBound - ( sourceIndex._neuron ); - double sourceUb = predecessor->getUpperBound - ( sourceIndex._neuron ); + DeepPolyElement *predecessor = deepPolyElementsBefore[sourceIndex._layer]; + double sourceLb = predecessor->getLowerBound( sourceIndex._neuron ); + double sourceUb = predecessor->getUpperBound( sourceIndex._neuron ); _ub[i] = SigmoidConstraint::sigmoid( sourceUb ); _lb[i] = SigmoidConstraint::sigmoid( sourceLb ); @@ -75,7 +73,8 @@ void DeepPolySigmoidElement::execute( const Map else { _symbolicLb[i] = lambdaPrime; - _symbolicLowerBias[i] = SigmoidConstraint::sigmoid( sourceLb ) - lambdaPrime * sourceLb; + _symbolicLowerBias[i] = + SigmoidConstraint::sigmoid( sourceLb ) - lambdaPrime * sourceLb; } // update upper bound @@ -87,23 +86,31 @@ void DeepPolySigmoidElement::execute( const Map else { _symbolicUb[i] = lambdaPrime; - _symbolicUpperBias[i] = SigmoidConstraint::sigmoid( sourceUb ) - lambdaPrime * sourceUb; + _symbolicUpperBias[i] = + SigmoidConstraint::sigmoid( sourceUb ) - lambdaPrime * sourceUb; } } log( Stringf( "Neuron%u LB: %f b + %f, UB: %f b + %f", - i, _symbolicLb[i], _symbolicLowerBias[i], - _symbolicUb[i], _symbolicUpperBias[i] ) ); + i, + _symbolicLb[i], + _symbolicLowerBias[i], + _symbolicUb[i], + _symbolicUpperBias[i] ) ); log( Stringf( "Neuron%u LB: %f, UB: %f", i, _lb[i], _ub[i] ) ); } log( "Executing - done" ); } -void DeepPolySigmoidElement::symbolicBoundInTermsOfPredecessor -( const double *symbolicLb, const double*symbolicUb, double - *symbolicLowerBias, double *symbolicUpperBias, double - *symbolicLbInTermsOfPredecessor, double *symbolicUbInTermsOfPredecessor, - unsigned targetLayerSize, DeepPolyElement *predecessor ) +void DeepPolySigmoidElement::symbolicBoundInTermsOfPredecessor( + const double *symbolicLb, + const double *symbolicUb, + double *symbolicLowerBias, + double *symbolicUpperBias, + double *symbolicLbInTermsOfPredecessor, + double *symbolicUbInTermsOfPredecessor, + unsigned targetLayerSize, + DeepPolyElement *predecessor ) { log( Stringf( "Computing symbolic bounds with respect to layer %u...", predecessor->getLayerIndex() ) ); @@ -115,12 +122,9 @@ void DeepPolySigmoidElement::symbolicBoundInTermsOfPredecessor */ for ( unsigned i = 0; i < _size; ++i ) { - NeuronIndex sourceIndex = *( _layer-> - getActivationSources( i ).begin() ); + NeuronIndex sourceIndex = *( _layer->getActivationSources( i ).begin() ); unsigned sourceNeuronIndex = sourceIndex._neuron; - DEBUG({ - ASSERT( predecessor->getLayerIndex() == sourceIndex._layer ); - }); + DEBUG( { ASSERT( predecessor->getLayerIndex() == sourceIndex._layer ); } ); /* Take symbolic upper bound as an example. @@ -154,7 +158,8 @@ void DeepPolySigmoidElement::symbolicBoundInTermsOfPredecessor { symbolicLbInTermsOfPredecessor[newIndex] += weightLb * coeffLb; symbolicLowerBias[j] += weightLb * lowerBias; - } else + } + else { symbolicLbInTermsOfPredecessor[newIndex] += weightLb * coeffUb; symbolicLowerBias[j] += weightLb * upperBias; @@ -166,7 +171,8 @@ void DeepPolySigmoidElement::symbolicBoundInTermsOfPredecessor { symbolicUbInTermsOfPredecessor[newIndex] += weightUb * coeffUb; symbolicUpperBias[j] += weightUb * upperBias; - } else + } + else { symbolicUbInTermsOfPredecessor[newIndex] += weightUb * coeffLb; symbolicUpperBias[j] += weightUb * lowerBias; diff --git a/src/nlr/DeepPolySigmoidElement.h b/src/nlr/DeepPolySigmoidElement.h index 27b0921ac0..cc2279fef6 100644 --- a/src/nlr/DeepPolySigmoidElement.h +++ b/src/nlr/DeepPolySigmoidElement.h @@ -20,6 +20,7 @@ #include "Layer.h" #include "MStringf.h" #include "NLRError.h" + #include namespace NLR { @@ -30,17 +31,18 @@ class DeepPolySigmoidElement : public DeepPolyElement DeepPolySigmoidElement( Layer *layer ); ~DeepPolySigmoidElement(); - void execute( const Map - &deepPolyElementsBefore ); + void execute( const Map &deepPolyElementsBefore ); - void symbolicBoundInTermsOfPredecessor - ( const double *symbolicLb, const double*symbolicUb, double - *symbolicLowerBias, double *symbolicUpperBias, double - *symbolicLbInTermsOfPredecessor, double *symbolicUbInTermsOfPredecessor, - unsigned targetLayerSize, DeepPolyElement *predecessor ); + void symbolicBoundInTermsOfPredecessor( const double *symbolicLb, + const double *symbolicUb, + double *symbolicLowerBias, + double *symbolicUpperBias, + double *symbolicLbInTermsOfPredecessor, + double *symbolicUbInTermsOfPredecessor, + unsigned targetLayerSize, + DeepPolyElement *predecessor ); private: - void allocateMemory(); void freeMemoryIfNeeded(); void log( const String &message ); diff --git a/src/nlr/DeepPolySignElement.cpp b/src/nlr/DeepPolySignElement.cpp index 2c0bccb681..632897079a 100644 --- a/src/nlr/DeepPolySignElement.cpp +++ b/src/nlr/DeepPolySignElement.cpp @@ -14,6 +14,7 @@ **/ #include "DeepPolySignElement.h" + #include "FloatUtils.h" namespace NLR { @@ -30,8 +31,7 @@ DeepPolySignElement::~DeepPolySignElement() freeMemoryIfNeeded(); } -void DeepPolySignElement::execute( const Map - &deepPolyElementsBefore ) +void DeepPolySignElement::execute( const Map &deepPolyElementsBefore ) { log( "Executing..." ); ASSERT( hasPredecessor() ); @@ -42,12 +42,9 @@ void DeepPolySignElement::execute( const Map for ( unsigned i = 0; i < _size; ++i ) { NeuronIndex sourceIndex = *( _layer->getActivationSources( i ).begin() ); - DeepPolyElement *predecessor = - deepPolyElementsBefore[sourceIndex._layer]; - double sourceLb = predecessor->getLowerBound - ( sourceIndex._neuron ); - double sourceUb = predecessor->getUpperBound - ( sourceIndex._neuron ); + DeepPolyElement *predecessor = deepPolyElementsBefore[sourceIndex._layer]; + double sourceLb = predecessor->getLowerBound( sourceIndex._neuron ); + double sourceUb = predecessor->getUpperBound( sourceIndex._neuron ); if ( !FloatUtils::isNegative( sourceLb ) ) { @@ -92,18 +89,24 @@ void DeepPolySignElement::execute( const Map _lb[i] = -1; } log( Stringf( "Neuron%u LB: %f b + %f, UB: %f b + %f", - i, _symbolicLb[i], _symbolicLowerBias[i], - _symbolicUb[i], _symbolicUpperBias[i] ) ); + i, + _symbolicLb[i], + _symbolicLowerBias[i], + _symbolicUb[i], + _symbolicUpperBias[i] ) ); log( Stringf( "Neuron%u LB: %f, UB: %f", i, _lb[i], _ub[i] ) ); } log( "Executing - done" ); } -void DeepPolySignElement::symbolicBoundInTermsOfPredecessor -( const double *symbolicLb, const double*symbolicUb, double - *symbolicLowerBias, double *symbolicUpperBias, double - *symbolicLbInTermsOfPredecessor, double *symbolicUbInTermsOfPredecessor, - unsigned targetLayerSize, DeepPolyElement *predecessor ) +void DeepPolySignElement::symbolicBoundInTermsOfPredecessor( const double *symbolicLb, + const double *symbolicUb, + double *symbolicLowerBias, + double *symbolicUpperBias, + double *symbolicLbInTermsOfPredecessor, + double *symbolicUbInTermsOfPredecessor, + unsigned targetLayerSize, + DeepPolyElement *predecessor ) { log( Stringf( "Computing symbolic bounds with respect to layer %u...", predecessor->getLayerIndex() ) ); @@ -115,12 +118,9 @@ void DeepPolySignElement::symbolicBoundInTermsOfPredecessor */ for ( unsigned i = 0; i < _size; ++i ) { - NeuronIndex sourceIndex = *( _layer-> - getActivationSources( i ).begin() ); + NeuronIndex sourceIndex = *( _layer->getActivationSources( i ).begin() ); unsigned sourceNeuronIndex = sourceIndex._neuron; - DEBUG({ - ASSERT( predecessor->getLayerIndex() == sourceIndex._layer ); - }); + DEBUG( { ASSERT( predecessor->getLayerIndex() == sourceIndex._layer ); } ); /* Take symbolic upper bound as an example. @@ -154,7 +154,8 @@ void DeepPolySignElement::symbolicBoundInTermsOfPredecessor { symbolicLbInTermsOfPredecessor[newIndex] += weightLb * coeffLb; symbolicLowerBias[j] += weightLb * lowerBias; - } else + } + else { symbolicLbInTermsOfPredecessor[newIndex] += weightLb * coeffUb; symbolicLowerBias[j] += weightLb * upperBias; @@ -166,7 +167,8 @@ void DeepPolySignElement::symbolicBoundInTermsOfPredecessor { symbolicUbInTermsOfPredecessor[newIndex] += weightUb * coeffUb; symbolicUpperBias[j] += weightUb * upperBias; - } else + } + else { symbolicUbInTermsOfPredecessor[newIndex] += weightUb * coeffLb; symbolicUpperBias[j] += weightUb * lowerBias; diff --git a/src/nlr/DeepPolySignElement.h b/src/nlr/DeepPolySignElement.h index cd0597ca1c..f39f84bd4a 100644 --- a/src/nlr/DeepPolySignElement.h +++ b/src/nlr/DeepPolySignElement.h @@ -20,6 +20,7 @@ #include "Layer.h" #include "MStringf.h" #include "NLRError.h" + #include namespace NLR { @@ -30,17 +31,18 @@ class DeepPolySignElement : public DeepPolyElement DeepPolySignElement( Layer *layer ); ~DeepPolySignElement(); - void execute( const Map - &deepPolyElementsBefore ); + void execute( const Map &deepPolyElementsBefore ); - void symbolicBoundInTermsOfPredecessor - ( const double *symbolicLb, const double*symbolicUb, double - *symbolicLowerBias, double *symbolicUpperBias, double - *symbolicLbInTermsOfPredecessor, double *symbolicUbInTermsOfPredecessor, - unsigned targetLayerSize, DeepPolyElement *predecessor ); + void symbolicBoundInTermsOfPredecessor( const double *symbolicLb, + const double *symbolicUb, + double *symbolicLowerBias, + double *symbolicUpperBias, + double *symbolicLbInTermsOfPredecessor, + double *symbolicUbInTermsOfPredecessor, + unsigned targetLayerSize, + DeepPolyElement *predecessor ); private: - void allocateMemory(); void freeMemoryIfNeeded(); void log( const String &message ); diff --git a/src/nlr/DeepPolySoftmaxElement.cpp b/src/nlr/DeepPolySoftmaxElement.cpp index 0b412977fc..ea09f49902 100644 --- a/src/nlr/DeepPolySoftmaxElement.cpp +++ b/src/nlr/DeepPolySoftmaxElement.cpp @@ -509,8 +509,7 @@ double DeepPolySoftmaxElement::LSEUpperBound( const Vector &inputs, Vector inputTilda; SoftmaxConstraint::xTilda( inputs, inputs[i], inputTilda ); - return ( ( li * std::log( ui ) - ui * std::log( li ) ) / - ( std::log( ui ) - std::log( li ) ) - + return ( ( li * std::log( ui ) - ui * std::log( li ) ) / ( std::log( ui ) - std::log( li ) ) - ( ui - li ) / ( std::log( ui ) - std::log( li ) ) * SoftmaxConstraint::logSumOfExponential( inputTilda ) ); } diff --git a/src/nlr/DeepPolySoftmaxElement.h b/src/nlr/DeepPolySoftmaxElement.h index ed638064fc..a2ba08c03b 100644 --- a/src/nlr/DeepPolySoftmaxElement.h +++ b/src/nlr/DeepPolySoftmaxElement.h @@ -55,14 +55,14 @@ class DeepPolySoftmaxElement : public DeepPolyElement unsigned outputIndex, unsigned inputIndex ); static double LSELowerBound2( const Vector &sourceMids, - const Vector &inputLbs, - const Vector &inputUbs, - unsigned outputIndex ); + const Vector &inputLbs, + const Vector &inputUbs, + unsigned outputIndex ); static double dLSELowerBound2( const Vector &sourceMids, const Vector &inputLbs, const Vector &inputUbs, - unsigned outputIndex, - unsigned inputIndex ); + unsigned outputIndex, + unsigned inputIndex ); static double LSEUpperBound( const Vector &sourceMids, const Vector &outputLb, const Vector &outputUb, @@ -100,7 +100,7 @@ class DeepPolySoftmaxElement : public DeepPolyElement private: SoftmaxBoundType _boundType; unsigned _maxLayerSize; - double * _work; + double *_work; void allocateMemory( unsigned maxLayerSize ); void freeMemoryIfNeeded(); diff --git a/src/nlr/DeepPolyWeightedSumElement.cpp b/src/nlr/DeepPolyWeightedSumElement.cpp index 8e3cc3c8d0..026a7e15ff 100644 --- a/src/nlr/DeepPolyWeightedSumElement.cpp +++ b/src/nlr/DeepPolyWeightedSumElement.cpp @@ -14,6 +14,7 @@ **/ #include "DeepPolyWeightedSumElement.h" + #include "FloatUtils.h" #include @@ -34,8 +35,8 @@ DeepPolyWeightedSumElement::~DeepPolyWeightedSumElement() freeMemoryIfNeeded(); } -void DeepPolyWeightedSumElement::execute -( const Map &deepPolyElementsBefore ) +void DeepPolyWeightedSumElement::execute( + const Map &deepPolyElementsBefore ) { log( "Executing..." ); ASSERT( hasPredecessor() ); @@ -46,8 +47,8 @@ void DeepPolyWeightedSumElement::execute log( "Executing - done" ); } -void DeepPolyWeightedSumElement::computeBoundWithBackSubstitution -( const Map &deepPolyElementsBefore ) +void DeepPolyWeightedSumElement::computeBoundWithBackSubstitution( + const Map &deepPolyElementsBefore ) { log( "Computing bounds with back substitution..." ); @@ -70,42 +71,38 @@ void DeepPolyWeightedSumElement::computeBoundWithBackSubstitution predecessorIndex = pair.first; if ( counter < numPredecessors - 1 ) { - log( Stringf( "Adding residual from layer %u...", - predecessorIndex ) ); + log( Stringf( "Adding residual from layer %u...", predecessorIndex ) ); allocateMemoryForResidualsIfNeeded( predecessorIndex, pair.second ); const double *weights = _layer->getWeights( predecessorIndex ); - memcpy( _residualLb[predecessorIndex], weights, - _size * pair.second * sizeof(double) ); - memcpy( _residualUb[predecessorIndex], weights, - _size * pair.second * sizeof(double) ); + memcpy( + _residualLb[predecessorIndex], weights, _size * pair.second * sizeof( double ) ); + memcpy( + _residualUb[predecessorIndex], weights, _size * pair.second * sizeof( double ) ); ++counter; log( Stringf( "Adding residual from layer %u - done", pair.first ) ); } } - log( Stringf( "Computing symbolic bounds with respect to layer %u...", - predecessorIndex ) ); - DeepPolyElement *precedingElement = - deepPolyElementsBefore[predecessorIndex]; + log( Stringf( "Computing symbolic bounds with respect to layer %u...", predecessorIndex ) ); + DeepPolyElement *precedingElement = deepPolyElementsBefore[predecessorIndex]; unsigned sourceLayerSize = precedingElement->getSize(); const double *weights = _layer->getWeights( predecessorIndex ); - memcpy( _work1SymbolicLb, - weights, _size * sourceLayerSize * sizeof(double) ); - memcpy( _work1SymbolicUb, - weights, _size * sourceLayerSize * sizeof(double) ); + memcpy( _work1SymbolicLb, weights, _size * sourceLayerSize * sizeof( double ) ); + memcpy( _work1SymbolicUb, weights, _size * sourceLayerSize * sizeof( double ) ); double *bias = _layer->getBiases(); - memcpy( _workSymbolicLowerBias, bias, _size * sizeof(double) ); - memcpy( _workSymbolicUpperBias, bias, _size * sizeof(double) ); + memcpy( _workSymbolicLowerBias, bias, _size * sizeof( double ) ); + memcpy( _workSymbolicUpperBias, bias, _size * sizeof( double ) ); DeepPolyElement *currentElement = precedingElement; - concretizeSymbolicBound( _work1SymbolicLb, _work1SymbolicUb, + concretizeSymbolicBound( _work1SymbolicLb, + _work1SymbolicUb, _workSymbolicLowerBias, _workSymbolicUpperBias, - currentElement, deepPolyElementsBefore ); - log( Stringf( "Computing symbolic bounds with respect to layer %u - done", - predecessorIndex ) ); + currentElement, + deepPolyElementsBefore ); + log( Stringf( "Computing symbolic bounds with respect to layer %u - done", predecessorIndex ) ); while ( currentElement->hasPredecessor() ) { @@ -126,16 +123,17 @@ void DeepPolyWeightedSumElement::computeBoundWithBackSubstitution if ( counter < numPredecessors - 1 ) { unsigned predecessorIndex = pair.first; - log( Stringf( "Adding residual from layer %u...", - predecessorIndex ) ); - allocateMemoryForResidualsIfNeeded( predecessorIndex, - pair.second ); + log( Stringf( "Adding residual from layer %u...", predecessorIndex ) ); + allocateMemoryForResidualsIfNeeded( predecessorIndex, pair.second ); // Do we need to add bias here? - currentElement->symbolicBoundInTermsOfPredecessor - ( _work1SymbolicLb, _work1SymbolicUb, NULL, NULL, - _residualLb[predecessorIndex], - _residualUb[predecessorIndex], - _size, precedingElement ); + currentElement->symbolicBoundInTermsOfPredecessor( _work1SymbolicLb, + _work1SymbolicUb, + NULL, + NULL, + _residualLb[predecessorIndex], + _residualUb[predecessorIndex], + _size, + precedingElement ); ++counter; log( Stringf( "Adding residual from layer %u - done", pair.first ) ); } @@ -143,10 +141,14 @@ void DeepPolyWeightedSumElement::computeBoundWithBackSubstitution std::fill_n( _work2SymbolicLb, _size * precedingElement->getSize(), 0 ); std::fill_n( _work2SymbolicUb, _size * precedingElement->getSize(), 0 ); - currentElement->symbolicBoundInTermsOfPredecessor - ( _work1SymbolicLb, _work1SymbolicUb, _workSymbolicLowerBias, - _workSymbolicUpperBias, _work2SymbolicLb, _work2SymbolicUb, - _size, precedingElement ); + currentElement->symbolicBoundInTermsOfPredecessor( _work1SymbolicLb, + _work1SymbolicUb, + _workSymbolicLowerBias, + _workSymbolicUpperBias, + _work2SymbolicLb, + _work2SymbolicUb, + _size, + precedingElement ); // The symbolic lower-bound is // _work2SymbolicLb * precedingElement + residualLb1 * residualElement1 + @@ -163,21 +165,19 @@ void DeepPolyWeightedSumElement::computeBoundWithBackSubstitution _work2SymbolicUb[i] += _residualUb[predecessorIndex][i]; } _residualLayerIndices.erase( predecessorIndex ); - std::fill_n( _residualLb[predecessorIndex], - _size * precedingElement->getSize(), 0 ); - std::fill_n( _residualUb[predecessorIndex], - _size * precedingElement->getSize(), 0 ); + std::fill_n( _residualLb[predecessorIndex], _size * precedingElement->getSize(), 0 ); + std::fill_n( _residualUb[predecessorIndex], _size * precedingElement->getSize(), 0 ); log( Stringf( "merge residual from layer %u - done", predecessorIndex ) ); } - DEBUG({ - // Residual layers topologically after precedingElement should - // have been merged already. - for ( const auto &residualLayerIndex : _residualLayerIndices ) - { - ASSERT( residualLayerIndex < predecessorIndex ); - } - }); + DEBUG( { + // Residual layers topologically after precedingElement should + // have been merged already. + for ( const auto &residualLayerIndex : _residualLayerIndices ) + { + ASSERT( residualLayerIndex < predecessorIndex ); + } + } ); double *temp = _work1SymbolicLb; _work1SymbolicLb = _work2SymbolicLb; @@ -188,40 +188,43 @@ void DeepPolyWeightedSumElement::computeBoundWithBackSubstitution _work2SymbolicUb = temp; currentElement = precedingElement; - concretizeSymbolicBound( _work1SymbolicLb, _work1SymbolicUb, - _workSymbolicLowerBias, _workSymbolicUpperBias, - currentElement, deepPolyElementsBefore ); + concretizeSymbolicBound( _work1SymbolicLb, + _work1SymbolicUb, + _workSymbolicLowerBias, + _workSymbolicUpperBias, + currentElement, + deepPolyElementsBefore ); } ASSERT( _residualLayerIndices.empty() ); log( "Computing bounds with back substitution - done" ); } -void DeepPolyWeightedSumElement::concretizeSymbolicBound -( const double *symbolicLb, const double*symbolicUb, double const - *symbolicLowerBias, const double *symbolicUpperBias, DeepPolyElement - *sourceElement, const Map - &deepPolyElementsBefore ) +void DeepPolyWeightedSumElement::concretizeSymbolicBound( + const double *symbolicLb, + const double *symbolicUb, + double const *symbolicLowerBias, + const double *symbolicUpperBias, + DeepPolyElement *sourceElement, + const Map &deepPolyElementsBefore ) { log( "Concretizing bound..." ); std::fill_n( _workLb, _size, 0 ); std::fill_n( _workUb, _size, 0 ); - concretizeSymbolicBoundForSourceLayer( symbolicLb, symbolicUb, - symbolicLowerBias, symbolicUpperBias, - sourceElement ); + concretizeSymbolicBoundForSourceLayer( + symbolicLb, symbolicUb, symbolicLowerBias, symbolicUpperBias, sourceElement ); for ( const auto &residualLayerIndex : _residualLayerIndices ) { ASSERT( residualLayerIndex < sourceElement->getLayerIndex() ); - DeepPolyElement *residualElement = - deepPolyElementsBefore[residualLayerIndex]; + DeepPolyElement *residualElement = deepPolyElementsBefore[residualLayerIndex]; concretizeSymbolicBoundForSourceLayer( _residualLb[residualLayerIndex], _residualUb[residualLayerIndex], NULL, NULL, residualElement ); } - for ( unsigned i = 0; i <_size; ++i ) + for ( unsigned i = 0; i < _size; ++i ) { if ( _lb[i] < _workLb[i] ) _lb[i] = _workLb[i]; @@ -234,16 +237,18 @@ void DeepPolyWeightedSumElement::concretizeSymbolicBound log( "Concretizing bound - done" ); } -void DeepPolyWeightedSumElement::concretizeSymbolicBoundForSourceLayer -( const double *symbolicLb, const double*symbolicUb, const double - *symbolicLowerBias, const double *symbolicUpperBias, DeepPolyElement - *sourceElement ) +void DeepPolyWeightedSumElement::concretizeSymbolicBoundForSourceLayer( + const double *symbolicLb, + const double *symbolicUb, + const double *symbolicLowerBias, + const double *symbolicUpperBias, + DeepPolyElement *sourceElement ) { /* DEBUG({ log( Stringf( "Source layer: %u", sourceElement->getLayerIndex() ) ); - String s = Stringf( "Symbolic lowerbounds w.r.t. layer %u: \n ", sourceElement->getLayerIndex() ); - for ( unsigned i = 0; i <_size; ++i ) + String s = Stringf( "Symbolic lowerbounds w.r.t. layer %u: \n ", + sourceElement->getLayerIndex() ); for ( unsigned i = 0; i <_size; ++i ) { for ( unsigned j = 0; j < sourceElement->getSize(); ++j ) { @@ -254,15 +259,15 @@ void DeepPolyWeightedSumElement::concretizeSymbolicBoundForSourceLayer s += "\n"; if ( symbolicLowerBias ) { - s += Stringf( "Symbolic lower bias w.r.t. layer %u: \n ", sourceElement->getLayerIndex() ); - for ( unsigned i = 0; i <_size; ++i ) + s += Stringf( "Symbolic lower bias w.r.t. layer %u: \n ", + sourceElement->getLayerIndex() ); for ( unsigned i = 0; i <_size; ++i ) { s += Stringf( "%f ", symbolicLowerBias[i] ); } s += "\n"; } - s += Stringf( "Symbolic upperbounds w.r.t. layer %u: \n ", sourceElement->getLayerIndex() ); - for ( unsigned i = 0; i <_size; ++i ) + s += Stringf( "Symbolic upperbounds w.r.t. layer %u: \n ", + sourceElement->getLayerIndex() ); for ( unsigned i = 0; i <_size; ++i ) { for ( unsigned j = 0; j < sourceElement->getSize(); ++j ) { @@ -273,8 +278,8 @@ void DeepPolyWeightedSumElement::concretizeSymbolicBoundForSourceLayer s += "\n"; if ( symbolicUpperBias ) { - s += Stringf( "Symbolic upper bias w.r.t. layer %u: \n ", sourceElement->getLayerIndex() ); - for ( unsigned i = 0; i <_size; ++i ) + s += Stringf( "Symbolic upper bias w.r.t. layer %u: \n ", + sourceElement->getLayerIndex() ); for ( unsigned i = 0; i <_size; ++i ) { s += Stringf( "%f ", symbolicUpperBias[i] ); } @@ -287,13 +292,16 @@ void DeepPolyWeightedSumElement::concretizeSymbolicBoundForSourceLayer // Get concrete bounds for ( unsigned i = 0; i < sourceElement->getSize(); ++i ) { - double sourceLb = sourceElement->getLowerBoundFromLayer( i ) - - GlobalConfiguration::SYMBOLIC_TIGHTENING_ROUNDING_CONSTANT; - double sourceUb = sourceElement->getUpperBoundFromLayer( i ) - + GlobalConfiguration::SYMBOLIC_TIGHTENING_ROUNDING_CONSTANT; + double sourceLb = sourceElement->getLowerBoundFromLayer( i ) - + GlobalConfiguration::SYMBOLIC_TIGHTENING_ROUNDING_CONSTANT; + double sourceUb = sourceElement->getUpperBoundFromLayer( i ) + + GlobalConfiguration::SYMBOLIC_TIGHTENING_ROUNDING_CONSTANT; - log( Stringf( "Bounds of neuron%u_%u: [%f, %f]", sourceElement-> - getLayerIndex(), i, sourceLb, sourceUb ) ); + log( Stringf( "Bounds of neuron%u_%u: [%f, %f]", + sourceElement->getLayerIndex(), + i, + sourceLb, + sourceUb ) ); for ( unsigned j = 0; j < _size; ++j ) { @@ -302,7 +310,8 @@ void DeepPolyWeightedSumElement::concretizeSymbolicBoundForSourceLayer if ( weight >= 0 ) { _workLb[j] += ( weight * sourceLb ); - } else + } + else { _workLb[j] += ( weight * sourceUb ); } @@ -312,7 +321,8 @@ void DeepPolyWeightedSumElement::concretizeSymbolicBoundForSourceLayer if ( weight >= 0 ) { _workUb[j] += ( weight * sourceUb ); - } else + } + else { _workUb[j] += ( weight * sourceLb ); } @@ -329,15 +339,18 @@ void DeepPolyWeightedSumElement::concretizeSymbolicBoundForSourceLayer } -void DeepPolyWeightedSumElement::symbolicBoundInTermsOfPredecessor -( const double *symbolicLb, const double*symbolicUb, double - *symbolicLowerBias, double *symbolicUpperBias, double - *symbolicLbInTermsOfPredecessor, double *symbolicUbInTermsOfPredecessor, - unsigned targetLayerSize, DeepPolyElement *predecessor ) +void DeepPolyWeightedSumElement::symbolicBoundInTermsOfPredecessor( + const double *symbolicLb, + const double *symbolicUb, + double *symbolicLowerBias, + double *symbolicUpperBias, + double *symbolicLbInTermsOfPredecessor, + double *symbolicUbInTermsOfPredecessor, + unsigned targetLayerSize, + DeepPolyElement *predecessor ) { unsigned predecessorIndex = predecessor->getLayerIndex(); - log( Stringf( "Computing symbolic bounds with respect to layer %u...", - predecessorIndex ) ); + log( Stringf( "Computing symbolic bounds with respect to layer %u...", predecessorIndex ) ); unsigned predecessorSize = predecessor->getSize(); double *weights = _layer->getWeights( predecessorIndex ); @@ -345,27 +358,30 @@ void DeepPolyWeightedSumElement::symbolicBoundInTermsOfPredecessor // newSymbolicLb = weights * symbolicLb // newSymbolicUb = weights * symbolicUb - matrixMultiplication( weights, symbolicLb, - symbolicLbInTermsOfPredecessor, predecessorSize, - _size, targetLayerSize ); - matrixMultiplication( weights, symbolicUb, - symbolicUbInTermsOfPredecessor, predecessorSize, - _size, targetLayerSize ); + matrixMultiplication( weights, + symbolicLb, + symbolicLbInTermsOfPredecessor, + predecessorSize, + _size, + targetLayerSize ); + matrixMultiplication( weights, + symbolicUb, + symbolicUbInTermsOfPredecessor, + predecessorSize, + _size, + targetLayerSize ); // symbolicLowerBias = biases * symbolicLb // symbolicUpperBias = biases * symbolicUb - if ( symbolicLowerBias ) - matrixMultiplication( biases, symbolicLb, symbolicLowerBias, 1, - _size, targetLayerSize ); - if ( symbolicUpperBias ) - matrixMultiplication( biases, symbolicUb, symbolicUpperBias, 1, - _size, targetLayerSize ); - log( Stringf( "Computing symbolic bounds with respect to layer %u - done", - predecessorIndex ) ); + if ( symbolicLowerBias ) + matrixMultiplication( biases, symbolicLb, symbolicLowerBias, 1, _size, targetLayerSize ); + if ( symbolicUpperBias ) + matrixMultiplication( biases, symbolicUb, symbolicUpperBias, 1, _size, targetLayerSize ); + log( Stringf( "Computing symbolic bounds with respect to layer %u - done", predecessorIndex ) ); } -void DeepPolyWeightedSumElement::allocateMemoryForResidualsIfNeeded -( unsigned residualLayerIndex, unsigned residualLayerSize ) +void DeepPolyWeightedSumElement::allocateMemoryForResidualsIfNeeded( unsigned residualLayerIndex, + unsigned residualLayerSize ) { _residualLayerIndices.insert( residualLayerIndex ); unsigned matrixSize = residualLayerSize * _size; diff --git a/src/nlr/DeepPolyWeightedSumElement.h b/src/nlr/DeepPolyWeightedSumElement.h index 3e3b961fc5..d4ec1143f0 100644 --- a/src/nlr/DeepPolyWeightedSumElement.h +++ b/src/nlr/DeepPolyWeightedSumElement.h @@ -20,6 +20,7 @@ #include "Layer.h" #include "MStringf.h" #include "NLRError.h" + #include namespace NLR { @@ -27,19 +28,20 @@ namespace NLR { class DeepPolyWeightedSumElement : public DeepPolyElement { public: - DeepPolyWeightedSumElement( Layer *layer ); ~DeepPolyWeightedSumElement(); void execute( const Map &deepPolyElements ); - void symbolicBoundInTermsOfPredecessor - ( const double *symbolicLb, const double*symbolicUb, double - *symbolicLowerBias, double *symbolicUpperBias, double - *symbolicLbInTermsOfPredecessor, double *symbolicUbInTermsOfPredecessor, - unsigned targetLayerSize, DeepPolyElement *predecessor ); + void symbolicBoundInTermsOfPredecessor( const double *symbolicLb, + const double *symbolicUb, + double *symbolicLowerBias, + double *symbolicUpperBias, + double *symbolicLbInTermsOfPredecessor, + double *symbolicUbInTermsOfPredecessor, + unsigned targetLayerSize, + DeepPolyElement *predecessor ); private: - /* Memory allocated to store concrete bounds computed at different stages of back substitution. @@ -47,30 +49,30 @@ class DeepPolyWeightedSumElement : public DeepPolyElement double *_workLb; double *_workUb; - Set _residualLayerIndices; - Map _residualLb; - Map _residualUb; + Set _residualLayerIndices; + Map _residualLb; + Map _residualUb; /* Compute the concrete upper- and lower- bounds of this layer by concretizing the symbolic bounds with respect to every preceding element. */ - void computeBoundWithBackSubstitution( const Map - &deepPolyElementsBefore ); + void computeBoundWithBackSubstitution( + const Map &deepPolyElementsBefore ); /* Compute concrete bounds using symbolic bounds with respect to a sourceElement. */ - void concretizeSymbolicBound( const double *symbolicLb, const double - *symbolicUb, const double *symbolicLowerBias, + void concretizeSymbolicBound( const double *symbolicLb, + const double *symbolicUb, + const double *symbolicLowerBias, const double *symbolicUpperBias, DeepPolyElement *sourceElement, - const Map - &deepPolyElementsBefore ); + const Map &deepPolyElementsBefore ); void concretizeSymbolicBoundForSourceLayer( const double *symbolicLb, - const double*symbolicUb, + const double *symbolicUb, const double *symbolicLowerBias, const double *symbolicUpperBias, DeepPolyElement *sourceElement ); diff --git a/src/nlr/IterativePropagator.cpp b/src/nlr/IterativePropagator.cpp index bd3550e3bd..f6acb31c65 100644 --- a/src/nlr/IterativePropagator.cpp +++ b/src/nlr/IterativePropagator.cpp @@ -13,15 +13,15 @@ **/ +#include "IterativePropagator.h" + #include "Debug.h" #include "InfeasibleQueryException.h" -#include "IterativePropagator.h" #include "Layer.h" #include "MStringf.h" #include "NLRError.h" #include "Options.h" #include "TimeUtils.h" - #include "Vector.h" #include @@ -40,7 +40,8 @@ IterativePropagator::~IterativePropagator() { } -void IterativePropagator::optimizeBoundsWithIterativePropagation( const Map &layers ) +void IterativePropagator::optimizeBoundsWithIterativePropagation( + const Map &layers ) { unsigned numberOfWorkers = Options::get()->getInt( Options::NUM_WORKERS ); @@ -82,28 +83,31 @@ void IterativePropagator::optimizeBoundsWithIterativePropagation( const MapgetInt( Options::VERBOSITY ) > 0 ) - printf( "Number of tighter bounds found by Gurobi before this iteration: %u. Sign changes: %u. Cutoffs: %u\n", - tighterBoundCounter.load(), signChanges.load(), cutoffs.load() ); + printf( "Number of tighter bounds found by Gurobi before this iteration: %u. Sign " + "changes: %u. Cutoffs: %u\n", + tighterBoundCounter.load(), + signChanges.load(), + cutoffs.load() ); mtx.lock(); lastFixedNeuronFromPreviousIteration = lastFixedNeuronThisIteration; lastFixedNeuronThisIteration = lastIndex; mtx.unlock(); - DEBUG({ - std::cout << "Last fixed Neuron From Previous Iteration: " << - lastFixedNeuronFromPreviousIteration._layer << " " << - lastFixedNeuronFromPreviousIteration._neuron << std::endl; - }); + DEBUG( { + std::cout << "Last fixed Neuron From Previous Iteration: " + << lastFixedNeuronFromPreviousIteration._layer << " " + << lastFixedNeuronFromPreviousIteration._neuron << std::endl; + } ); for ( const auto ¤tLayer : layers ) { @@ -124,9 +128,8 @@ void IterativePropagator::optimizeBoundsWithIterativePropagation( const MapgetLayerIndex(), i ) ) + if ( !progressMade && lastFixedNeuronFromPreviousIteration < + NeuronIndex( layer->getLayerIndex(), i ) ) { // If we reached the last fixed neuron from the // previous iteration but this iteration hasn't fixed any neurons @@ -146,8 +149,7 @@ void IterativePropagator::optimizeBoundsWithIterativePropagation( const MapgetInt( Options::VERBOSITY ) > 1 ) - printf( "Handling layer %d neuron %d\n", - layer->getLayerIndex(), i ); + printf( "Handling layer %d neuron %d\n", layer->getLayerIndex(), i ); if ( infeasible ) { @@ -168,23 +170,29 @@ void IterativePropagator::optimizeBoundsWithIterativePropagation( const MapresetModel(); mtx.lock(); - _milpFormulator.createMILPEncoding - ( layers, *freeSolver, _layerOwner->getNumberOfLayers() ); + _milpFormulator.createMILPEncoding( + layers, *freeSolver, _layerOwner->getNumberOfLayers() ); mtx.unlock(); // spawn a thread to tighten the bounds for the current variable - ThreadArgument argument( freeSolver, layer, - i, currentLb, currentUb, - _cutoffInUse, _cutoffValue, - _layerOwner, std::ref( freeSolvers ), - std::ref( mtx ), std::ref( infeasible ), + ThreadArgument argument( freeSolver, + layer, + i, + currentLb, + currentUb, + _cutoffInUse, + _cutoffValue, + _layerOwner, + std::ref( freeSolvers ), + std::ref( mtx ), + std::ref( infeasible ), std::ref( tighterBoundCounter ), std::ref( signChanges ), std::ref( cutoffs ), &lastFixedNeuronThisIteration ); - threads[solverToIndex[freeSolver]] = boost::thread - ( tightenSingleVariableBounds, argument ); + threads[solverToIndex[freeSolver]] = + boost::thread( tightenSingleVariableBounds, argument ); } } @@ -194,16 +202,25 @@ void IterativePropagator::optimizeBoundsWithIterativePropagation( const MapgetInt( Options::VERBOSITY ) > 0 ) - printf( "Number of tighter bounds found by Gurobi after this iteration: %u. Sign changes: %u. Cutoffs: %u\n", - tighterBoundCounter.load(), signChanges.load(), cutoffs.load() ); + printf( "Number of tighter bounds found by Gurobi after this iteration: %u. Sign " + "changes: %u. Cutoffs: %u\n", + tighterBoundCounter.load(), + signChanges.load(), + cutoffs.load() ); } while ( !shouldQuit ); gurobiEnd = TimeUtils::sampleMicro(); - IterativePropagator_LOG( Stringf( "Number of tighter bounds found by Gurobi: %u. Sign changes: %u. Cutoffs: %u\n", - tighterBoundCounter.load(), signChanges.load(), cutoffs.load() ).ascii() ); - IterativePropagator_LOG( Stringf( "Seconds spent Gurobiing: %llu\n", TimeUtils::timePassed( gurobiStart, gurobiEnd ) / 1000000 ).ascii() ); + IterativePropagator_LOG( + Stringf( "Number of tighter bounds found by Gurobi: %u. Sign changes: %u. Cutoffs: %u\n", + tighterBoundCounter.load(), + signChanges.load(), + cutoffs.load() ) + .ascii() ); + IterativePropagator_LOG( Stringf( "Seconds spent Gurobiing: %llu\n", + TimeUtils::timePassed( gurobiStart, gurobiEnd ) / 1000000 ) + .ascii() ); clearSolverQueue( freeSolvers ); @@ -218,10 +235,11 @@ void IterativePropagator::setCutoff( double cutoff ) } -double IterativePropagator::optimizeWithGurobi( GurobiWrapper &gurobi, MinOrMax - minOrMax, String variableName, - double cutoffValue, - std::atomic_bool *infeasible ) +double IterativePropagator::optimizeWithGurobi( GurobiWrapper &gurobi, + MinOrMax minOrMax, + String variableName, + double cutoffValue, + std::atomic_bool *infeasible ) { List terms; terms.append( GurobiWrapper::Term( 1, variableName ) ); @@ -281,7 +299,7 @@ void IterativePropagator::tightenSingleVariableBounds( ThreadArgument &argument GurobiWrapper *gurobi = argument._gurobi; enqueueSolver( freeSolvers, gurobi ); } - catch ( boost::thread_interrupted& ) + catch ( boost::thread_interrupted & ) { enqueueSolver( argument._freeSolvers, argument._gurobi ); } @@ -306,30 +324,27 @@ bool IterativePropagator::tightenSingleVariableLowerBounds( ThreadArgument &argu unsigned variable = layer->neuronToVariable( index ); Stringf variableName( "x%u", variable ); gurobi->reset(); - double lb = optimizeWithGurobi( *gurobi, MinOrMax::MIN, variableName, - cutoffValue, &infeasible ); + double lb = + optimizeWithGurobi( *gurobi, MinOrMax::MIN, variableName, cutoffValue, &infeasible ); // Store the new bound if it is tighter if ( lb > currentLb ) { - if ( FloatUtils::isNegative( currentLb ) && - !FloatUtils::isNegative( lb ) ) + if ( FloatUtils::isNegative( currentLb ) && !FloatUtils::isNegative( lb ) ) { IterativePropagator_LOG( Stringf( "Neuron(%d, %d) new lower bound non-nagative!", - layer->getLayerIndex(), index - ).ascii() ); + layer->getLayerIndex(), + index ) + .ascii() ); ++signChanges; mtx.lock(); - *lastFixedNeuron = NeuronIndex( layer->getLayerIndex(), - index ); + *lastFixedNeuron = NeuronIndex( layer->getLayerIndex(), index ); mtx.unlock(); } mtx.lock(); layer->setLb( index, lb ); - layerOwner->receiveTighterBound( Tightening( variable, - lb, - Tightening::LB ) ); + layerOwner->receiveTighterBound( Tightening( variable, lb, Tightening::LB ) ); mtx.unlock(); ++tighterBoundCounter; @@ -362,30 +377,27 @@ bool IterativePropagator::tightenSingleVariableUpperBounds( ThreadArgument &argu unsigned variable = layer->neuronToVariable( index ); Stringf variableName( "x%u", variable ); gurobi->reset(); - double ub = optimizeWithGurobi( *gurobi, MinOrMax::MAX, variableName, - cutoffValue, &infeasible ); + double ub = + optimizeWithGurobi( *gurobi, MinOrMax::MAX, variableName, cutoffValue, &infeasible ); // Store the new bound if it is tighter if ( ub < currentUb ) { - if ( FloatUtils::isPositive( currentUb ) && - !FloatUtils::isPositive( ub ) ) + if ( FloatUtils::isPositive( currentUb ) && !FloatUtils::isPositive( ub ) ) { IterativePropagator_LOG( Stringf( "Neuron(%d, %d) new upper bound non-positive!", - layer->getLayerIndex(), index - ).ascii() ); + layer->getLayerIndex(), + index ) + .ascii() ); ++signChanges; mtx.lock(); - *lastFixedNeuron = NeuronIndex( layer->getLayerIndex(), - index ); + *lastFixedNeuron = NeuronIndex( layer->getLayerIndex(), index ); mtx.unlock(); } mtx.lock(); layer->setUb( index, ub ); - layerOwner->receiveTighterBound( Tightening( variable, - ub, - Tightening::UB ) ); + layerOwner->receiveTighterBound( Tightening( variable, ub, Tightening::UB ) ); mtx.unlock(); ++tighterBoundCounter; diff --git a/src/nlr/IterativePropagator.h b/src/nlr/IterativePropagator.h index cb29cfbd37..be6691d99c 100644 --- a/src/nlr/IterativePropagator.h +++ b/src/nlr/IterativePropagator.h @@ -26,7 +26,8 @@ namespace NLR { -#define IterativePropagator_LOG(x, ...) LOG(GlobalConfiguration::PREPROCESSOR_LOGGING, "Iterativepropagator: %s\n", x) +#define IterativePropagator_LOG( x, ... ) \ + LOG( GlobalConfiguration::PREPROCESSOR_LOGGING, "Iterativepropagator: %s\n", x ) class IterativePropagator : public ParallelSolver { @@ -58,8 +59,10 @@ class IterativePropagator : public ParallelSolver Optimize for the min/max value of variableName with respect to the constraints encoded in gurobi. If the query is infeasible, *infeasible is set to true. */ - static double optimizeWithGurobi( GurobiWrapper &gurobi, MinOrMax minOrMax, - String variableName, double cutoffValue, + static double optimizeWithGurobi( GurobiWrapper &gurobi, + MinOrMax minOrMax, + String variableName, + double cutoffValue, std::atomic_bool *infeasible = NULL ); /* diff --git a/src/nlr/LPFormulator.cpp b/src/nlr/LPFormulator.cpp index 4ccb82acba..e281112e53 100644 --- a/src/nlr/LPFormulator.cpp +++ b/src/nlr/LPFormulator.cpp @@ -13,9 +13,10 @@ **/ +#include "LPFormulator.h" + #include "GurobiWrapper.h" #include "InfeasibleQueryException.h" -#include "LPFormulator.h" #include "Layer.h" #include "MStringf.h" #include "NLRError.h" @@ -38,7 +39,8 @@ LPFormulator::~LPFormulator() double LPFormulator::solveLPRelaxation( GurobiWrapper &gurobi, const Map &layers, - MinOrMax minOrMax, String variableName, + MinOrMax minOrMax, + String variableName, unsigned lastLayer ) { gurobi.resetModel(); @@ -47,8 +49,10 @@ double LPFormulator::solveLPRelaxation( GurobiWrapper &gurobi, } double LPFormulator::optimizeWithGurobi( GurobiWrapper &gurobi, - MinOrMax minOrMax, String variableName, - double cutoffValue, std::atomic_bool *infeasible ) + MinOrMax minOrMax, + String variableName, + double cutoffValue, + std::atomic_bool *infeasible ) { List terms; terms.append( GurobiWrapper::Term( 1, variableName ) ); @@ -107,9 +111,9 @@ void LPFormulator::optimizeBoundsWithIncrementalLpRelaxation( const MapsetUb( j, ub ); - _layerOwner->receiveTighterBound( Tightening( variable, - ub, - Tightening::UB ) ); + _layerOwner->receiveTighterBound( Tightening( variable, ub, Tightening::UB ) ); ++tighterBoundCounter; if ( _cutoffInUse && ub < _cutoffValue ) @@ -217,14 +218,11 @@ void LPFormulator::optimizeBoundsWithIncrementalLpRelaxation( const MapsetLb( j, lb ); - _layerOwner->receiveTighterBound( Tightening( variable, - lb, - Tightening::LB ) ); + _layerOwner->receiveTighterBound( Tightening( variable, lb, Tightening::LB ) ); ++tighterBoundCounter; if ( _cutoffInUse && lb >= _cutoffValue ) @@ -238,9 +236,15 @@ void LPFormulator::optimizeBoundsWithIncrementalLpRelaxation( const Map &layers ) @@ -268,9 +272,9 @@ void LPFormulator::optimizeBoundsWithLpRelaxation( const Map std::atomic_uint cutoffs( 0 ); struct timespec gurobiStart; - (void) gurobiStart; + (void)gurobiStart; struct timespec gurobiEnd; - (void) gurobiEnd; + (void)gurobiEnd; gurobiStart = TimeUtils::sampleMicro(); @@ -278,16 +282,18 @@ void LPFormulator::optimizeBoundsWithLpRelaxation( const Map { Layer *layer = currentLayer.second; - ThreadArgument argument( layer, &layers, - std::ref( freeSolvers ), - std::ref( mtx ), std::ref( infeasible ), - std::ref( tighterBoundCounter ), - std::ref( signChanges ), - std::ref( cutoffs ), - layer->getLayerIndex(), - currentLayer.first, - threads, - &solverToIndex ); + ThreadArgument argument( layer, + &layers, + std::ref( freeSolvers ), + std::ref( mtx ), + std::ref( infeasible ), + std::ref( tighterBoundCounter ), + std::ref( signChanges ), + std::ref( cutoffs ), + layer->getLayerIndex(), + currentLayer.first, + threads, + &solverToIndex ); // optimize every neuron of layer optimizeBoundsOfNeuronsWithLpRlaxation( argument ); @@ -300,9 +306,15 @@ void LPFormulator::optimizeBoundsWithLpRelaxation( const Map gurobiEnd = TimeUtils::sampleMicro(); - LPFormulator_LOG( Stringf( "Number of tighter bounds found by Gurobi: %u. Sign changes: %u. Cutoffs: %u\n", - tighterBoundCounter.load(), signChanges.load(), cutoffs.load() ).ascii() ); - LPFormulator_LOG( Stringf( "Seconds spent Gurobiing: %llu\n", TimeUtils::timePassed( gurobiStart, gurobiEnd ) / 1000000 ).ascii() ); + LPFormulator_LOG( + Stringf( "Number of tighter bounds found by Gurobi: %u. Sign changes: %u. Cutoffs: %u\n", + tighterBoundCounter.load(), + signChanges.load(), + cutoffs.load() ) + .ascii() ); + LPFormulator_LOG( Stringf( "Seconds spent Gurobiing: %llu\n", + TimeUtils::timePassed( gurobiStart, gurobiEnd ) / 1000000 ) + .ascii() ); clearSolverQueue( freeSolvers ); @@ -310,7 +322,8 @@ void LPFormulator::optimizeBoundsWithLpRelaxation( const Map throw InfeasibleQueryException(); } -void LPFormulator::optimizeBoundsOfOneLayerWithLpRelaxation( const Map &layers, unsigned targetIndex ) +void LPFormulator::optimizeBoundsOfOneLayerWithLpRelaxation( const Map &layers, + unsigned targetIndex ) { unsigned numberOfWorkers = Options::get()->getInt( Options::NUM_WORKERS ); @@ -335,24 +348,26 @@ void LPFormulator::optimizeBoundsOfOneLayerWithLpRelaxation( const Map layers = *args._layers; unsigned targetIndex = args._targetIndex; @@ -401,8 +422,10 @@ void LPFormulator::optimizeBoundsOfNeuronsWithLpRlaxation( ThreadArgument &args bool skipTightenLb = false; // If true, skip lower bound tightening bool skipTightenUb = false; // If true, skip upper bound tightening - // declare simulations as local var to avoid a problem which can happen due to multi thread process. - const Vector> *simulations = _layerOwner->getLayer( targetIndex )->getSimulations(); + // declare simulations as local var to avoid a problem which can happen due to multi thread + // process. + const Vector> *simulations = + _layerOwner->getLayer( targetIndex )->getSimulations(); for ( unsigned i = 0; i < layer->getSize(); ++i ) { @@ -419,12 +442,14 @@ void LPFormulator::optimizeBoundsOfNeuronsWithLpRlaxation( ThreadArgument &args skipTightenUb = false; // Loop for simulation - for ( const auto &simValue : (*simulations).get( i ) ) + for ( const auto &simValue : ( *simulations ).get( i ) ) { - if ( _cutoffInUse && _cutoffValue < simValue ) // If x_lower < 0 < x_sim, do not try to call tightning upper bound. + if ( _cutoffInUse && _cutoffValue < simValue ) // If x_lower < 0 < x_sim, do not try to + // call tightning upper bound. skipTightenUb = true; - if ( _cutoffInUse && simValue < _cutoffValue ) // If x_sim < 0 < x_upper, do not try to call tightning lower bound. + if ( _cutoffInUse && simValue < _cutoffValue ) // If x_sim < 0 < x_upper, do not try to + // call tightning lower bound. skipTightenLb = true; if ( skipTightenUb && skipTightenLb ) @@ -434,19 +459,23 @@ void LPFormulator::optimizeBoundsOfNeuronsWithLpRlaxation( ThreadArgument &args // If no tightning is needed, continue if ( skipTightenUb && skipTightenLb ) { - LPFormulator_LOG( Stringf( "Skip tightening lower and upper bounds for layer %d index %u", - targetIndex, i ).ascii() ); + LPFormulator_LOG( + Stringf( + "Skip tightening lower and upper bounds for layer %d index %u", targetIndex, i ) + .ascii() ); continue; } else if ( skipTightenUb ) { - LPFormulator_LOG( Stringf( "Skip tightening upper bound for layer %u index %u", - targetIndex, i ).ascii() ); + LPFormulator_LOG( + Stringf( "Skip tightening upper bound for layer %u index %u", targetIndex, i ) + .ascii() ); } else if ( skipTightenLb ) { - LPFormulator_LOG( Stringf( "Skip tightening lower bound for layer %u index %u", - targetIndex, i ).ascii() ); + LPFormulator_LOG( + Stringf( "Skip tightening lower bound for layer %u index %u", targetIndex, i ) + .ascii() ); } if ( infeasible ) @@ -473,22 +502,28 @@ void LPFormulator::optimizeBoundsOfNeuronsWithLpRlaxation( ThreadArgument &args mtx.unlock(); // spawn a thread to tighten the bounds for the current variable - ThreadArgument argument( freeSolver, layer, - i, currentLb, currentUb, - _cutoffInUse, _cutoffValue, - _layerOwner, std::ref( freeSolvers ), - std::ref( mtx ), std::ref( infeasible ), - std::ref( tighterBoundCounter ), - std::ref( signChanges ), - std::ref( cutoffs ), - skipTightenLb, - skipTightenUb ); + ThreadArgument argument( freeSolver, + layer, + i, + currentLb, + currentUb, + _cutoffInUse, + _cutoffValue, + _layerOwner, + std::ref( freeSolvers ), + std::ref( mtx ), + std::ref( infeasible ), + std::ref( tighterBoundCounter ), + std::ref( signChanges ), + std::ref( cutoffs ), + skipTightenLb, + skipTightenUb ); if ( numberOfWorkers == 1 ) tightenSingleVariableBoundsWithLPRelaxation( argument ); else - threads[solverToIndex[freeSolver]] = boost::thread - ( tightenSingleVariableBoundsWithLPRelaxation, argument ); + threads[solverToIndex[freeSolver]] = + boost::thread( tightenSingleVariableBoundsWithLPRelaxation, argument ); } } @@ -514,8 +549,9 @@ void LPFormulator::tightenSingleVariableBoundsWithLPRelaxation( ThreadArgument & bool skipTightenLb = argument._skipTightenLb; bool skipTightenUb = argument._skipTightenUb; - LPFormulator_LOG( Stringf( "Tightening bounds for layer %u index %u", - layer->getLayerIndex(), index ).ascii() ); + LPFormulator_LOG( + Stringf( "Tightening bounds for layer %u index %u", layer->getLayerIndex(), index ) + .ascii() ); unsigned variable = layer->neuronToVariable( index ); Stringf variableName( "x%u", variable ); @@ -523,22 +559,19 @@ void LPFormulator::tightenSingleVariableBoundsWithLPRelaxation( ThreadArgument & if ( !skipTightenUb ) { LPFormulator_LOG( Stringf( "Computing upperbound..." ).ascii() ); - double ub = optimizeWithGurobi( *gurobi, MinOrMax::MAX, variableName, - cutoffValue, &infeasible ); + double ub = optimizeWithGurobi( + *gurobi, MinOrMax::MAX, variableName, cutoffValue, &infeasible ); LPFormulator_LOG( Stringf( "Upperbound computed %f", ub ).ascii() ); // Store the new bound if it is tighter if ( ub < currentUb ) { - if ( FloatUtils::isPositive( currentUb ) && - !FloatUtils::isPositive( ub ) ) + if ( FloatUtils::isPositive( currentUb ) && !FloatUtils::isPositive( ub ) ) ++signChanges; mtx.lock(); layer->setUb( index, ub ); - layerOwner->receiveTighterBound( Tightening( variable, - ub, - Tightening::UB ) ); + layerOwner->receiveTighterBound( Tightening( variable, ub, Tightening::UB ) ); mtx.unlock(); ++tighterBoundCounter; @@ -556,21 +589,18 @@ void LPFormulator::tightenSingleVariableBoundsWithLPRelaxation( ThreadArgument & { LPFormulator_LOG( Stringf( "Computing lowerbound..." ).ascii() ); gurobi->reset(); - double lb = optimizeWithGurobi( *gurobi, MinOrMax::MIN, variableName, - cutoffValue, &infeasible ); + double lb = optimizeWithGurobi( + *gurobi, MinOrMax::MIN, variableName, cutoffValue, &infeasible ); LPFormulator_LOG( Stringf( "Lowerbound computed: %f", lb ).ascii() ); // Store the new bound if it is tighter if ( lb > currentLb ) { - if ( FloatUtils::isNegative( currentLb ) && - !FloatUtils::isNegative( lb ) ) + if ( FloatUtils::isNegative( currentLb ) && !FloatUtils::isNegative( lb ) ) ++signChanges; mtx.lock(); layer->setLb( index, lb ); - layerOwner->receiveTighterBound( Tightening( variable, - lb, - Tightening::LB ) ); + layerOwner->receiveTighterBound( Tightening( variable, lb, Tightening::LB ) ); mtx.unlock(); ++tighterBoundCounter; @@ -580,7 +610,7 @@ void LPFormulator::tightenSingleVariableBoundsWithLPRelaxation( ThreadArgument & } enqueueSolver( freeSolvers, gurobi ); } - catch ( boost::thread_interrupted& ) + catch ( boost::thread_interrupted & ) { enqueueSolver( argument._freeSolvers, argument._gurobi ); } @@ -629,20 +659,16 @@ void LPFormulator::addLayerToModel( GurobiWrapper &gurobi, const Layer *layer ) } } -void LPFormulator::addInputLayerToLpRelaxation( GurobiWrapper &gurobi, - const Layer *layer ) +void LPFormulator::addInputLayerToLpRelaxation( GurobiWrapper &gurobi, const Layer *layer ) { for ( unsigned i = 0; i < layer->getSize(); ++i ) { unsigned variable = layer->neuronToVariable( i ); - gurobi.addVariable( Stringf( "x%u", variable ), - layer->getLb( i ), - layer->getUb( i ) ); + gurobi.addVariable( Stringf( "x%u", variable ), layer->getLb( i ), layer->getUb( i ) ); } } -void LPFormulator::addReluLayerToLpRelaxation( GurobiWrapper &gurobi, - const Layer *layer ) +void LPFormulator::addReluLayerToLpRelaxation( GurobiWrapper &gurobi, const Layer *layer ) { for ( unsigned i = 0; i < layer->getSize(); ++i ) { @@ -660,9 +686,7 @@ void LPFormulator::addReluLayerToLpRelaxation( GurobiWrapper &gurobi, double sourceValue = sourceLayer->getEliminatedNeuronValue( sourceNeuron ); double targetValue = sourceValue > 0 ? sourceValue : 0; - gurobi.addVariable( Stringf( "x%u", targetVariable ), - targetValue, - targetValue ); + gurobi.addVariable( Stringf( "x%u", targetVariable ), targetValue, targetValue ); continue; } @@ -671,9 +695,7 @@ void LPFormulator::addReluLayerToLpRelaxation( GurobiWrapper &gurobi, double sourceLb = sourceLayer->getLb( sourceNeuron ); double sourceUb = sourceLayer->getUb( sourceNeuron ); - gurobi.addVariable( Stringf( "x%u", targetVariable ), - 0, - layer->getUb( i ) ); + gurobi.addVariable( Stringf( "x%u", targetVariable ), 0, layer->getUb( i ) ); if ( !FloatUtils::isNegative( sourceLb ) ) { @@ -723,15 +745,16 @@ void LPFormulator::addReluLayerToLpRelaxation( GurobiWrapper &gurobi, */ terms.clear(); terms.append( GurobiWrapper::Term( 1, Stringf( "x%u", targetVariable ) ) ); - terms.append( GurobiWrapper::Term( -sourceUb / ( sourceUb - sourceLb ), Stringf( "x%u", sourceVariable ) ) ); - gurobi.addLeqConstraint( terms, ( -sourceUb * sourceLb ) / ( sourceUb - sourceLb ) ); + terms.append( GurobiWrapper::Term( -sourceUb / ( sourceUb - sourceLb ), + Stringf( "x%u", sourceVariable ) ) ); + gurobi.addLeqConstraint( terms, + ( -sourceUb * sourceLb ) / ( sourceUb - sourceLb ) ); } } } } -void LPFormulator::addSignLayerToLpRelaxation( GurobiWrapper &gurobi, - const Layer *layer ) +void LPFormulator::addSignLayerToLpRelaxation( GurobiWrapper &gurobi, const Layer *layer ) { for ( unsigned i = 0; i < layer->getSize(); ++i ) { @@ -750,9 +773,7 @@ void LPFormulator::addSignLayerToLpRelaxation( GurobiWrapper &gurobi, double sourceValue = sourceLayer->getEliminatedNeuronValue( sourceNeuron ); double targetValue = FloatUtils::isNegative( sourceValue ) ? -1 : 1; - gurobi.addVariable( Stringf( "x%u", targetVariable ), - targetValue, - targetValue ); + gurobi.addVariable( Stringf( "x%u", targetVariable ), targetValue, targetValue ); continue; } @@ -804,14 +825,14 @@ void LPFormulator::addSignLayerToLpRelaxation( GurobiWrapper &gurobi, */ terms.clear(); terms.append( GurobiWrapper::Term( 1, Stringf( "x%u", targetVariable ) ) ); - terms.append( GurobiWrapper::Term( -2.0 / sourceUb, Stringf( "x%u", sourceVariable ) ) ); + terms.append( + GurobiWrapper::Term( -2.0 / sourceUb, Stringf( "x%u", sourceVariable ) ) ); gurobi.addGeqConstraint( terms, -1 ); } } } -void LPFormulator::addMaxLayerToLpRelaxation( GurobiWrapper &gurobi, - const Layer *layer ) +void LPFormulator::addMaxLayerToLpRelaxation( GurobiWrapper &gurobi, const Layer *layer ) { for ( unsigned i = 0; i < layer->getSize(); ++i ) { @@ -819,7 +840,8 @@ void LPFormulator::addMaxLayerToLpRelaxation( GurobiWrapper &gurobi, continue; unsigned targetVariable = layer->neuronToVariable( i ); - gurobi.addVariable( Stringf( "x%u", targetVariable ), layer->getLb( i ), layer->getUb( i ) ); + gurobi.addVariable( + Stringf( "x%u", targetVariable ), layer->getLb( i ), layer->getUb( i ) ); List sources = layer->getActivationSources( i ); @@ -892,9 +914,7 @@ void LPFormulator::addWeightedSumLayerToLpRelaxation( GurobiWrapper &gurobi, con { unsigned variable = layer->neuronToVariable( i ); - gurobi.addVariable( Stringf( "x%u", variable ), - layer->getLb( i ), - layer->getUb( i ) ); + gurobi.addVariable( Stringf( "x%u", variable ), layer->getLb( i ), layer->getUb( i ) ); List terms; terms.append( GurobiWrapper::Term( -1, Stringf( "x%u", variable ) ) ); @@ -911,8 +931,7 @@ void LPFormulator::addWeightedSumLayerToLpRelaxation( GurobiWrapper &gurobi, con double weight = layer->getWeight( sourceLayerPair.first, j, i ); if ( !sourceLayer->neuronEliminated( j ) ) { - Stringf sourceVariableName( "x%u", - sourceLayer->neuronToVariable( j ) ); + Stringf sourceVariableName( "x%u", sourceLayer->neuronToVariable( j ) ); terms.append( GurobiWrapper::Term( weight, sourceVariableName ) ); } else diff --git a/src/nlr/LPFormulator.h b/src/nlr/LPFormulator.h index 99ed538796..e52cdf6bac 100644 --- a/src/nlr/LPFormulator.h +++ b/src/nlr/LPFormulator.h @@ -18,19 +18,20 @@ #include "GurobiWrapper.h" #include "LayerOwner.h" -#include "ParallelSolver.h" #include "Map.h" -#include +#include "ParallelSolver.h" #include -#include #include +#include #include +#include #include namespace NLR { -#define LPFormulator_LOG(x, ...) LOG(GlobalConfiguration::PREPROCESSOR_LOGGING, "LP Preprocessor: %s\n", x) +#define LPFormulator_LOG( x, ... ) \ + LOG( GlobalConfiguration::PREPROCESSOR_LOGGING, "LP Preprocessor: %s\n", x ) class LPFormulator : public ParallelSolver { @@ -51,7 +52,8 @@ class LPFormulator : public ParallelSolver constructed from scratch */ void optimizeBoundsWithLpRelaxation( const Map &layers ); - void optimizeBoundsOfOneLayerWithLpRelaxation( const Map &layers, unsigned targetIndex ); + void optimizeBoundsOfOneLayerWithLpRelaxation( const Map &layers, + unsigned targetIndex ); void optimizeBoundsWithIncrementalLpRelaxation( const Map &layers ); /* @@ -73,31 +75,26 @@ class LPFormulator : public ParallelSolver double solveLPRelaxation( GurobiWrapper &gurobi, const Map &layers, - MinOrMax minOrMax, String variableName, + MinOrMax minOrMax, + String variableName, unsigned lastLayer = UINT_MAX ); void addLayerToModel( GurobiWrapper &gurobi, const Layer *layer ); private: - LayerOwner *_layerOwner; bool _cutoffInUse; double _cutoffValue; - void addInputLayerToLpRelaxation( GurobiWrapper &gurobi, - const Layer *layer ); + void addInputLayerToLpRelaxation( GurobiWrapper &gurobi, const Layer *layer ); - void addReluLayerToLpRelaxation( GurobiWrapper &gurobi, - const Layer *layer ); + void addReluLayerToLpRelaxation( GurobiWrapper &gurobi, const Layer *layer ); - void addSignLayerToLpRelaxation( GurobiWrapper &gurobi, - const Layer *layer ); + void addSignLayerToLpRelaxation( GurobiWrapper &gurobi, const Layer *layer ); - void addMaxLayerToLpRelaxation( GurobiWrapper &gurobi, - const Layer *layer ); + void addMaxLayerToLpRelaxation( GurobiWrapper &gurobi, const Layer *layer ); - void addWeightedSumLayerToLpRelaxation( GurobiWrapper &gurobi, - const Layer *layer ); + void addWeightedSumLayerToLpRelaxation( GurobiWrapper &gurobi, const Layer *layer ); void optimizeBoundsOfNeuronsWithLpRlaxation( ThreadArgument &args ); @@ -105,8 +102,10 @@ class LPFormulator : public ParallelSolver Optimize for the min/max value of variableName with respect to the constraints encoded in gurobi. If the query is infeasible, *infeasible is set to true. */ - static double optimizeWithGurobi( GurobiWrapper &gurobi, MinOrMax minOrMax, - String variableName, double cutoffValue, + static double optimizeWithGurobi( GurobiWrapper &gurobi, + MinOrMax minOrMax, + String variableName, + double cutoffValue, std::atomic_bool *infeasible = NULL ); /* diff --git a/src/nlr/Layer.cpp b/src/nlr/Layer.cpp index eed063b419..9ea90de931 100644 --- a/src/nlr/Layer.cpp +++ b/src/nlr/Layer.cpp @@ -13,8 +13,9 @@ **/ -#include "InputQuery.h" #include "Layer.h" + +#include "InputQuery.h" #include "Options.h" #include "SoftmaxConstraint.h" #include "SymbolicBoundTighteningType.h" @@ -69,7 +70,8 @@ void Layer::allocateMemory() _assignment = new double[_size]; - _simulations.assign( _size, Vector( Options::get()->getInt( Options::NUMBER_OF_SIMULATIONS ) ) ); + _simulations.assign( + _size, Vector( Options::get()->getInt( Options::NUMBER_OF_SIMULATIONS ) ) ); _inputLayerSize = ( _type == INPUT ) ? _size : _layerOwner->getLayer( 0 )->getSize(); if ( Options::get()->getSymbolicBoundTighteningType() == @@ -102,7 +104,7 @@ void Layer::allocateMemory() void Layer::setAssignment( const double *values ) { ASSERT( _eliminatedNeurons.empty() ); - memcpy( _assignment, values, _size * sizeof(double) ); + memcpy( _assignment, values, _size * sizeof( double ) ); } const double *Layer::getAssignment() const @@ -132,7 +134,7 @@ void Layer::computeAssignment() if ( _type == WEIGHTED_SUM ) { // Initialize to bias - memcpy( _assignment, _bias, sizeof(double) * _size ); + memcpy( _assignment, _bias, sizeof( double ) * _size ); // Process each of the source layers for ( auto &sourceLayerEntry : _sourceLayers ) @@ -153,7 +155,8 @@ void Layer::computeAssignment() for ( unsigned i = 0; i < _size; ++i ) { NeuronIndex sourceIndex = *_neuronToActivationSources[i].begin(); - double inputValue = _layerOwner->getLayer( sourceIndex._layer )->getAssignment( sourceIndex._neuron ); + double inputValue = + _layerOwner->getLayer( sourceIndex._layer )->getAssignment( sourceIndex._neuron ); _assignment[i] = FloatUtils::max( inputValue, 0 ); } @@ -164,7 +167,8 @@ void Layer::computeAssignment() for ( unsigned i = 0; i < _size; ++i ) { NeuronIndex sourceIndex = *_neuronToActivationSources[i].begin(); - double inputValue = _layerOwner->getLayer( sourceIndex._layer )->getAssignment( sourceIndex._neuron ); + double inputValue = + _layerOwner->getLayer( sourceIndex._layer )->getAssignment( sourceIndex._neuron ); _assignment[i] = FloatUtils::round( inputValue ); } @@ -175,7 +179,8 @@ void Layer::computeAssignment() for ( unsigned i = 0; i < _size; ++i ) { NeuronIndex sourceIndex = *_neuronToActivationSources[i].begin(); - double inputValue = _layerOwner->getLayer( sourceIndex._layer )->getAssignment( sourceIndex._neuron ); + double inputValue = + _layerOwner->getLayer( sourceIndex._layer )->getAssignment( sourceIndex._neuron ); ASSERT( _alpha > 0 && _alpha < 1 ); _assignment[i] = FloatUtils::max( inputValue, _alpha * inputValue ); } @@ -186,7 +191,8 @@ void Layer::computeAssignment() for ( unsigned i = 0; i < _size; ++i ) { NeuronIndex sourceIndex = *_neuronToActivationSources[i].begin(); - double inputValue = _layerOwner->getLayer( sourceIndex._layer )->getAssignment( sourceIndex._neuron ); + double inputValue = + _layerOwner->getLayer( sourceIndex._layer )->getAssignment( sourceIndex._neuron ); _assignment[i] = FloatUtils::abs( inputValue ); } @@ -200,7 +206,8 @@ void Layer::computeAssignment() for ( const auto &input : _neuronToActivationSources[i] ) { - double value = _layerOwner->getLayer( input._layer )->getAssignment( input._neuron ); + double value = + _layerOwner->getLayer( input._layer )->getAssignment( input._neuron ); if ( value > _assignment[i] ) _assignment[i] = value; } @@ -212,7 +219,8 @@ void Layer::computeAssignment() for ( unsigned i = 0; i < _size; ++i ) { NeuronIndex sourceIndex = *_neuronToActivationSources[i].begin(); - double inputValue = _layerOwner->getLayer( sourceIndex._layer )->getAssignment( sourceIndex._neuron ); + double inputValue = + _layerOwner->getLayer( sourceIndex._layer )->getAssignment( sourceIndex._neuron ); _assignment[i] = FloatUtils::isNegative( inputValue ) ? -1 : 1; } @@ -223,7 +231,8 @@ void Layer::computeAssignment() for ( unsigned i = 0; i < _size; ++i ) { NeuronIndex sourceIndex = *_neuronToActivationSources[i].begin(); - double inputValue = _layerOwner->getLayer( sourceIndex._layer )->getAssignment( sourceIndex._neuron ); + double inputValue = + _layerOwner->getLayer( sourceIndex._layer )->getAssignment( sourceIndex._neuron ); _assignment[i] = 1 / ( 1 + std::exp( -inputValue ) ); } @@ -231,40 +240,41 @@ void Layer::computeAssignment() else if ( _type == SOFTMAX ) { - for ( unsigned i = 0; i < _size; ++i ) - { - _assignment[i] = FloatUtils::negativeInfinity(); - - Vector inputs; - Vector outputs; - unsigned outputIndex = 0; - unsigned index = 0; - for ( const auto &input : _neuronToActivationSources[i] ) + for ( unsigned i = 0; i < _size; ++i ) { - if ( input._neuron == i ) - outputIndex = index; - double value = _layerOwner->getLayer( input._layer )->getAssignment( input._neuron ); - inputs.append(value); - ++index; - } + _assignment[i] = FloatUtils::negativeInfinity(); - SoftmaxConstraint::softmax(inputs, outputs); - _assignment[i] = outputs[outputIndex]; + Vector inputs; + Vector outputs; + unsigned outputIndex = 0; + unsigned index = 0; + for ( const auto &input : _neuronToActivationSources[i] ) + { + if ( input._neuron == i ) + outputIndex = index; + double value = + _layerOwner->getLayer( input._layer )->getAssignment( input._neuron ); + inputs.append( value ); + ++index; + } - } + SoftmaxConstraint::softmax( inputs, outputs ); + _assignment[i] = outputs[outputIndex]; + } } else if ( _type == BILINEAR ) { - for ( unsigned i = 0; i < _size; ++i ) - { - _assignment[i] = 1; - for ( const auto &input : _neuronToActivationSources[i] ) + for ( unsigned i = 0; i < _size; ++i ) { - double value = _layerOwner->getLayer( input._layer )->getAssignment( input._neuron ); - _assignment[i] *= value; + _assignment[i] = 1; + for ( const auto &input : _neuronToActivationSources[i] ) + { + double value = + _layerOwner->getLayer( input._layer )->getAssignment( input._neuron ); + _assignment[i] *= value; + } } - } } else { @@ -304,15 +314,18 @@ void Layer::computeSimulations() for ( unsigned i = 0; i < sourceSize; ++i ) for ( unsigned j = 0; j < simulationSize; ++j ) for ( unsigned k = 0; k < _size; ++k ) - _simulations[k][j] += ( ( *sourceSimulations ).get( i ).get( j ) * weights[i * _size + k] ); + _simulations[k][j] += + ( ( *sourceSimulations ).get( i ).get( j ) * weights[i * _size + k] ); } - } + } else if ( _type == RELU ) { for ( unsigned i = 0; i < _size; ++i ) { - NeuronIndex sourceIndex = *_neuronToActivationSources[i].begin(); - const Vector &simulations = ( *( _layerOwner->getLayer( sourceIndex._layer )->getSimulations() ) ).get( sourceIndex._neuron ); + NeuronIndex sourceIndex = *_neuronToActivationSources[i].begin(); + const Vector &simulations = + ( *( _layerOwner->getLayer( sourceIndex._layer )->getSimulations() ) ) + .get( sourceIndex._neuron ); for ( unsigned j = 0; j < simulationSize; ++j ) _simulations[i][j] = FloatUtils::max( simulations.get( j ), 0 ); } @@ -322,10 +335,13 @@ void Layer::computeSimulations() for ( unsigned i = 0; i < _size; ++i ) { NeuronIndex sourceIndex = *_neuronToActivationSources[i].begin(); - const Vector &simulations = ( *( _layerOwner->getLayer( sourceIndex._layer )->getSimulations() ) ).get( sourceIndex._neuron ); - ASSERT( _alpha > 0 && _alpha < 1); + const Vector &simulations = + ( *( _layerOwner->getLayer( sourceIndex._layer )->getSimulations() ) ) + .get( sourceIndex._neuron ); + ASSERT( _alpha > 0 && _alpha < 1 ); for ( unsigned j = 0; j < simulationSize; ++j ) - _simulations[i][j] = FloatUtils::max( simulations.get( j ), _alpha * simulations.get( j ) ); + _simulations[i][j] = + FloatUtils::max( simulations.get( j ), _alpha * simulations.get( j ) ); } } else if ( _type == ABSOLUTE_VALUE ) @@ -333,8 +349,10 @@ void Layer::computeSimulations() for ( unsigned i = 0; i < _size; ++i ) { NeuronIndex sourceIndex = *_neuronToActivationSources[i].begin(); - const Vector &simulations = ( *( _layerOwner->getLayer( sourceIndex._layer )->getSimulations() ) ).get( sourceIndex._neuron ); - for ( unsigned j = 0; j < simulationSize; ++j ) + const Vector &simulations = + ( *( _layerOwner->getLayer( sourceIndex._layer )->getSimulations() ) ) + .get( sourceIndex._neuron ); + for ( unsigned j = 0; j < simulationSize; ++j ) _simulations[i][j] = FloatUtils::abs( simulations.get( j ) ); } } @@ -348,8 +366,11 @@ void Layer::computeSimulations() for ( const auto &input : _neuronToActivationSources[i] ) { - //double value = ( *( _layerOwner->getLayer( input._layer )->getSimulations() ) )[input._neuron][j]; - double value = ( *( _layerOwner->getLayer( input._layer )->getSimulations() ) ).get( input._neuron ).get( j ); + // double value = ( *( _layerOwner->getLayer( input._layer )->getSimulations() ) + // )[input._neuron][j]; + double value = ( *( _layerOwner->getLayer( input._layer )->getSimulations() ) ) + .get( input._neuron ) + .get( j ); if ( value > _simulations[i][j] ) _simulations[i][j] = value; } @@ -361,7 +382,8 @@ void Layer::computeSimulations() for ( unsigned i = 0; i < _size; ++i ) { NeuronIndex sourceIndex = *_neuronToActivationSources[i].begin(); - const Vector &simulations = ( *( _layerOwner->getLayer( sourceIndex._layer )->getSimulations() ) ).get( i ); + const Vector &simulations = + ( *( _layerOwner->getLayer( sourceIndex._layer )->getSimulations() ) ).get( i ); for ( unsigned j = 0; j < simulationSize; ++j ) _simulations[i][j] = FloatUtils::isNegative( simulations.get( j ) ) ? -1 : 1; } @@ -371,7 +393,8 @@ void Layer::computeSimulations() for ( unsigned i = 0; i < _size; ++i ) { NeuronIndex sourceIndex = *_neuronToActivationSources[i].begin(); - const Vector &simulations = ( *( _layerOwner->getLayer( sourceIndex._layer )->getSimulations() ) ).get( i ); + const Vector &simulations = + ( *( _layerOwner->getLayer( sourceIndex._layer )->getSimulations() ) ).get( i ); for ( unsigned j = 0; j < simulationSize; ++j ) _simulations[i][j] = 1 / ( 1 + std::exp( -simulations.get( j ) ) ); } @@ -438,7 +461,10 @@ void Layer::removeSourceLayer( unsigned sourceLayer ) _layerToNegativeWeights.erase( sourceLayer ); } -void Layer::setWeight( unsigned sourceLayer, unsigned sourceNeuron, unsigned targetNeuron, double weight ) +void Layer::setWeight( unsigned sourceLayer, + unsigned sourceNeuron, + unsigned targetNeuron, + double weight ) { unsigned index = sourceNeuron * _size + targetNeuron; _layerToWeights[sourceLayer][index] = weight; @@ -455,9 +481,7 @@ void Layer::setWeight( unsigned sourceLayer, unsigned sourceNeuron, unsigned tar } } -double Layer::getWeight( unsigned sourceLayer, - unsigned sourceNeuron, - unsigned targetNeuron ) const +double Layer::getWeight( unsigned sourceLayer, unsigned sourceNeuron, unsigned targetNeuron ) const { unsigned index = sourceNeuron * _size + targetNeuron; return _layerToWeights[sourceLayer][index]; @@ -493,21 +517,24 @@ double *Layer::getBiases() const return _bias; } -void Layer::addActivationSource( unsigned sourceLayer, unsigned sourceNeuron, unsigned targetNeuron ) +void Layer::addActivationSource( unsigned sourceLayer, + unsigned sourceNeuron, + unsigned targetNeuron ) { - ASSERT( _type == RELU || _type == LEAKY_RELU || _type == ABSOLUTE_VALUE || _type == MAX || _type == ROUND || - _type == SIGN || _type == SIGMOID || _type == SOFTMAX || _type == BILINEAR ); + ASSERT( _type == RELU || _type == LEAKY_RELU || _type == ABSOLUTE_VALUE || _type == MAX || + _type == ROUND || _type == SIGN || _type == SIGMOID || _type == SOFTMAX || + _type == BILINEAR ); if ( !_neuronToActivationSources.exists( targetNeuron ) ) _neuronToActivationSources[targetNeuron] = List(); _neuronToActivationSources[targetNeuron].append( NeuronIndex( sourceLayer, sourceNeuron ) ); - DEBUG({ - if ( _type == RELU || _type == LEAKY_RELU || _type == ABSOLUTE_VALUE || - _type == SIGN || _type == ROUND ) - ASSERT( _neuronToActivationSources[targetNeuron].size() == 1 ); - }); + DEBUG( { + if ( _type == RELU || _type == LEAKY_RELU || _type == ABSOLUTE_VALUE || _type == SIGN || + _type == ROUND ) + ASSERT( _neuronToActivationSources[targetNeuron].size() == 1 ); + } ); } List Layer::getActivationSources( unsigned neuron ) const @@ -688,12 +715,14 @@ void Layer::computeIntervalArithmeticBoundsForWeightedSum() if ( newLb[i] > _lb[i] ) { _lb[i] = newLb[i]; - _layerOwner->receiveTighterBound( Tightening( _neuronToVariable[i], _lb[i], Tightening::LB ) ); + _layerOwner->receiveTighterBound( + Tightening( _neuronToVariable[i], _lb[i], Tightening::LB ) ); } if ( newUb[i] < _ub[i] ) { _ub[i] = newUb[i]; - _layerOwner->receiveTighterBound( Tightening( _neuronToVariable[i], _ub[i], Tightening::UB ) ); + _layerOwner->receiveTighterBound( + Tightening( _neuronToVariable[i], _ub[i], Tightening::UB ) ); } } @@ -720,12 +749,14 @@ void Layer::computeIntervalArithmeticBoundsForRelu() if ( lb > _lb[i] ) { _lb[i] = lb; - _layerOwner->receiveTighterBound( Tightening( _neuronToVariable[i], _lb[i], Tightening::LB ) ); + _layerOwner->receiveTighterBound( + Tightening( _neuronToVariable[i], _lb[i], Tightening::LB ) ); } if ( ub < _ub[i] ) { _ub[i] = ub; - _layerOwner->receiveTighterBound( Tightening( _neuronToVariable[i], _ub[i], Tightening::UB ) ); + _layerOwner->receiveTighterBound( + Tightening( _neuronToVariable[i], _ub[i], Tightening::UB ) ); } } } @@ -748,12 +779,14 @@ void Layer::computeIntervalArithmeticBoundsForAbs() if ( lb > _lb[i] ) { _lb[i] = lb; - _layerOwner->receiveTighterBound( Tightening( _neuronToVariable[i], _lb[i], Tightening::LB ) ); + _layerOwner->receiveTighterBound( + Tightening( _neuronToVariable[i], _lb[i], Tightening::LB ) ); } if ( ub < _ub[i] ) { _ub[i] = ub; - _layerOwner->receiveTighterBound( Tightening( _neuronToVariable[i], _ub[i], Tightening::UB ) ); + _layerOwner->receiveTighterBound( + Tightening( _neuronToVariable[i], _ub[i], Tightening::UB ) ); } } else if ( ub < 0 ) @@ -761,12 +794,14 @@ void Layer::computeIntervalArithmeticBoundsForAbs() if ( -ub > _lb[i] ) { _lb[i] = -ub; - _layerOwner->receiveTighterBound( Tightening( _neuronToVariable[i], _lb[i], Tightening::LB ) ); + _layerOwner->receiveTighterBound( + Tightening( _neuronToVariable[i], _lb[i], Tightening::LB ) ); } if ( -lb < _ub[i] ) { _ub[i] = -lb; - _layerOwner->receiveTighterBound( Tightening( _neuronToVariable[i], _ub[i], Tightening::UB ) ); + _layerOwner->receiveTighterBound( + Tightening( _neuronToVariable[i], _ub[i], Tightening::UB ) ); } } else @@ -775,13 +810,15 @@ void Layer::computeIntervalArithmeticBoundsForAbs() if ( _lb[i] < 0 ) { _lb[i] = 0; - _layerOwner->receiveTighterBound( Tightening( _neuronToVariable[i], _lb[i], Tightening::LB ) ); + _layerOwner->receiveTighterBound( + Tightening( _neuronToVariable[i], _lb[i], Tightening::LB ) ); } if ( FloatUtils::max( ub, -lb ) < _ub[i] ) { _ub[i] = FloatUtils::max( ub, -lb ); - _layerOwner->receiveTighterBound( Tightening( _neuronToVariable[i], _ub[i], Tightening::UB ) ); + _layerOwner->receiveTighterBound( + Tightening( _neuronToVariable[i], _ub[i], Tightening::UB ) ); } } } @@ -822,7 +859,6 @@ void Layer::computeSymbolicBounds() { switch ( _type ) { - case INPUT: comptueSymbolicBoundsForInput(); break; @@ -966,8 +1002,10 @@ void Layer::computeSymbolicBoundsForRelu() for ( unsigned j = 0; j < _inputLayerSize; ++j ) { - _symbolicLb[j * _size + i] = sourceSymbolicLb[j * sourceLayerSize + sourceIndex._neuron]; - _symbolicUb[j * _size + i] = sourceSymbolicUb[j * sourceLayerSize + sourceIndex._neuron]; + _symbolicLb[j * _size + i] = + sourceSymbolicLb[j * sourceLayerSize + sourceIndex._neuron]; + _symbolicUb[j * _size + i] = + sourceSymbolicUb[j * sourceLayerSize + sourceIndex._neuron]; } _symbolicLowerBias[i] = sourceLayer->getSymbolicLowerBias()[sourceIndex._neuron]; _symbolicUpperBias[i] = sourceLayer->getSymbolicUpperBias()[sourceIndex._neuron]; @@ -1003,12 +1041,14 @@ void Layer::computeSymbolicBoundsForRelu() // lbOfUb[i] < 0 < ubOfUb[i] // Concretize the upper bound using the Ehler's-like approximation for ( unsigned j = 0; j < _inputLayerSize; ++j ) - _symbolicUb[j * _size + i] = - _symbolicUb[j * _size + i] * _symbolicUbOfUb[i] / ( _symbolicUbOfUb[i] - _symbolicLbOfUb[i] ); + _symbolicUb[j * _size + i] = _symbolicUb[j * _size + i] * _symbolicUbOfUb[i] / + ( _symbolicUbOfUb[i] - _symbolicLbOfUb[i] ); // Do the same for the bias, and then adjust - _symbolicUpperBias[i] = _symbolicUpperBias[i] * _symbolicUbOfUb[i] / ( _symbolicUbOfUb[i] - _symbolicLbOfUb[i] ); - _symbolicUpperBias[i] -= _symbolicLbOfUb[i] * _symbolicUbOfUb[i] / ( _symbolicUbOfUb[i] - _symbolicLbOfUb[i] ); + _symbolicUpperBias[i] = _symbolicUpperBias[i] * _symbolicUbOfUb[i] / + ( _symbolicUbOfUb[i] - _symbolicLbOfUb[i] ); + _symbolicUpperBias[i] -= _symbolicLbOfUb[i] * _symbolicUbOfUb[i] / + ( _symbolicUbOfUb[i] - _symbolicLbOfUb[i] ); } // Lower bound @@ -1022,10 +1062,11 @@ void Layer::computeSymbolicBoundsForRelu() else { for ( unsigned j = 0; j < _inputLayerSize; ++j ) - _symbolicLb[j * _size + i] = - _symbolicLb[j * _size + i] * _symbolicUbOfLb[i] / ( _symbolicUbOfLb[i] - _symbolicLbOfLb[i] ); + _symbolicLb[j * _size + i] = _symbolicLb[j * _size + i] * _symbolicUbOfLb[i] / + ( _symbolicUbOfLb[i] - _symbolicLbOfLb[i] ); - _symbolicLowerBias[i] = _symbolicLowerBias[i] * _symbolicUbOfLb[i] / ( _symbolicUbOfLb[i] - _symbolicLbOfLb[i] ); + _symbolicLowerBias[i] = _symbolicLowerBias[i] * _symbolicUbOfLb[i] / + ( _symbolicUbOfLb[i] - _symbolicLbOfLb[i] ); } _symbolicLbOfLb[i] = 0; @@ -1067,13 +1108,15 @@ void Layer::computeSymbolicBoundsForRelu() if ( _lb[i] < _symbolicLbOfLb[i] ) { _lb[i] = _symbolicLbOfLb[i]; - _layerOwner->receiveTighterBound( Tightening( _neuronToVariable[i], _lb[i], Tightening::LB ) ); + _layerOwner->receiveTighterBound( + Tightening( _neuronToVariable[i], _lb[i], Tightening::LB ) ); } if ( _ub[i] > _symbolicUbOfUb[i] ) { _ub[i] = _symbolicUbOfUb[i]; - _layerOwner->receiveTighterBound( Tightening( _neuronToVariable[i], _ub[i], Tightening::UB ) ); + _layerOwner->receiveTighterBound( + Tightening( _neuronToVariable[i], _ub[i], Tightening::UB ) ); } } } @@ -1127,8 +1170,10 @@ void Layer::computeSymbolicBoundsForSign() for ( unsigned j = 0; j < _inputLayerSize; ++j ) { - _symbolicLb[j * _size + i] = sourceSymbolicLb[j * sourceLayerSize + sourceIndex._neuron]; - _symbolicUb[j * _size + i] = sourceSymbolicUb[j * sourceLayerSize + sourceIndex._neuron]; + _symbolicLb[j * _size + i] = + sourceSymbolicLb[j * sourceLayerSize + sourceIndex._neuron]; + _symbolicUb[j * _size + i] = + sourceSymbolicUb[j * sourceLayerSize + sourceIndex._neuron]; } _symbolicLowerBias[i] = sourceLayer->getSymbolicLowerBias()[sourceIndex._neuron]; _symbolicUpperBias[i] = sourceLayer->getSymbolicUpperBias()[sourceIndex._neuron]; @@ -1222,8 +1267,7 @@ void Layer::computeSymbolicBoundsForSign() else { // The phase of this Sign is fixed! - double constant = - ( signPhase == SIGN_PHASE_POSITIVE ) ? 1 : -1; + double constant = ( signPhase == SIGN_PHASE_POSITIVE ) ? 1 : -1; _symbolicLbOfLb[i] = constant; _symbolicUbOfLb[i] = constant; @@ -1253,13 +1297,15 @@ void Layer::computeSymbolicBoundsForSign() if ( _lb[i] < _symbolicLbOfLb[i] ) { _lb[i] = _symbolicLbOfLb[i]; - _layerOwner->receiveTighterBound( Tightening( _neuronToVariable[i], _lb[i], Tightening::LB ) ); + _layerOwner->receiveTighterBound( + Tightening( _neuronToVariable[i], _lb[i], Tightening::LB ) ); } if ( _ub[i] > _symbolicUbOfUb[i] ) { _ub[i] = _symbolicUbOfUb[i]; - _layerOwner->receiveTighterBound( Tightening( _neuronToVariable[i], _ub[i], Tightening::UB ) ); + _layerOwner->receiveTighterBound( + Tightening( _neuronToVariable[i], _ub[i], Tightening::UB ) ); } } } @@ -1296,8 +1342,10 @@ void Layer::computeSymbolicBoundsForAbsoluteValue() for ( unsigned j = 0; j < _inputLayerSize; ++j ) { - _symbolicLb[j * _size + i] = sourceSymbolicLb[j * sourceLayerSize + sourceIndex._neuron]; - _symbolicUb[j * _size + i] = sourceSymbolicUb[j * sourceLayerSize + sourceIndex._neuron]; + _symbolicLb[j * _size + i] = + sourceSymbolicLb[j * sourceLayerSize + sourceIndex._neuron]; + _symbolicUb[j * _size + i] = + sourceSymbolicUb[j * sourceLayerSize + sourceIndex._neuron]; } _symbolicLowerBias[i] = sourceLayer->getSymbolicLowerBias()[sourceIndex._neuron]; @@ -1381,13 +1429,15 @@ void Layer::computeSymbolicBoundsForAbsoluteValue() if ( _lb[i] < _symbolicLbOfLb[i] ) { _lb[i] = _symbolicLbOfLb[i]; - _layerOwner->receiveTighterBound( Tightening( _neuronToVariable[i], _lb[i], Tightening::LB ) ); + _layerOwner->receiveTighterBound( + Tightening( _neuronToVariable[i], _lb[i], Tightening::LB ) ); } if ( _ub[i] > _symbolicUbOfUb[i] ) { _ub[i] = _symbolicUbOfUb[i]; - _layerOwner->receiveTighterBound( Tightening( _neuronToVariable[i], _ub[i], Tightening::UB ) ); + _layerOwner->receiveTighterBound( + Tightening( _neuronToVariable[i], _ub[i], Tightening::UB ) ); } } } @@ -1429,18 +1479,30 @@ void Layer::computeSymbolicBoundsForWeightedSum() newLB = oldUB * negWeights + oldLB * posWeights */ - matrixMultiplication( sourceLayer->getSymbolicUb(), _layerToPositiveWeights[sourceLayerIndex], - _symbolicUb, _inputLayerSize, - sourceLayerSize, _size ); - matrixMultiplication( sourceLayer->getSymbolicLb(), _layerToNegativeWeights[sourceLayerIndex], - _symbolicUb, _inputLayerSize, - sourceLayerSize, _size ); - matrixMultiplication( sourceLayer->getSymbolicLb(), _layerToPositiveWeights[sourceLayerIndex], - _symbolicLb, _inputLayerSize, - sourceLayerSize, _size); - matrixMultiplication( sourceLayer->getSymbolicUb(), _layerToNegativeWeights[sourceLayerIndex], - _symbolicLb, _inputLayerSize, - sourceLayerSize, _size); + matrixMultiplication( sourceLayer->getSymbolicUb(), + _layerToPositiveWeights[sourceLayerIndex], + _symbolicUb, + _inputLayerSize, + sourceLayerSize, + _size ); + matrixMultiplication( sourceLayer->getSymbolicLb(), + _layerToNegativeWeights[sourceLayerIndex], + _symbolicUb, + _inputLayerSize, + sourceLayerSize, + _size ); + matrixMultiplication( sourceLayer->getSymbolicLb(), + _layerToPositiveWeights[sourceLayerIndex], + _symbolicLb, + _inputLayerSize, + sourceLayerSize, + _size ); + matrixMultiplication( sourceLayer->getSymbolicUb(), + _layerToNegativeWeights[sourceLayerIndex], + _symbolicLb, + _inputLayerSize, + sourceLayerSize, + _size ); // Restore the zero bound on eliminated neurons unsigned index; @@ -1538,13 +1600,15 @@ void Layer::computeSymbolicBoundsForWeightedSum() if ( _lb[i] < _symbolicLbOfLb[i] ) { _lb[i] = _symbolicLbOfLb[i]; - _layerOwner->receiveTighterBound( Tightening( _neuronToVariable[i], _lb[i], Tightening::LB ) ); + _layerOwner->receiveTighterBound( + Tightening( _neuronToVariable[i], _lb[i], Tightening::LB ) ); } if ( _ub[i] > _symbolicUbOfUb[i] ) { _ub[i] = _symbolicUbOfUb[i]; - _layerOwner->receiveTighterBound( Tightening( _neuronToVariable[i], _ub[i], Tightening::UB ) ); + _layerOwner->receiveTighterBound( + Tightening( _neuronToVariable[i], _ub[i], Tightening::UB ) ); } } } @@ -1645,21 +1709,21 @@ Layer::Layer( const Layer *other ) if ( other->_layerToWeights.exists( sourceLayerEntry.first ) ) memcpy( _layerToWeights[sourceLayerEntry.first], other->_layerToWeights[sourceLayerEntry.first], - sizeof(double) * sourceLayerEntry.second * _size ); + sizeof( double ) * sourceLayerEntry.second * _size ); if ( other->_layerToPositiveWeights.exists( sourceLayerEntry.first ) ) memcpy( _layerToPositiveWeights[sourceLayerEntry.first], other->_layerToPositiveWeights[sourceLayerEntry.first], - sizeof(double) * sourceLayerEntry.second * _size ); + sizeof( double ) * sourceLayerEntry.second * _size ); if ( other->_layerToNegativeWeights.exists( sourceLayerEntry.first ) ) memcpy( _layerToNegativeWeights[sourceLayerEntry.first], other->_layerToNegativeWeights[sourceLayerEntry.first], - sizeof(double) * sourceLayerEntry.second * _size ); + sizeof( double ) * sourceLayerEntry.second * _size ); } if ( other->_bias ) - memcpy( _bias, other->_bias, sizeof(double) * _size ); + memcpy( _bias, other->_bias, sizeof( double ) * _size ); _neuronToActivationSources = other->_neuronToActivationSources; @@ -1834,16 +1898,16 @@ String Layer::typeToString( Type type ) break; case ROUND: - return "ROUND"; - break; + return "ROUND"; + break; case SOFTMAX: - return "SOFTMAX"; - break; + return "SOFTMAX"; + break; case BILINEAR: - return "BILINEAR"; - break; + return "BILINEAR"; + break; default: @@ -1942,10 +2006,10 @@ bool Layer::neuronHasVariable( unsigned neuron ) const unsigned Layer::neuronToVariable( unsigned neuron ) const { - DEBUG({ - if ( !_neuronToVariable.exists( neuron ) ) - ASSERT( _eliminatedNeurons.exists( neuron ) ); - }) + DEBUG( { + if ( !_neuronToVariable.exists( neuron ) ) + ASSERT( _eliminatedNeurons.exists( neuron ) ); + } ) ASSERT( _neuronToVariable.exists( neuron ) ); return _neuronToVariable[neuron]; @@ -2025,7 +2089,7 @@ bool Layer::operator==( const Layer &layer ) const if ( _bias && layer._bias ) { - if ( std::memcmp( _bias, layer._bias, _size * sizeof(double) ) != 0 ) + if ( std::memcmp( _bias, layer._bias, _size * sizeof( double ) ) != 0 ) return false; } @@ -2044,7 +2108,8 @@ bool Layer::operator==( const Layer &layer ) const return true; } -bool Layer::compareWeights( const Map &map, const Map &mapOfOtherLayer ) const +bool Layer::compareWeights( const Map &map, + const Map &mapOfOtherLayer ) const { if ( map.size() != mapOfOtherLayer.size() ) return false; @@ -2057,9 +2122,8 @@ bool Layer::compareWeights( const Map &map, const Map getActivationSources( unsigned neuron ) const; void setNeuronVariable( unsigned neuron, unsigned variable ); @@ -113,9 +107,9 @@ class Layer /* Set/get the simulations, or compute it from source layers */ - void setSimulations( const Vector> *values ); - void computeSimulations(); - const Vector> *getSimulations() const; + void setSimulations( const Vector> *values ); + void computeSimulations(); + const Vector> *getSimulations() const; /* Bound related functionality: grab the current bounds from the @@ -129,8 +123,14 @@ class Layer double *getLbs() const; double *getUbs() const; - void setAlpha( double alpha ) { _alpha = alpha; } - double getAlpha() const { return _alpha; } + void setAlpha( double alpha ) + { + _alpha = alpha; + } + double getAlpha() const + { + return _alpha; + } void obtainCurrentBounds( const InputQuery &inputQuery ); void obtainCurrentBounds(); @@ -158,7 +158,8 @@ class Layer void dump() const; static String typeToString( Type type ); bool operator==( const Layer &layer ) const; - bool compareWeights( const Map &map, const Map &mapOfOtherLayer ) const; + bool compareWeights( const Map &map, + const Map &mapOfOtherLayer ) const; private: unsigned _layerIndex; @@ -197,7 +198,7 @@ class Layer double *_symbolicUbOfUb; // A field variable to store parameter value. Right now it is only used to store the slope of - // leaky relus. Moving forward, we should keep a parameter map (e.g., Map) + // leaky relus. Moving forward, we should keep a parameter map (e.g., Map) // to store layer-specific information like "weights" and "alpha". double _alpha = 0; @@ -231,9 +232,8 @@ class Layer double getSymbolicLbOfUb( unsigned neuron ) const; double getSymbolicUbOfUb( unsigned neuron ) const; - void adjustWeightMapIndexing( Map &map, - unsigned indexToStart ); - }; + void adjustWeightMapIndexing( Map &map, unsigned indexToStart ); +}; } // namespace NLR diff --git a/src/nlr/LayerOwner.h b/src/nlr/LayerOwner.h index 636681bf54..9799c9474d 100644 --- a/src/nlr/LayerOwner.h +++ b/src/nlr/LayerOwner.h @@ -25,7 +25,9 @@ class Layer; class LayerOwner { public: - virtual ~LayerOwner() {} + virtual ~LayerOwner() + { + } virtual const Layer *getLayer( unsigned index ) const = 0; virtual const Map &getLayerIndexToLayer() const = 0; virtual unsigned getMaxLayerSize() const = 0; diff --git a/src/nlr/MILPFormulator.cpp b/src/nlr/MILPFormulator.cpp index f4dc58a44f..04ac4a44bd 100644 --- a/src/nlr/MILPFormulator.cpp +++ b/src/nlr/MILPFormulator.cpp @@ -13,11 +13,12 @@ **/ +#include "MILPFormulator.h" + #include "GurobiWrapper.h" #include "InfeasibleQueryException.h" #include "LPFormulator.h" #include "Layer.h" -#include "MILPFormulator.h" #include "MStringf.h" #include "NLRError.h" #include "Options.h" @@ -43,7 +44,8 @@ MILPFormulator::~MILPFormulator() { } -void MILPFormulator::optimizeBoundsWithIncrementalMILPEncoding( const Map &layers ) +void MILPFormulator::optimizeBoundsWithIncrementalMILPEncoding( + const Map &layers ) { _tighterBoundCounter = 0; _signChanges = 0; @@ -140,8 +142,11 @@ void MILPFormulator::optimizeBoundsWithIncrementalMILPEncoding( const Map &layers ) @@ -174,16 +179,18 @@ void MILPFormulator::optimizeBoundsWithMILPEncoding( const MapgetLayerIndex(), - currentLayer.first, - threads, - &solverToIndex ); + ThreadArgument argument( layer, + &layers, + std::ref( freeSolvers ), + std::ref( mtx ), + std::ref( infeasible ), + std::ref( tighterBoundCounter ), + std::ref( signChanges ), + std::ref( cutoffs ), + layer->getLayerIndex(), + currentLayer.first, + threads, + &solverToIndex ); // optimize every neuron of layer optimizeBoundsOfNeuronsWithMILPEncoding( argument ); @@ -197,15 +204,19 @@ void MILPFormulator::optimizeBoundsWithMILPEncoding( const Map &layers, unsigned targetIndex ) +void MILPFormulator::optimizeBoundsOfOneLayerWithMILPEncoding( const Map &layers, + unsigned targetIndex ) { unsigned numberOfWorkers = Options::get()->getInt( Options::NUM_WORKERS ); @@ -233,16 +244,18 @@ void MILPFormulator::optimizeBoundsOfOneLayerWithMILPEncoding( const Map &layers = *args._layers; unsigned targetIndex = args._targetIndex; @@ -290,8 +306,10 @@ void MILPFormulator::optimizeBoundsOfNeuronsWithMILPEncoding( ThreadArgument &ar bool skipTightenLb = false; // If true, skip lower bound tightening bool skipTightenUb = false; // If true, skip upper bound tightening - // declare simulations as local var to avoid a problem which can happen due to multi thread process. - const Vector> *simulations = _layerOwner->getLayer( targetIndex )->getSimulations(); + // declare simulations as local var to avoid a problem which can happen due to multi thread + // process. + const Vector> *simulations = + _layerOwner->getLayer( targetIndex )->getSimulations(); for ( unsigned i = 0; i < layer->getSize(); ++i ) { @@ -308,12 +326,14 @@ void MILPFormulator::optimizeBoundsOfNeuronsWithMILPEncoding( ThreadArgument &ar skipTightenUb = false; // Loop for simulation - for ( const auto &simValue : (*simulations).get( i ) ) + for ( const auto &simValue : ( *simulations ).get( i ) ) { - if ( _cutoffInUse && _cutoffValue < simValue ) // If x_lower < 0 < x_sim, do not try to call tightning upper bound. + if ( _cutoffInUse && _cutoffValue < simValue ) // If x_lower < 0 < x_sim, do not try to + // call tightning upper bound. skipTightenUb = true; - if ( _cutoffInUse && simValue < _cutoffValue ) // If x_sim < 0 < x_upper, do not try to call tightning lower bound. + if ( _cutoffInUse && simValue < _cutoffValue ) // If x_sim < 0 < x_upper, do not try to + // call tightning lower bound. skipTightenLb = true; if ( skipTightenUb && skipTightenLb ) @@ -324,18 +344,20 @@ void MILPFormulator::optimizeBoundsOfNeuronsWithMILPEncoding( ThreadArgument &ar if ( skipTightenUb && skipTightenLb ) { log( Stringf( "Skip tightening lower and upper bounds for layer %d index %u", - targetIndex, i ).ascii() ); + targetIndex, + i ) + .ascii() ); continue; } else if ( skipTightenUb ) { - log( Stringf( "Skip tightening upper bound for layer %u index %u", - targetIndex, i ).ascii() ); + log( Stringf( "Skip tightening upper bound for layer %u index %u", targetIndex, i ) + .ascii() ); } else if ( skipTightenLb ) { - log( Stringf( "Skip tightening lower bound for layer %u index %u", - targetIndex, i ).ascii() ); + log( Stringf( "Skip tightening lower bound for layer %u index %u", targetIndex, i ) + .ascii() ); } if ( infeasible ) @@ -362,22 +384,29 @@ void MILPFormulator::optimizeBoundsOfNeuronsWithMILPEncoding( ThreadArgument &ar mtx.unlock(); // spawn a thread to tighten the bounds for the current variable - ThreadArgument argument( freeSolver, layer, &layers, - i, currentLb, currentUb, - _cutoffInUse, _cutoffValue, - _layerOwner, std::ref( freeSolvers ), - std::ref( mtx ), std::ref( infeasible ), - std::ref( tighterBoundCounter ), - std::ref( signChanges ), - std::ref( cutoffs ), - skipTightenLb, - skipTightenUb ); + ThreadArgument argument( freeSolver, + layer, + &layers, + i, + currentLb, + currentUb, + _cutoffInUse, + _cutoffValue, + _layerOwner, + std::ref( freeSolvers ), + std::ref( mtx ), + std::ref( infeasible ), + std::ref( tighterBoundCounter ), + std::ref( signChanges ), + std::ref( cutoffs ), + skipTightenLb, + skipTightenUb ); if ( numberOfWorkers == 1 ) tightenSingleVariableBoundsWithMILPEncoding( argument ); else - threads[solverToIndex[freeSolver]] = boost::thread - ( tightenSingleVariableBoundsWithMILPEncoding, argument ); + threads[solverToIndex[freeSolver]] = + boost::thread( tightenSingleVariableBoundsWithMILPEncoding, argument ); } } @@ -419,8 +448,8 @@ void MILPFormulator::tightenSingleVariableBoundsWithMILPEncoding( ThreadArgument bool skipTightenUb = argument._skipTightenUb; // LP Relaxation - log( Stringf( "Tightening bounds for layer %u index %u", - layer->getLayerIndex(), index ).ascii() ); + log( Stringf( "Tightening bounds for layer %u index %u", layer->getLayerIndex(), index ) + .ascii() ); unsigned variable = layer->neuronToVariable( index ); Stringf variableName( "x%u", variable ); @@ -428,22 +457,19 @@ void MILPFormulator::tightenSingleVariableBoundsWithMILPEncoding( ThreadArgument if ( !skipTightenLb ) { log( Stringf( "Computing lowerbound..." ).ascii() ); - double lb = optimizeWithGurobi( *gurobi, MinOrMax::MIN, variableName, - cutoffValue, &infeasible ); + double lb = optimizeWithGurobi( + *gurobi, MinOrMax::MIN, variableName, cutoffValue, &infeasible ); log( Stringf( "Lowerbound computed: %f", lb ).ascii() ); // Store the new bound if it is tighter if ( lb > currentLb ) { - if ( FloatUtils::isNegative( currentLb ) && - !FloatUtils::isNegative( lb ) ) + if ( FloatUtils::isNegative( currentLb ) && !FloatUtils::isNegative( lb ) ) ++signChanges; mtx.lock(); layer->setLb( index, lb ); - layerOwner->receiveTighterBound( Tightening( variable, - lb, - Tightening::LB ) ); + layerOwner->receiveTighterBound( Tightening( variable, lb, Tightening::LB ) ); mtx.unlock(); ++tighterBoundCounter; @@ -460,22 +486,19 @@ void MILPFormulator::tightenSingleVariableBoundsWithMILPEncoding( ThreadArgument { log( Stringf( "Computing upperbound..." ).ascii() ); gurobi->reset(); - double ub = optimizeWithGurobi( *gurobi, MinOrMax::MAX, variableName, - cutoffValue, &infeasible ); + double ub = optimizeWithGurobi( + *gurobi, MinOrMax::MAX, variableName, cutoffValue, &infeasible ); log( Stringf( "Upperbound computed %f", ub ).ascii() ); // Store the new bound if it is tighter if ( ub < currentUb ) { - if ( FloatUtils::isPositive( currentUb ) && - !FloatUtils::isPositive( ub ) ) + if ( FloatUtils::isPositive( currentUb ) && !FloatUtils::isPositive( ub ) ) ++signChanges; mtx.lock(); layer->setUb( index, ub ); - layerOwner->receiveTighterBound( Tightening( variable, - ub, - Tightening::UB ) ); + layerOwner->receiveTighterBound( Tightening( variable, ub, Tightening::UB ) ); mtx.unlock(); ++tighterBoundCounter; @@ -504,22 +527,19 @@ void MILPFormulator::tightenSingleVariableBoundsWithMILPEncoding( ThreadArgument if ( !skipTightenLb ) { log( Stringf( "Computing lowerbound..." ).ascii() ); - double lb = optimizeWithGurobi( *gurobi, MinOrMax::MIN, variableName, - cutoffValue, &infeasible ); + double lb = optimizeWithGurobi( + *gurobi, MinOrMax::MIN, variableName, cutoffValue, &infeasible ); log( Stringf( "Lowerbound computed: %f", lb ).ascii() ); // Store the new bound if it is tighter if ( lb > currentLb ) { - if ( FloatUtils::isNegative( currentLb ) && - !FloatUtils::isNegative( lb ) ) + if ( FloatUtils::isNegative( currentLb ) && !FloatUtils::isNegative( lb ) ) ++signChanges; mtx.lock(); layer->setLb( index, lb ); - layerOwner->receiveTighterBound( Tightening( variable, - lb, - Tightening::LB ) ); + layerOwner->receiveTighterBound( Tightening( variable, lb, Tightening::LB ) ); mtx.unlock(); ++tighterBoundCounter; @@ -534,27 +554,24 @@ void MILPFormulator::tightenSingleVariableBoundsWithMILPEncoding( ThreadArgument if ( !skipTightenUb ) { - log( Stringf( "Tightening bounds for layer %u index %u", - layer->getLayerIndex(), index ).ascii() ); + log( Stringf( "Tightening bounds for layer %u index %u", layer->getLayerIndex(), index ) + .ascii() ); log( Stringf( "Computing upperbound..." ).ascii() ); gurobi->reset(); - double ub = optimizeWithGurobi( *gurobi, MinOrMax::MAX, variableName, - cutoffValue, &infeasible ); + double ub = optimizeWithGurobi( + *gurobi, MinOrMax::MAX, variableName, cutoffValue, &infeasible ); log( Stringf( "Upperbound computed %f", ub ).ascii() ); // Store the new bound if it is tighter if ( ub < currentUb ) { - if ( FloatUtils::isPositive( currentUb ) && - !FloatUtils::isPositive( ub ) ) + if ( FloatUtils::isPositive( currentUb ) && !FloatUtils::isPositive( ub ) ) ++signChanges; mtx.lock(); layer->setUb( index, ub ); - layerOwner->receiveTighterBound( Tightening( variable, - ub, - Tightening::UB ) ); + layerOwner->receiveTighterBound( Tightening( variable, ub, Tightening::UB ) ); mtx.unlock(); ++tighterBoundCounter; @@ -566,7 +583,7 @@ void MILPFormulator::tightenSingleVariableBoundsWithMILPEncoding( ThreadArgument enqueueSolver( freeSolvers, gurobi ); } - catch ( boost::thread_interrupted& ) + catch ( boost::thread_interrupted & ) { enqueueSolver( argument._freeSolvers, argument._gurobi ); } @@ -589,27 +606,30 @@ void MILPFormulator::createMILPEncoding( const Map &layers, } } -void MILPFormulator::addLayerToModel( GurobiWrapper &gurobi, const Layer *layer, +void MILPFormulator::addLayerToModel( GurobiWrapper &gurobi, + const Layer *layer, LayerOwner *layerOwner ) { switch ( layer->getLayerType() ) { - case Layer::INPUT: - case Layer::WEIGHTED_SUM: - break; + case Layer::INPUT: + case Layer::WEIGHTED_SUM: + break; - case Layer::RELU: - addReluLayerToMILPFormulation( gurobi, layer, layerOwner ); - break; + case Layer::RELU: + addReluLayerToMILPFormulation( gurobi, layer, layerOwner ); + break; - default: - throw NLRError( NLRError::LAYER_TYPE_NOT_SUPPORTED, "MILPFormulator" ); - break; + default: + throw NLRError( NLRError::LAYER_TYPE_NOT_SUPPORTED, "MILPFormulator" ); + break; } } -void MILPFormulator::addNeuronToModel( GurobiWrapper &gurobi, const Layer *layer, - unsigned neuron, LayerOwner *layerOwner ) +void MILPFormulator::addNeuronToModel( GurobiWrapper &gurobi, + const Layer *layer, + unsigned neuron, + LayerOwner *layerOwner ) { if ( layer->getLayerType() != Layer::RELU ) throw NLRError( NLRError::LAYER_TYPE_NOT_SUPPORTED, "MILPFormulator" ); @@ -627,8 +647,7 @@ void MILPFormulator::addNeuronToModel( GurobiWrapper &gurobi, const Layer *layer double sourceLb = sourceLayer->getLb( sourceNeuron ); double sourceUb = sourceLayer->getUb( sourceNeuron ); - if ( !FloatUtils::isNegative( sourceLb ) || - !FloatUtils::isPositive( sourceUb ) ) + if ( !FloatUtils::isNegative( sourceLb ) || !FloatUtils::isPositive( sourceUb ) ) { // This ReLU is fixed in one of its phases return; @@ -647,10 +666,7 @@ void MILPFormulator::addNeuronToModel( GurobiWrapper &gurobi, const Layer *layer y - ua <= 0 */ - gurobi.addVariable( Stringf( "a%u", targetVariable ), - 0, - 1, - GurobiWrapper::BINARY ); + gurobi.addVariable( Stringf( "a%u", targetVariable ), 0, 1, GurobiWrapper::BINARY ); List terms; terms.append( GurobiWrapper::Term( 1, Stringf( "x%u", targetVariable ) ) ); @@ -675,8 +691,10 @@ void MILPFormulator::addReluLayerToMILPFormulation( GurobiWrapper &gurobi, } double MILPFormulator::optimizeWithGurobi( GurobiWrapper &gurobi, - MinOrMax minOrMax, String variableName, - double cutoffValue, std::atomic_bool *infeasible ) + MinOrMax minOrMax, + String variableName, + double cutoffValue, + std::atomic_bool *infeasible ) { List terms; terms.append( GurobiWrapper::Term( 1, variableName ) ); @@ -717,7 +735,10 @@ double MILPFormulator::optimizeWithGurobi( GurobiWrapper &gurobi, throw NLRError( NLRError::UNEXPECTED_RETURN_STATUS_FROM_GUROBI ); } -void MILPFormulator::storeUbIfNeeded( Layer *layer, unsigned neuron, unsigned variable, double newUb ) +void MILPFormulator::storeUbIfNeeded( Layer *layer, + unsigned neuron, + unsigned variable, + double newUb ) { double ub = layer->getUb( neuron ); if ( newUb < ub ) @@ -726,14 +747,15 @@ void MILPFormulator::storeUbIfNeeded( Layer *layer, unsigned neuron, unsigned va ++_signChanges; layer->setUb( neuron, newUb ); - _layerOwner->receiveTighterBound( Tightening( variable, - newUb, - Tightening::UB ) ); + _layerOwner->receiveTighterBound( Tightening( variable, newUb, Tightening::UB ) ); ++_tighterBoundCounter; } } -void MILPFormulator::storeLbIfNeeded( Layer *layer, unsigned neuron, unsigned variable, double newLb ) +void MILPFormulator::storeLbIfNeeded( Layer *layer, + unsigned neuron, + unsigned variable, + double newLb ) { double lb = layer->getLb( neuron ); if ( newLb > lb ) @@ -742,9 +764,7 @@ void MILPFormulator::storeLbIfNeeded( Layer *layer, unsigned neuron, unsigned va ++_signChanges; layer->setLb( neuron, newLb ); - _layerOwner->receiveTighterBound( Tightening( variable, - newLb, - Tightening::LB ) ); + _layerOwner->receiveTighterBound( Tightening( variable, newLb, Tightening::LB ) ); ++_tighterBoundCounter; } } @@ -801,14 +821,11 @@ bool MILPFormulator::tightenUpperBound( GurobiWrapper &gurobi, { gurobi.setUpperBound( variableName, newUb ); - if ( FloatUtils::isPositive( currentUb ) && - !FloatUtils::isPositive( newUb ) ) + if ( FloatUtils::isPositive( currentUb ) && !FloatUtils::isPositive( newUb ) ) ++_signChanges; layer->setUb( neuron, newUb ); - _layerOwner->receiveTighterBound( Tightening( variable, - newUb, - Tightening::UB ) ); + _layerOwner->receiveTighterBound( Tightening( variable, newUb, Tightening::UB ) ); ++_tighterBoundCounter; currentUb = newUb; @@ -865,14 +882,11 @@ bool MILPFormulator::tightenLowerBound( GurobiWrapper &gurobi, { gurobi.setLowerBound( variableName, newLb ); - if ( FloatUtils::isNegative( currentLb ) && - !FloatUtils::isNegative( newLb ) ) + if ( FloatUtils::isNegative( currentLb ) && !FloatUtils::isNegative( newLb ) ) ++_signChanges; layer->setLb( neuron, newLb ); - _layerOwner->receiveTighterBound( Tightening( variable, - newLb, - Tightening::LB ) ); + _layerOwner->receiveTighterBound( Tightening( variable, newLb, Tightening::LB ) ); ++_tighterBoundCounter; currentLb = newLb; diff --git a/src/nlr/MILPFormulator.h b/src/nlr/MILPFormulator.h index a4f9819f61..6ebfdebfc6 100644 --- a/src/nlr/MILPFormulator.h +++ b/src/nlr/MILPFormulator.h @@ -17,12 +17,12 @@ #define __MILPFormulator_h__ #include "GurobiWrapper.h" -#include "LayerOwner.h" #include "LPFormulator.h" +#include "LayerOwner.h" #include -#include #include +#include #include #include @@ -40,7 +40,8 @@ class MILPFormulator : public ParallelSolver ~MILPFormulator(); void optimizeBoundsWithMILPEncoding( const Map &layers ); - void optimizeBoundsOfOneLayerWithMILPEncoding( const Map &layers, unsigned targetIndex ); + void optimizeBoundsOfOneLayerWithMILPEncoding( const Map &layers, + unsigned targetIndex ); void optimizeBoundsWithIncrementalMILPEncoding( const Map &layers ); /* @@ -75,8 +76,8 @@ class MILPFormulator : public ParallelSolver unsigned variable, double ¤tUb ); - static void addLayerToModel( GurobiWrapper &gurobi, const Layer *layer, - LayerOwner *layerOwner ); + static void + addLayerToModel( GurobiWrapper &gurobi, const Layer *layer, LayerOwner *layerOwner ); static void addReluLayerToMILPFormulation( GurobiWrapper &gurobi, const Layer *layer, @@ -91,19 +92,15 @@ class MILPFormulator : public ParallelSolver Optimize for the min/max value of variableName with respect to the constraints encoded in gurobi. If the query is infeasible, *infeasible is set to true. */ - static double optimizeWithGurobi( GurobiWrapper &gurobi, MinOrMax minOrMax, - String variableName, double cutoffValue, + static double optimizeWithGurobi( GurobiWrapper &gurobi, + MinOrMax minOrMax, + String variableName, + double cutoffValue, std::atomic_bool *infeasible = NULL ); - void storeUbIfNeeded( Layer *layer, - unsigned neuron, - unsigned variable, - double newUb ); + void storeUbIfNeeded( Layer *layer, unsigned neuron, unsigned variable, double newUb ); - void storeLbIfNeeded( Layer *layer, - unsigned neuron, - unsigned variable, - double newLb ); + void storeLbIfNeeded( Layer *layer, unsigned neuron, unsigned variable, double newLb ); bool layerRequiresMILPEncoding( const Layer *layer ); diff --git a/src/nlr/NLRError.h b/src/nlr/NLRError.h index e35732e80a..2f03cb0b89 100644 --- a/src/nlr/NLRError.h +++ b/src/nlr/NLRError.h @@ -21,18 +21,20 @@ class NLRError : public Error { public: - enum Code { + enum Code { UNEXPECTED_RETURN_STATUS_FROM_GUROBI = 0, LAYER_TYPE_NOT_SUPPORTED = 1, INPUT_LAYER_NOT_THE_FIRST_LAYER = 2, LEAKY_RELU_SLOPES_NOT_UNIFORM = 3, }; - NLRError( NLRError::Code code ) : Error( "NLRError", (int)code ) - { - } + NLRError( NLRError::Code code ) + : Error( "NLRError", (int)code ) + { + } - NLRError( NLRError::Code code, const char *userMessage ) : Error( "NLRError", (int)code, userMessage ) + NLRError( NLRError::Code code, const char *userMessage ) + : Error( "NLRError", (int)code, userMessage ) { } }; diff --git a/src/nlr/NetworkLevelReasoner.cpp b/src/nlr/NetworkLevelReasoner.cpp index 3448d6fbc6..e145e85338 100644 --- a/src/nlr/NetworkLevelReasoner.cpp +++ b/src/nlr/NetworkLevelReasoner.cpp @@ -13,6 +13,8 @@ **/ +#include "NetworkLevelReasoner.h" + #include "AbsoluteValueConstraint.h" #include "Debug.h" #include "FloatUtils.h" @@ -26,10 +28,10 @@ #include "MatrixMultiplication.h" #include "MaxConstraint.h" #include "NLRError.h" -#include "NetworkLevelReasoner.h" #include "Options.h" #include "ReluConstraint.h" #include "SignConstraint.h" + #include namespace NLR { @@ -67,7 +69,8 @@ void NetworkLevelReasoner::addLayer( unsigned layerIndex, Layer::Type type, unsi void NetworkLevelReasoner::addLayerDependency( unsigned sourceLayer, unsigned targetLayer ) { - _layerIndexToLayer[targetLayer]->addSourceLayer( sourceLayer, _layerIndexToLayer[sourceLayer]->getSize() ); + _layerIndexToLayer[targetLayer]->addSourceLayer( sourceLayer, + _layerIndexToLayer[sourceLayer]->getSize() ); } void NetworkLevelReasoner::setWeight( unsigned sourceLayer, @@ -76,8 +79,7 @@ void NetworkLevelReasoner::setWeight( unsigned sourceLayer, unsigned targetNeuron, double weight ) { - _layerIndexToLayer[targetLayer]->setWeight - ( sourceLayer, sourceNeuron, targetNeuron, weight ); + _layerIndexToLayer[targetLayer]->setWeight( sourceLayer, sourceNeuron, targetNeuron, weight ); } void NetworkLevelReasoner::setBias( unsigned layer, unsigned neuron, double bias ) @@ -110,13 +112,10 @@ void NetworkLevelReasoner::evaluate( double *input, double *output ) _layerIndexToLayer[i]->computeAssignment(); const Layer *outputLayer = _layerIndexToLayer[_layerIndexToLayer.size() - 1]; - memcpy( output, - outputLayer->getAssignment(), - sizeof(double) * outputLayer->getSize() ); + memcpy( output, outputLayer->getAssignment(), sizeof( double ) * outputLayer->getSize() ); } -void NetworkLevelReasoner::concretizeInputAssignment( Map - &assignment ) +void NetworkLevelReasoner::concretizeInputAssignment( Map &assignment ) { Layer *inputLayer = _layerIndexToLayer[0]; ASSERT( inputLayer->getLayerType() == Layer::INPUT ); @@ -195,8 +194,7 @@ void NetworkLevelReasoner::symbolicBoundPropagation() void NetworkLevelReasoner::deepPolyPropagation() { if ( _deepPolyAnalysis == nullptr ) - _deepPolyAnalysis = std::unique_ptr - ( new DeepPolyAnalysis( this ) ); + _deepPolyAnalysis = std::unique_ptr( new DeepPolyAnalysis( this ) ); _deepPolyAnalysis->run(); } @@ -328,11 +326,14 @@ void NetworkLevelReasoner::dumpTopology( bool dumpLayerDetails ) const printf( "Number of layers: %u. Sizes:\n", _layerIndexToLayer.size() ); for ( unsigned i = 0; i < _layerIndexToLayer.size(); ++i ) { - printf( "\tLayer %u: %u \t[%s]", i, _layerIndexToLayer[i]->getSize(), Layer::typeToString( _layerIndexToLayer[i]->getLayerType() ).ascii() ); - printf("\tSource layers:"); + printf( "\tLayer %u: %u \t[%s]", + i, + _layerIndexToLayer[i]->getSize(), + Layer::typeToString( _layerIndexToLayer[i]->getLayerType() ).ascii() ); + printf( "\tSource layers:" ); for ( const auto &sourceLayer : _layerIndexToLayer[i]->getSourceLayers() ) - printf(" %u", sourceLayer.first ); - printf("\n"); + printf( " %u", sourceLayer.first ); + printf( "\n" ); } if ( dumpLayerDetails ) for ( const auto &layer : _layerIndexToLayer ) @@ -354,7 +355,8 @@ void NetworkLevelReasoner::addConstraintInTopologicalOrder( PiecewiseLinearConst _constraintsInTopologicalOrder.append( constraint ); } -void NetworkLevelReasoner::removeConstraintFromTopologicalOrder( PiecewiseLinearConstraint *constraint ) +void NetworkLevelReasoner::removeConstraintFromTopologicalOrder( + PiecewiseLinearConstraint *constraint ) { if ( _constraintsInTopologicalOrder.exists( constraint ) ) _constraintsInTopologicalOrder.erase( constraint ); @@ -418,8 +420,7 @@ void NetworkLevelReasoner::reindexNeurons() } } -void NetworkLevelReasoner::generateInputQueryForLayer( InputQuery &inputQuery, - const Layer &layer ) +void NetworkLevelReasoner::generateInputQueryForLayer( InputQuery &inputQuery, const Layer &layer ) { switch ( layer.getLayerType() ) { @@ -457,51 +458,60 @@ void NetworkLevelReasoner::generateInputQueryForLayer( InputQuery &inputQuery, } } -void NetworkLevelReasoner::generateInputQueryForReluLayer( InputQuery &inputQuery, const Layer &layer ) +void NetworkLevelReasoner::generateInputQueryForReluLayer( InputQuery &inputQuery, + const Layer &layer ) { for ( unsigned i = 0; i < layer.getSize(); ++i ) { NeuronIndex sourceIndex = *layer.getActivationSources( i ).begin(); const Layer *sourceLayer = _layerIndexToLayer[sourceIndex._layer]; - ReluConstraint *relu = new ReluConstraint( sourceLayer->neuronToVariable( sourceIndex._neuron ), layer.neuronToVariable( i ) ); + ReluConstraint *relu = new ReluConstraint( + sourceLayer->neuronToVariable( sourceIndex._neuron ), layer.neuronToVariable( i ) ); inputQuery.addPiecewiseLinearConstraint( relu ); } } -void NetworkLevelReasoner::generateInputQueryForSigmoidLayer( InputQuery &inputQuery, const Layer &layer ) +void NetworkLevelReasoner::generateInputQueryForSigmoidLayer( InputQuery &inputQuery, + const Layer &layer ) { for ( unsigned i = 0; i < layer.getSize(); ++i ) { NeuronIndex sourceIndex = *layer.getActivationSources( i ).begin(); const Layer *sourceLayer = _layerIndexToLayer[sourceIndex._layer]; - SigmoidConstraint *sigmoid = new SigmoidConstraint( sourceLayer->neuronToVariable( sourceIndex._neuron ), layer.neuronToVariable( i ) ); + SigmoidConstraint *sigmoid = new SigmoidConstraint( + sourceLayer->neuronToVariable( sourceIndex._neuron ), layer.neuronToVariable( i ) ); inputQuery.addNonlinearConstraint( sigmoid ); } } -void NetworkLevelReasoner::generateInputQueryForSignLayer( InputQuery &inputQuery, const Layer &layer ) +void NetworkLevelReasoner::generateInputQueryForSignLayer( InputQuery &inputQuery, + const Layer &layer ) { for ( unsigned i = 0; i < layer.getSize(); ++i ) { NeuronIndex sourceIndex = *layer.getActivationSources( i ).begin(); const Layer *sourceLayer = _layerIndexToLayer[sourceIndex._layer]; - SignConstraint *sign = new SignConstraint( sourceLayer->neuronToVariable( sourceIndex._neuron ), layer.neuronToVariable( i ) ); + SignConstraint *sign = new SignConstraint( + sourceLayer->neuronToVariable( sourceIndex._neuron ), layer.neuronToVariable( i ) ); inputQuery.addPiecewiseLinearConstraint( sign ); } } -void NetworkLevelReasoner::generateInputQueryForAbsoluteValueLayer( InputQuery &inputQuery, const Layer &layer ) +void NetworkLevelReasoner::generateInputQueryForAbsoluteValueLayer( InputQuery &inputQuery, + const Layer &layer ) { for ( unsigned i = 0; i < layer.getSize(); ++i ) { NeuronIndex sourceIndex = *layer.getActivationSources( i ).begin(); const Layer *sourceLayer = _layerIndexToLayer[sourceIndex._layer]; - AbsoluteValueConstraint *absoluteValue = new AbsoluteValueConstraint( sourceLayer->neuronToVariable( sourceIndex._neuron ), layer.neuronToVariable( i ) ); + AbsoluteValueConstraint *absoluteValue = new AbsoluteValueConstraint( + sourceLayer->neuronToVariable( sourceIndex._neuron ), layer.neuronToVariable( i ) ); inputQuery.addPiecewiseLinearConstraint( absoluteValue ); } } -void NetworkLevelReasoner::generateInputQueryForMaxLayer( InputQuery &inputQuery, const Layer &layer ) +void NetworkLevelReasoner::generateInputQueryForMaxLayer( InputQuery &inputQuery, + const Layer &layer ) { for ( unsigned i = 0; i < layer.getSize(); ++i ) { @@ -512,13 +522,13 @@ void NetworkLevelReasoner::generateInputQueryForMaxLayer( InputQuery &inputQuery elements.insert( sourceLayer->neuronToVariable( source._neuron ) ); } - MaxConstraint *max = new MaxConstraint( layer.neuronToVariable( i ), - elements ); + MaxConstraint *max = new MaxConstraint( layer.neuronToVariable( i ), elements ); inputQuery.addPiecewiseLinearConstraint( max ); } } -void NetworkLevelReasoner::generateInputQueryForWeightedSumLayer( InputQuery &inputQuery, const Layer &layer ) +void NetworkLevelReasoner::generateInputQueryForWeightedSumLayer( InputQuery &inputQuery, + const Layer &layer ) { for ( unsigned i = 0; i < layer.getSize(); ++i ) { @@ -612,21 +622,17 @@ void NetworkLevelReasoner::mergeWSLayers( unsigned secondLayerIndex ) // Compute new weights const double *firstLayerMatrix = firstLayer->getWeightMatrix( previousToFirstLayerIndex ); const double *secondLayerMatrix = secondLayer->getWeightMatrix( firstLayerIndex ); - double *newWeightMatrix = multiplyWeights( firstLayerMatrix, - secondLayerMatrix, - inputDimension, - middleDimension, - outputDimension ); + double *newWeightMatrix = multiplyWeights( + firstLayerMatrix, secondLayerMatrix, inputDimension, middleDimension, outputDimension ); // Update bias for second layer for ( unsigned targetNeuron = 0; targetNeuron < secondLayer->getSize(); ++targetNeuron ) { double newBias = secondLayer->getBias( targetNeuron ); - for ( unsigned sourceNeuron = 0; - sourceNeuron < firstLayer->getSize(); - ++sourceNeuron ) + for ( unsigned sourceNeuron = 0; sourceNeuron < firstLayer->getSize(); ++sourceNeuron ) { - newBias += ( firstLayer->getBias( sourceNeuron ) * - secondLayer->getWeight( firstLayerIndex, sourceNeuron, targetNeuron ) ); + newBias += + ( firstLayer->getBias( sourceNeuron ) * + secondLayer->getWeight( firstLayerIndex, sourceNeuron, targetNeuron ) ); } secondLayer->setBias( targetNeuron, newBias ); @@ -639,10 +645,8 @@ void NetworkLevelReasoner::mergeWSLayers( unsigned secondLayerIndex ) for ( unsigned targetNeuron = 0; targetNeuron < outputDimension; ++targetNeuron ) { double weight = newWeightMatrix[sourceNeuron * outputDimension + targetNeuron]; - secondLayer->setWeight( previousToFirstLayerIndex, - sourceNeuron, - targetNeuron, - weight ); + secondLayer->setWeight( + previousToFirstLayerIndex, sourceNeuron, targetNeuron, weight ); } } delete[] newWeightMatrix; @@ -669,12 +673,8 @@ double *NetworkLevelReasoner::multiplyWeights( const double *firstMatrix, { double *newMatrix = new double[inputDimension * outputDimension]; std::fill_n( newMatrix, inputDimension * outputDimension, 0 ); - matrixMultiplication( firstMatrix, - secondMatrix, - newMatrix, - inputDimension, - middleDimension, - outputDimension ); + matrixMultiplication( + firstMatrix, secondMatrix, newMatrix, inputDimension, middleDimension, outputDimension ); return newMatrix; } diff --git a/src/nlr/NetworkLevelReasoner.h b/src/nlr/NetworkLevelReasoner.h index 1e07937069..23ce6c0f69 100644 --- a/src/nlr/NetworkLevelReasoner.h +++ b/src/nlr/NetworkLevelReasoner.h @@ -72,7 +72,7 @@ class NetworkLevelReasoner : public LayerOwner /* Perform an evaluation of the network for a specific input. */ - void evaluate( double *input , double *output ); + void evaluate( double *input, double *output ); /* Perform an evaluation of the network for the current input variable @@ -83,7 +83,7 @@ class NetworkLevelReasoner : public LayerOwner /* Perform a simulation of the network for a specific input */ - void simulate( Vector> *input ); + void simulate( Vector> *input ); /* Bound propagation methods: @@ -136,7 +136,7 @@ class NetworkLevelReasoner : public LayerOwner /* For debugging purposes: dump the network topology */ - void dumpTopology( bool dumpLayerDetails=true ) const; + void dumpTopology( bool dumpLayerDetails = true ) const; /* Duplicate the reasoner diff --git a/src/nlr/ParallelSolver.cpp b/src/nlr/ParallelSolver.cpp index 7944ef35c3..f2449008b0 100644 --- a/src/nlr/ParallelSolver.cpp +++ b/src/nlr/ParallelSolver.cpp @@ -13,12 +13,13 @@ **/ +#include "ParallelSolver.h" + #include "InfeasibleQueryException.h" #include "Layer.h" #include "MStringf.h" #include "NLRError.h" #include "Options.h" -#include "ParallelSolver.h" #include "TimeUtils.h" #include diff --git a/src/nlr/ParallelSolver.h b/src/nlr/ParallelSolver.h index 35f23faaa6..9b043f220a 100644 --- a/src/nlr/ParallelSolver.h +++ b/src/nlr/ParallelSolver.h @@ -32,107 +32,128 @@ struct NeuronIndex; class ParallelSolver { public: - - typedef boost::lockfree::queue - > SolverQueue; + typedef boost::lockfree::queue> SolverQueue; /* Arguments for the spawned thread. This is needed because Boost::thread does not seem to support functions with more than 7 arguments. */ - struct ThreadArgument{ - - ThreadArgument( GurobiWrapper *gurobi, Layer *layer, + struct ThreadArgument + { + ThreadArgument( GurobiWrapper *gurobi, + Layer *layer, const Map *layers, - unsigned index, double currentLb, double currentUb, - bool cutoffInUse, double cutoffValue, - LayerOwner *layerOwner, SolverQueue &freeSolvers, - std::mutex &mtx, std::atomic_bool &infeasible, + unsigned index, + double currentLb, + double currentUb, + bool cutoffInUse, + double cutoffValue, + LayerOwner *layerOwner, + SolverQueue &freeSolvers, + std::mutex &mtx, + std::atomic_bool &infeasible, std::atomic_uint &tighterBoundCounter, std::atomic_uint &signChanges, std::atomic_uint &cutoffs, - bool skipTightenLb, bool skipTightenUb ) - : _gurobi( gurobi ) - , _layer( layer ) - , _layers( layers ) - , _index( index ) - , _currentLb(currentLb ) - , _currentUb(currentUb ) - , _cutoffInUse( cutoffInUse ) - , _cutoffValue( cutoffValue ) - , _layerOwner( layerOwner ) - , _freeSolvers( freeSolvers ) - , _mtx( mtx ) - , _infeasible( infeasible ) - , _tighterBoundCounter( tighterBoundCounter ) - , _signChanges( signChanges ) - , _cutoffs( cutoffs ) - , _skipTightenLb ( skipTightenLb ) - , _skipTightenUb ( skipTightenUb ) - , _lastFixedNeuron( NULL ) + bool skipTightenLb, + bool skipTightenUb ) + : _gurobi( gurobi ) + , _layer( layer ) + , _layers( layers ) + , _index( index ) + , _currentLb( currentLb ) + , _currentUb( currentUb ) + , _cutoffInUse( cutoffInUse ) + , _cutoffValue( cutoffValue ) + , _layerOwner( layerOwner ) + , _freeSolvers( freeSolvers ) + , _mtx( mtx ) + , _infeasible( infeasible ) + , _tighterBoundCounter( tighterBoundCounter ) + , _signChanges( signChanges ) + , _cutoffs( cutoffs ) + , _skipTightenLb( skipTightenLb ) + , _skipTightenUb( skipTightenUb ) + , _lastFixedNeuron( NULL ) { } - ThreadArgument( GurobiWrapper *gurobi, Layer *layer, - unsigned index, double currentLb, double currentUb, - bool cutoffInUse, double cutoffValue, - LayerOwner *layerOwner, SolverQueue &freeSolvers, - std::mutex &mtx, std::atomic_bool &infeasible, + ThreadArgument( GurobiWrapper *gurobi, + Layer *layer, + unsigned index, + double currentLb, + double currentUb, + bool cutoffInUse, + double cutoffValue, + LayerOwner *layerOwner, + SolverQueue &freeSolvers, + std::mutex &mtx, + std::atomic_bool &infeasible, std::atomic_uint &tighterBoundCounter, std::atomic_uint &signChanges, std::atomic_uint &cutoffs, - bool skipTightenLb, bool skipTightenUb ) - : _gurobi( gurobi ) - , _layer( layer ) - , _layers( NULL ) - , _index( index ) - , _currentLb( currentLb ) - , _currentUb( currentUb ) - , _cutoffInUse( cutoffInUse ) - , _cutoffValue( cutoffValue ) - , _layerOwner( layerOwner ) - , _freeSolvers( freeSolvers ) - , _mtx( mtx ) - , _infeasible( infeasible ) - , _tighterBoundCounter( tighterBoundCounter ) - , _signChanges( signChanges ) - , _cutoffs( cutoffs ) - , _skipTightenLb ( skipTightenLb ) - , _skipTightenUb ( skipTightenUb ) - , _lastFixedNeuron( NULL ) + bool skipTightenLb, + bool skipTightenUb ) + : _gurobi( gurobi ) + , _layer( layer ) + , _layers( NULL ) + , _index( index ) + , _currentLb( currentLb ) + , _currentUb( currentUb ) + , _cutoffInUse( cutoffInUse ) + , _cutoffValue( cutoffValue ) + , _layerOwner( layerOwner ) + , _freeSolvers( freeSolvers ) + , _mtx( mtx ) + , _infeasible( infeasible ) + , _tighterBoundCounter( tighterBoundCounter ) + , _signChanges( signChanges ) + , _cutoffs( cutoffs ) + , _skipTightenLb( skipTightenLb ) + , _skipTightenUb( skipTightenUb ) + , _lastFixedNeuron( NULL ) { } - ThreadArgument( GurobiWrapper *gurobi, Layer *layer, - unsigned index, double currentLb, double currentUb, - bool cutoffInUse, double cutoffValue, - LayerOwner *layerOwner, SolverQueue &freeSolvers, - std::mutex &mtx, std::atomic_bool &infeasible, + ThreadArgument( GurobiWrapper *gurobi, + Layer *layer, + unsigned index, + double currentLb, + double currentUb, + bool cutoffInUse, + double cutoffValue, + LayerOwner *layerOwner, + SolverQueue &freeSolvers, + std::mutex &mtx, + std::atomic_bool &infeasible, std::atomic_uint &tighterBoundCounter, std::atomic_uint &signChanges, - std::atomic_uint &cutoffs, NeuronIndex *lastFixedNeuron ) - : _gurobi( gurobi ) - , _layer( layer ) - , _layers( NULL ) - , _index( index ) - , _currentLb( currentLb ) - , _currentUb( currentUb ) - , _cutoffInUse( cutoffInUse ) - , _cutoffValue( cutoffValue ) - , _layerOwner( layerOwner ) - , _freeSolvers( freeSolvers ) - , _mtx( mtx ) - , _infeasible( infeasible ) - , _tighterBoundCounter( tighterBoundCounter ) - , _signChanges( signChanges ) - , _cutoffs( cutoffs ) - , _lastFixedNeuron( lastFixedNeuron ) + std::atomic_uint &cutoffs, + NeuronIndex *lastFixedNeuron ) + : _gurobi( gurobi ) + , _layer( layer ) + , _layers( NULL ) + , _index( index ) + , _currentLb( currentLb ) + , _currentUb( currentUb ) + , _cutoffInUse( cutoffInUse ) + , _cutoffValue( cutoffValue ) + , _layerOwner( layerOwner ) + , _freeSolvers( freeSolvers ) + , _mtx( mtx ) + , _infeasible( infeasible ) + , _tighterBoundCounter( tighterBoundCounter ) + , _signChanges( signChanges ) + , _cutoffs( cutoffs ) + , _lastFixedNeuron( lastFixedNeuron ) { } - ThreadArgument( Layer *layer, const Map *layers, + ThreadArgument( Layer *layer, + const Map *layers, SolverQueue &freeSolvers, - std::mutex &mtx, std::atomic_bool &infeasible, + std::mutex &mtx, + std::atomic_bool &infeasible, std::atomic_uint &tighterBoundCounter, std::atomic_uint &signChanges, std::atomic_uint &cutoffs, @@ -140,18 +161,18 @@ class ParallelSolver unsigned targetIndex, boost::thread *threads, const Map *solverToIndex ) - : _layer( layer ) - , _layers( layers ) - , _freeSolvers( freeSolvers ) - , _mtx( mtx ) - , _infeasible( infeasible ) - , _tighterBoundCounter( tighterBoundCounter ) - , _signChanges( signChanges ) - , _cutoffs( cutoffs ) - , _lastIndexOfRelaxation( lastIndexOfRelaxation ) - , _targetIndex ( targetIndex ) - , _threads( threads ) - , _solverToIndex( solverToIndex ) + : _layer( layer ) + , _layers( layers ) + , _freeSolvers( freeSolvers ) + , _mtx( mtx ) + , _infeasible( infeasible ) + , _tighterBoundCounter( tighterBoundCounter ) + , _signChanges( signChanges ) + , _cutoffs( cutoffs ) + , _lastIndexOfRelaxation( lastIndexOfRelaxation ) + , _targetIndex( targetIndex ) + , _threads( threads ) + , _solverToIndex( solverToIndex ) { } diff --git a/src/nlr/SoftmaxBoundType.h b/src/nlr/SoftmaxBoundType.h index bcbc9792cf..44b2c1e82d 100644 --- a/src/nlr/SoftmaxBoundType.h +++ b/src/nlr/SoftmaxBoundType.h @@ -21,10 +21,9 @@ Details can be found in "Convex Bounds on the Softmax Function with Applications to Robustness Verification" by Wei et al. AISTATS'23 */ -enum class SoftmaxBoundType -{ - EXPONENTIAL_RECIPROCAL_DECOMPOSITION = 0, - LOG_SUM_EXP_DECOMPOSITION = 1 +enum class SoftmaxBoundType { + EXPONENTIAL_RECIPROCAL_DECOMPOSITION = 0, + LOG_SUM_EXP_DECOMPOSITION = 1 }; #endif // __SoftmaxBoundType_h__ diff --git a/src/nlr/tests/Test_DeepPolyAnalysis.h b/src/nlr/tests/Test_DeepPolyAnalysis.h index a47d3cff77..521a8114a2 100644 --- a/src/nlr/tests/Test_DeepPolyAnalysis.h +++ b/src/nlr/tests/Test_DeepPolyAnalysis.h @@ -185,32 +185,23 @@ class DeepPolyAnalysisTestSuite : public CxxTest::TestSuite */ - List expectedBounds( { Tightening( 2, -2, Tightening::LB ), - Tightening( 2, 2, Tightening::UB ), - Tightening( 3, -2, Tightening::LB ), - Tightening( 3, 2, Tightening::UB ), + List expectedBounds( + { Tightening( 2, -2, Tightening::LB ), Tightening( 2, 2, Tightening::UB ), + Tightening( 3, -2, Tightening::LB ), Tightening( 3, 2, Tightening::UB ), - Tightening( 4, 0, Tightening::LB ), - Tightening( 4, 2, Tightening::UB ), - Tightening( 5, 0, Tightening::LB ), - Tightening( 5, 2, Tightening::UB ), + Tightening( 4, 0, Tightening::LB ), Tightening( 4, 2, Tightening::UB ), + Tightening( 5, 0, Tightening::LB ), Tightening( 5, 2, Tightening::UB ), - Tightening( 6, 0, Tightening::LB ), - Tightening( 6, 3, Tightening::UB ), - Tightening( 7, -2, Tightening::LB ), - Tightening( 7, 2, Tightening::UB ), + Tightening( 6, 0, Tightening::LB ), Tightening( 6, 3, Tightening::UB ), + Tightening( 7, -2, Tightening::LB ), Tightening( 7, 2, Tightening::UB ), - Tightening( 8, 0, Tightening::LB ), - Tightening( 8, 3, Tightening::UB ), - Tightening( 9, 0, Tightening::LB ), - Tightening( 9, 2, Tightening::UB ), + Tightening( 8, 0, Tightening::LB ), Tightening( 8, 3, Tightening::UB ), + Tightening( 9, 0, Tightening::LB ), Tightening( 9, 2, Tightening::UB ), - Tightening( 10, 1, Tightening::LB ), - Tightening( 10, 5.5, Tightening::UB ), - Tightening( 11, 0, Tightening::LB ), - Tightening( 11, 2, Tightening::UB ) + Tightening( 10, 1, Tightening::LB ), Tightening( 10, 5.5, Tightening::UB ), + Tightening( 11, 0, Tightening::LB ), Tightening( 11, 2, Tightening::UB ) - } ); + } ); List bounds; TS_ASSERT_THROWS_NOTHING( nlr.getConstraintTightenings( bounds ) ); @@ -765,32 +756,23 @@ class DeepPolyAnalysisTestSuite : public CxxTest::TestSuite */ - List expectedBounds( { Tightening( 2, -2, Tightening::LB ), - Tightening( 2, 2, Tightening::UB ), - Tightening( 3, -2, Tightening::LB ), - Tightening( 3, 2, Tightening::UB ), + List expectedBounds( + { Tightening( 2, -2, Tightening::LB ), Tightening( 2, 2, Tightening::UB ), + Tightening( 3, -2, Tightening::LB ), Tightening( 3, 2, Tightening::UB ), - Tightening( 4, 0, Tightening::LB ), - Tightening( 4, 2, Tightening::UB ), - Tightening( 5, 0, Tightening::LB ), - Tightening( 5, 2, Tightening::UB ), + Tightening( 4, 0, Tightening::LB ), Tightening( 4, 2, Tightening::UB ), + Tightening( 5, 0, Tightening::LB ), Tightening( 5, 2, Tightening::UB ), - Tightening( 6, 0, Tightening::LB ), - Tightening( 6, 3, Tightening::UB ), - Tightening( 7, -2, Tightening::LB ), - Tightening( 7, 2, Tightening::UB ), + Tightening( 6, 0, Tightening::LB ), Tightening( 6, 3, Tightening::UB ), + Tightening( 7, -2, Tightening::LB ), Tightening( 7, 2, Tightening::UB ), - Tightening( 8, 0, Tightening::LB ), - Tightening( 8, 3, Tightening::UB ), - Tightening( 9, 0, Tightening::LB ), - Tightening( 9, 2, Tightening::UB ), + Tightening( 8, 0, Tightening::LB ), Tightening( 8, 3, Tightening::UB ), + Tightening( 9, 0, Tightening::LB ), Tightening( 9, 2, Tightening::UB ), - Tightening( 10, 1, Tightening::LB ), - Tightening( 10, 5.5, Tightening::UB ), - Tightening( 11, 0, Tightening::LB ), - Tightening( 11, 2, Tightening::UB ) + Tightening( 10, 1, Tightening::LB ), Tightening( 10, 5.5, Tightening::UB ), + Tightening( 11, 0, Tightening::LB ), Tightening( 11, 2, Tightening::UB ) - } ); + } ); List bounds; TS_ASSERT_THROWS_NOTHING( nlr.getConstraintTightenings( bounds ) ); @@ -800,7 +782,7 @@ class DeepPolyAnalysisTestSuite : public CxxTest::TestSuite TS_ASSERT( existsBound( bounds, bound ) ); } - void populateNetworkWithSigmoidsAndRound( NLR::NetworkLevelReasoner &nlr, MockTableau &tableau ) + void populateNetworkWithSigmoidsAndRound( NLR::NetworkLevelReasoner &nlr, MockTableau &tableau ) { /* @@ -865,14 +847,22 @@ class DeepPolyAnalysisTestSuite : public CxxTest::TestSuite double large = 1000000; tableau.getBoundManager().initialize( 10 ); - tableau.setLowerBound( 2, -large ); tableau.setUpperBound( 2, large ); - tableau.setLowerBound( 3, -large ); tableau.setUpperBound( 3, large ); - tableau.setLowerBound( 4, -large ); tableau.setUpperBound( 4, large ); - tableau.setLowerBound( 5, -large ); tableau.setUpperBound( 5, large ); - tableau.setLowerBound( 6, -large ); tableau.setUpperBound( 6, large ); - tableau.setLowerBound( 7, -large ); tableau.setUpperBound( 7, large ); - tableau.setLowerBound( 8, -large ); tableau.setUpperBound( 8, large ); - tableau.setLowerBound( 9, -large ); tableau.setUpperBound( 9, large ); + tableau.setLowerBound( 2, -large ); + tableau.setUpperBound( 2, large ); + tableau.setLowerBound( 3, -large ); + tableau.setUpperBound( 3, large ); + tableau.setLowerBound( 4, -large ); + tableau.setUpperBound( 4, large ); + tableau.setLowerBound( 5, -large ); + tableau.setUpperBound( 5, large ); + tableau.setLowerBound( 6, -large ); + tableau.setUpperBound( 6, large ); + tableau.setLowerBound( 7, -large ); + tableau.setUpperBound( 7, large ); + tableau.setLowerBound( 8, -large ); + tableau.setUpperBound( 8, large ); + tableau.setLowerBound( 9, -large ); + tableau.setUpperBound( 9, large ); } void test_deeppoly_sigmoids_and_round() @@ -952,10 +942,10 @@ class DeepPolyAnalysisTestSuite : public CxxTest::TestSuite TS_ASSERT( FloatUtils::areEqual( nlr.getLayer( 3 )->getUb( 1 ), 0.5516, 0.0001 ) ); // Layer 4 - TS_ASSERT_EQUALS( nlr.getLayer(4)->getLb( 0 ), 0 ); - TS_ASSERT_EQUALS( nlr.getLayer(4)->getUb( 0 ), 2 ); - TS_ASSERT_EQUALS( nlr.getLayer(4)->getLb( 1 ), -1 ); - TS_ASSERT_EQUALS( nlr.getLayer(4)->getUb( 1 ), 1 ); + TS_ASSERT_EQUALS( nlr.getLayer( 4 )->getLb( 0 ), 0 ); + TS_ASSERT_EQUALS( nlr.getLayer( 4 )->getUb( 0 ), 2 ); + TS_ASSERT_EQUALS( nlr.getLayer( 4 )->getLb( 1 ), -1 ); + TS_ASSERT_EQUALS( nlr.getLayer( 4 )->getUb( 1 ), 1 ); } void populateNetworkSoftmax( NLR::NetworkLevelReasoner &nlr, MockTableau &tableau ) @@ -1574,8 +1564,8 @@ class DeepPolyAnalysisTestSuite : public CxxTest::TestSuite nlr.addLayer( 4, NLR::Layer::LEAKY_RELU, 2 ); nlr.addLayer( 5, NLR::Layer::WEIGHTED_SUM, 2 ); - nlr.getLayer(2)->setAlpha(0.2); - nlr.getLayer(4)->setAlpha(0.2); + nlr.getLayer( 2 )->setAlpha( 0.2 ); + nlr.getLayer( 4 )->setAlpha( 0.2 ); // Mark layer dependencies for ( unsigned i = 1; i <= 5; ++i ) @@ -1629,16 +1619,26 @@ class DeepPolyAnalysisTestSuite : public CxxTest::TestSuite double large = 1000000; tableau.getBoundManager().initialize( 12 ); - tableau.setLowerBound( 2, -large ); tableau.setUpperBound( 2, large ); - tableau.setLowerBound( 3, -large ); tableau.setUpperBound( 3, large ); - tableau.setLowerBound( 4, -large ); tableau.setUpperBound( 4, large ); - tableau.setLowerBound( 5, -large ); tableau.setUpperBound( 5, large ); - tableau.setLowerBound( 6, -large ); tableau.setUpperBound( 6, large ); - tableau.setLowerBound( 7, -large ); tableau.setUpperBound( 7, large ); - tableau.setLowerBound( 8, -large ); tableau.setUpperBound( 8, large ); - tableau.setLowerBound( 9, -large ); tableau.setUpperBound( 9, large ); - tableau.setLowerBound( 10, -large ); tableau.setUpperBound( 10, large ); - tableau.setLowerBound( 11, -large ); tableau.setUpperBound( 11, large ); + tableau.setLowerBound( 2, -large ); + tableau.setUpperBound( 2, large ); + tableau.setLowerBound( 3, -large ); + tableau.setUpperBound( 3, large ); + tableau.setLowerBound( 4, -large ); + tableau.setUpperBound( 4, large ); + tableau.setLowerBound( 5, -large ); + tableau.setUpperBound( 5, large ); + tableau.setLowerBound( 6, -large ); + tableau.setUpperBound( 6, large ); + tableau.setLowerBound( 7, -large ); + tableau.setUpperBound( 7, large ); + tableau.setLowerBound( 8, -large ); + tableau.setUpperBound( 8, large ); + tableau.setLowerBound( 9, -large ); + tableau.setUpperBound( 9, large ); + tableau.setLowerBound( 10, -large ); + tableau.setUpperBound( 10, large ); + tableau.setLowerBound( 11, -large ); + tableau.setUpperBound( 11, large ); } void test_deeppoly_leaky_relus() @@ -1690,33 +1690,23 @@ class DeepPolyAnalysisTestSuite : public CxxTest::TestSuite */ - List expectedBounds({ - Tightening( 2, -2, Tightening::LB ), - Tightening( 2, 2, Tightening::UB ), - Tightening( 3, -2, Tightening::LB ), - Tightening( 3, 2, Tightening::UB ), + List expectedBounds( + { Tightening( 2, -2, Tightening::LB ), Tightening( 2, 2, Tightening::UB ), + Tightening( 3, -2, Tightening::LB ), Tightening( 3, 2, Tightening::UB ), - Tightening( 4, -2, Tightening::LB ), - Tightening( 4, 2, Tightening::UB ), - Tightening( 5, -2, Tightening::LB ), - Tightening( 5, 2, Tightening::UB ), + Tightening( 4, -2, Tightening::LB ), Tightening( 4, 2, Tightening::UB ), + Tightening( 5, -2, Tightening::LB ), Tightening( 5, 2, Tightening::UB ), - Tightening( 6, -2, Tightening::LB ), - Tightening( 6, 2.8, Tightening::UB ), - Tightening( 7, -2.8, Tightening::LB ), - Tightening( 7, 2.8, Tightening::UB ), + Tightening( 6, -2, Tightening::LB ), Tightening( 6, 2.8, Tightening::UB ), + Tightening( 7, -2.8, Tightening::LB ), Tightening( 7, 2.8, Tightening::UB ), - Tightening( 8, -2, Tightening::LB ), - Tightening( 8, 2.8, Tightening::UB ), - Tightening( 9, -2.8, Tightening::LB ), - Tightening( 9, 2.8, Tightening::UB ), + Tightening( 8, -2, Tightening::LB ), Tightening( 8, 2.8, Tightening::UB ), + Tightening( 9, -2.8, Tightening::LB ), Tightening( 9, 2.8, Tightening::UB ), - Tightening( 10, -3, Tightening::LB ), - Tightening( 10, 5.64, Tightening::UB ), - Tightening( 11, -2.8, Tightening::LB ), - Tightening( 11, 2.8, Tightening::UB ) + Tightening( 10, -3, Tightening::LB ), Tightening( 10, 5.64, Tightening::UB ), + Tightening( 11, -2.8, Tightening::LB ), Tightening( 11, 2.8, Tightening::UB ) - }); + } ); List bounds; TS_ASSERT_THROWS_NOTHING( nlr.getConstraintTightenings( bounds ) ); @@ -1775,33 +1765,23 @@ class DeepPolyAnalysisTestSuite : public CxxTest::TestSuite */ - List expectedBounds({ - Tightening( 2, 0, Tightening::LB ), - Tightening( 2, 0, Tightening::UB ), - Tightening( 3, -2, Tightening::LB ), - Tightening( 3, -2, Tightening::UB ), - - Tightening( 4, 0, Tightening::LB ), - Tightening( 4, 0, Tightening::UB ), - Tightening( 5, -0.4, Tightening::LB ), - Tightening( 5, -0.4, Tightening::UB ), - - Tightening( 6, -0.4, Tightening::LB ), - Tightening( 6, -0.4, Tightening::UB ), - Tightening( 7, 0.4, Tightening::LB ), - Tightening( 7, 0.4, Tightening::UB ), - - Tightening( 8, -0.08, Tightening::LB ), - Tightening( 8, -0.08, Tightening::UB ), - Tightening( 9, 0.4, Tightening::LB ), - Tightening( 9, 0.4, Tightening::UB ), - - Tightening( 10, 1.32, Tightening::LB ), - Tightening( 10, 1.32, Tightening::UB ), - Tightening( 11, 0.4, Tightening::LB ), - Tightening( 11, 0.4, Tightening::UB ) - - }); + List expectedBounds( + { Tightening( 2, 0, Tightening::LB ), Tightening( 2, 0, Tightening::UB ), + Tightening( 3, -2, Tightening::LB ), Tightening( 3, -2, Tightening::UB ), + + Tightening( 4, 0, Tightening::LB ), Tightening( 4, 0, Tightening::UB ), + Tightening( 5, -0.4, Tightening::LB ), Tightening( 5, -0.4, Tightening::UB ), + + Tightening( 6, -0.4, Tightening::LB ), Tightening( 6, -0.4, Tightening::UB ), + Tightening( 7, 0.4, Tightening::LB ), Tightening( 7, 0.4, Tightening::UB ), + + Tightening( 8, -0.08, Tightening::LB ), Tightening( 8, -0.08, Tightening::UB ), + Tightening( 9, 0.4, Tightening::LB ), Tightening( 9, 0.4, Tightening::UB ), + + Tightening( 10, 1.32, Tightening::LB ), Tightening( 10, 1.32, Tightening::UB ), + Tightening( 11, 0.4, Tightening::LB ), Tightening( 11, 0.4, Tightening::UB ) + + } ); List bounds; TS_ASSERT_THROWS_NOTHING( nlr.getConstraintTightenings( bounds ) ); diff --git a/src/nlr/tests/Test_NetworkLevelReasoner.h b/src/nlr/tests/Test_NetworkLevelReasoner.h index 67b0aa3f93..fafe4d0144 100644 --- a/src/nlr/tests/Test_NetworkLevelReasoner.h +++ b/src/nlr/tests/Test_NetworkLevelReasoner.h @@ -13,8 +13,6 @@ **/ -#include - #include "../../engine/tests/MockTableau.h" // TODO: fix this #include "FloatUtils.h" #include "InputQuery.h" @@ -24,6 +22,8 @@ #include "Tightening.h" #include "Vector.h" +#include + class MockForNetworkLevelReasoner { public: @@ -484,18 +484,30 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite tableau.setUpperBound( 1, 1 ); double large = 1000; - tableau.setLowerBound( 2, -large ); tableau.setUpperBound( 2, large ); - tableau.setLowerBound( 3, -large ); tableau.setUpperBound( 3, large ); - tableau.setLowerBound( 4, -large ); tableau.setUpperBound( 4, large ); - tableau.setLowerBound( 5, -large ); tableau.setUpperBound( 5, large ); - tableau.setLowerBound( 6, -large ); tableau.setUpperBound( 6, large ); - tableau.setLowerBound( 7, -large ); tableau.setUpperBound( 7, large ); - tableau.setLowerBound( 8, -large ); tableau.setUpperBound( 8, large ); - tableau.setLowerBound( 9, -large ); tableau.setUpperBound( 9, large ); - tableau.setLowerBound( 10, -large ); tableau.setUpperBound( 10, large ); - tableau.setLowerBound( 11, -large ); tableau.setUpperBound( 11, large ); - tableau.setLowerBound( 12, -large ); tableau.setUpperBound( 12, large ); - tableau.setLowerBound( 13, -large ); tableau.setUpperBound( 13, large ); + tableau.setLowerBound( 2, -large ); + tableau.setUpperBound( 2, large ); + tableau.setLowerBound( 3, -large ); + tableau.setUpperBound( 3, large ); + tableau.setLowerBound( 4, -large ); + tableau.setUpperBound( 4, large ); + tableau.setLowerBound( 5, -large ); + tableau.setUpperBound( 5, large ); + tableau.setLowerBound( 6, -large ); + tableau.setUpperBound( 6, large ); + tableau.setLowerBound( 7, -large ); + tableau.setUpperBound( 7, large ); + tableau.setLowerBound( 8, -large ); + tableau.setUpperBound( 8, large ); + tableau.setLowerBound( 9, -large ); + tableau.setUpperBound( 9, large ); + tableau.setLowerBound( 10, -large ); + tableau.setUpperBound( 10, large ); + tableau.setLowerBound( 11, -large ); + tableau.setUpperBound( 11, large ); + tableau.setLowerBound( 12, -large ); + tableau.setUpperBound( 12, large ); + tableau.setLowerBound( 13, -large ); + tableau.setUpperBound( 13, large ); nlr.setTableau( &tableau ); @@ -505,37 +517,25 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite // Perform the tightening pass TS_ASSERT_THROWS_NOTHING( nlr.intervalArithmeticBoundPropagation() ); - List expectedBounds({ - Tightening( 2, 0, Tightening::LB ), - Tightening( 2, 2, Tightening::UB ), - Tightening( 3, 0, Tightening::LB ), - Tightening( 3, 2, Tightening::UB ), - - Tightening( 4, -5, Tightening::LB ), - Tightening( 4, 5, Tightening::UB ), - Tightening( 5, 0, Tightening::LB ), - Tightening( 5, 5, Tightening::UB ), - - Tightening( 6, -1, Tightening::LB ), - Tightening( 6, 1, Tightening::UB ), - Tightening( 7, 0, Tightening::LB ), - Tightening( 7, 1, Tightening::UB ), - - Tightening( 8, -1, Tightening::LB ), - Tightening( 8, 7, Tightening::UB ), - Tightening( 9, 0, Tightening::LB ), - Tightening( 9, 7, Tightening::UB ), - - Tightening( 10, -1, Tightening::LB ), - Tightening( 10, 7, Tightening::UB ), - Tightening( 11, 0, Tightening::LB ), - Tightening( 11, 7, Tightening::UB ), - - Tightening( 12, 0, Tightening::LB ), - Tightening( 12, 7, Tightening::UB ), - Tightening( 13, 0, Tightening::LB ), - Tightening( 13, 28, Tightening::UB ), - }); + List expectedBounds( { + Tightening( 2, 0, Tightening::LB ), Tightening( 2, 2, Tightening::UB ), + Tightening( 3, 0, Tightening::LB ), Tightening( 3, 2, Tightening::UB ), + + Tightening( 4, -5, Tightening::LB ), Tightening( 4, 5, Tightening::UB ), + Tightening( 5, 0, Tightening::LB ), Tightening( 5, 5, Tightening::UB ), + + Tightening( 6, -1, Tightening::LB ), Tightening( 6, 1, Tightening::UB ), + Tightening( 7, 0, Tightening::LB ), Tightening( 7, 1, Tightening::UB ), + + Tightening( 8, -1, Tightening::LB ), Tightening( 8, 7, Tightening::UB ), + Tightening( 9, 0, Tightening::LB ), Tightening( 9, 7, Tightening::UB ), + + Tightening( 10, -1, Tightening::LB ), Tightening( 10, 7, Tightening::UB ), + Tightening( 11, 0, Tightening::LB ), Tightening( 11, 7, Tightening::UB ), + + Tightening( 12, 0, Tightening::LB ), Tightening( 12, 7, Tightening::UB ), + Tightening( 13, 0, Tightening::LB ), Tightening( 13, 28, Tightening::UB ), + } ); List bounds; TS_ASSERT_THROWS_NOTHING( nlr.getConstraintTightenings( bounds ) ); @@ -550,18 +550,30 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite tableau.setLowerBound( 1, -1 ); tableau.setUpperBound( 1, 2 ); - tableau.setLowerBound( 2, -large ); tableau.setUpperBound( 2, large ); - tableau.setLowerBound( 3, -large ); tableau.setUpperBound( 3, large ); - tableau.setLowerBound( 4, -large ); tableau.setUpperBound( 4, large ); - tableau.setLowerBound( 5, -large ); tableau.setUpperBound( 5, large ); - tableau.setLowerBound( 6, -large ); tableau.setUpperBound( 6, large ); - tableau.setLowerBound( 7, -large ); tableau.setUpperBound( 7, large ); - tableau.setLowerBound( 8, -large ); tableau.setUpperBound( 8, large ); - tableau.setLowerBound( 9, -large ); tableau.setUpperBound( 9, large ); - tableau.setLowerBound( 10, -large ); tableau.setUpperBound( 10, large ); - tableau.setLowerBound( 11, -large ); tableau.setUpperBound( 11, large ); - tableau.setLowerBound( 12, -large ); tableau.setUpperBound( 12, large ); - tableau.setLowerBound( 13, -large ); tableau.setUpperBound( 13, large ); + tableau.setLowerBound( 2, -large ); + tableau.setUpperBound( 2, large ); + tableau.setLowerBound( 3, -large ); + tableau.setUpperBound( 3, large ); + tableau.setLowerBound( 4, -large ); + tableau.setUpperBound( 4, large ); + tableau.setLowerBound( 5, -large ); + tableau.setUpperBound( 5, large ); + tableau.setLowerBound( 6, -large ); + tableau.setUpperBound( 6, large ); + tableau.setLowerBound( 7, -large ); + tableau.setUpperBound( 7, large ); + tableau.setLowerBound( 8, -large ); + tableau.setUpperBound( 8, large ); + tableau.setLowerBound( 9, -large ); + tableau.setUpperBound( 9, large ); + tableau.setLowerBound( 10, -large ); + tableau.setUpperBound( 10, large ); + tableau.setLowerBound( 11, -large ); + tableau.setUpperBound( 11, large ); + tableau.setLowerBound( 12, -large ); + tableau.setUpperBound( 12, large ); + tableau.setLowerBound( 13, -large ); + tableau.setUpperBound( 13, large ); // Initialize TS_ASSERT_THROWS_NOTHING( nlr.obtainCurrentBounds() ); @@ -569,37 +581,25 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite // Perform the tightening pass TS_ASSERT_THROWS_NOTHING( nlr.intervalArithmeticBoundPropagation() ); - List expectedBounds2({ - Tightening( 2, -2, Tightening::LB ), - Tightening( 2, 2, Tightening::UB ), - Tightening( 3, 0, Tightening::LB ), - Tightening( 3, 2, Tightening::UB ), - - Tightening( 4, -12, Tightening::LB ), - Tightening( 4, 5, Tightening::UB ), - Tightening( 5, 0, Tightening::LB ), - Tightening( 5, 5, Tightening::UB ), - - Tightening( 6, -1, Tightening::LB ), - Tightening( 6, 2, Tightening::UB ), - Tightening( 7, 0, Tightening::LB ), - Tightening( 7, 2, Tightening::UB ), - - Tightening( 8, -2, Tightening::LB ), - Tightening( 8, 7, Tightening::UB ), - Tightening( 9, 0, Tightening::LB ), - Tightening( 9, 7, Tightening::UB ), - - Tightening( 10, -2, Tightening::LB ), - Tightening( 10, 7, Tightening::UB ), - Tightening( 11, 0, Tightening::LB ), - Tightening( 11, 7, Tightening::UB ), - - Tightening( 12, 0, Tightening::LB ), - Tightening( 12, 7, Tightening::UB ), - Tightening( 13, 0, Tightening::LB ), - Tightening( 13, 28, Tightening::UB ), - }); + List expectedBounds2( { + Tightening( 2, -2, Tightening::LB ), Tightening( 2, 2, Tightening::UB ), + Tightening( 3, 0, Tightening::LB ), Tightening( 3, 2, Tightening::UB ), + + Tightening( 4, -12, Tightening::LB ), Tightening( 4, 5, Tightening::UB ), + Tightening( 5, 0, Tightening::LB ), Tightening( 5, 5, Tightening::UB ), + + Tightening( 6, -1, Tightening::LB ), Tightening( 6, 2, Tightening::UB ), + Tightening( 7, 0, Tightening::LB ), Tightening( 7, 2, Tightening::UB ), + + Tightening( 8, -2, Tightening::LB ), Tightening( 8, 7, Tightening::UB ), + Tightening( 9, 0, Tightening::LB ), Tightening( 9, 7, Tightening::UB ), + + Tightening( 10, -2, Tightening::LB ), Tightening( 10, 7, Tightening::UB ), + Tightening( 11, 0, Tightening::LB ), Tightening( 11, 7, Tightening::UB ), + + Tightening( 12, 0, Tightening::LB ), Tightening( 12, 7, Tightening::UB ), + Tightening( 13, 0, Tightening::LB ), Tightening( 13, 28, Tightening::UB ), + } ); TS_ASSERT_THROWS_NOTHING( nlr.getConstraintTightenings( bounds ) ); @@ -690,18 +690,30 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite tableau.setUpperBound( 1, 2 ); double large = 1000; - tableau.setLowerBound( 2, -large ); tableau.setUpperBound( 2, large ); - tableau.setLowerBound( 3, -large ); tableau.setUpperBound( 3, large ); - tableau.setLowerBound( 4, -large ); tableau.setUpperBound( 4, large ); - tableau.setLowerBound( 5, -large ); tableau.setUpperBound( 5, large ); - tableau.setLowerBound( 6, -large ); tableau.setUpperBound( 6, large ); - tableau.setLowerBound( 7, -large ); tableau.setUpperBound( 7, large ); - tableau.setLowerBound( 8, -large ); tableau.setUpperBound( 8, large ); - tableau.setLowerBound( 9, -large ); tableau.setUpperBound( 9, large ); - tableau.setLowerBound( 10, -large ); tableau.setUpperBound( 10, large ); - tableau.setLowerBound( 11, -large ); tableau.setUpperBound( 11, large ); - tableau.setLowerBound( 12, -large ); tableau.setUpperBound( 12, large ); - tableau.setLowerBound( 13, -large ); tableau.setUpperBound( 13, large ); + tableau.setLowerBound( 2, -large ); + tableau.setUpperBound( 2, large ); + tableau.setLowerBound( 3, -large ); + tableau.setUpperBound( 3, large ); + tableau.setLowerBound( 4, -large ); + tableau.setUpperBound( 4, large ); + tableau.setLowerBound( 5, -large ); + tableau.setUpperBound( 5, large ); + tableau.setLowerBound( 6, -large ); + tableau.setUpperBound( 6, large ); + tableau.setLowerBound( 7, -large ); + tableau.setUpperBound( 7, large ); + tableau.setLowerBound( 8, -large ); + tableau.setUpperBound( 8, large ); + tableau.setLowerBound( 9, -large ); + tableau.setUpperBound( 9, large ); + tableau.setLowerBound( 10, -large ); + tableau.setUpperBound( 10, large ); + tableau.setLowerBound( 11, -large ); + tableau.setUpperBound( 11, large ); + tableau.setLowerBound( 12, -large ); + tableau.setUpperBound( 12, large ); + tableau.setLowerBound( 13, -large ); + tableau.setUpperBound( 13, large ); nlr.setTableau( &tableau ); @@ -711,37 +723,25 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite // Perform the tightening pass TS_ASSERT_THROWS_NOTHING( nlr.intervalArithmeticBoundPropagation() ); - List expectedBounds({ - Tightening( 2, 0, Tightening::LB ), - Tightening( 2, 3, Tightening::UB ), - Tightening( 3, 0, Tightening::LB ), - Tightening( 3, 3, Tightening::UB ), - - Tightening( 4, -8, Tightening::LB ), - Tightening( 4, 7, Tightening::UB ), - Tightening( 5, 0, Tightening::LB ), - Tightening( 5, 8, Tightening::UB ), - - Tightening( 6, -1, Tightening::LB ), - Tightening( 6, 2, Tightening::UB ), - Tightening( 7, 0, Tightening::LB ), - Tightening( 7, 2, Tightening::UB ), - - Tightening( 8, -2, Tightening::LB ), - Tightening( 8, 11, Tightening::UB ), - Tightening( 9, 0, Tightening::LB ), - Tightening( 9, 11, Tightening::UB ), - - Tightening( 10, -3, Tightening::LB ), - Tightening( 10, 10, Tightening::UB ), - Tightening( 11, 0, Tightening::LB ), - Tightening( 11, 10, Tightening::UB ), - - Tightening( 12, 0, Tightening::LB ), - Tightening( 12, 11, Tightening::UB ), - Tightening( 13, 0, Tightening::LB ), - Tightening( 13, 41, Tightening::UB ), - }); + List expectedBounds( { + Tightening( 2, 0, Tightening::LB ), Tightening( 2, 3, Tightening::UB ), + Tightening( 3, 0, Tightening::LB ), Tightening( 3, 3, Tightening::UB ), + + Tightening( 4, -8, Tightening::LB ), Tightening( 4, 7, Tightening::UB ), + Tightening( 5, 0, Tightening::LB ), Tightening( 5, 8, Tightening::UB ), + + Tightening( 6, -1, Tightening::LB ), Tightening( 6, 2, Tightening::UB ), + Tightening( 7, 0, Tightening::LB ), Tightening( 7, 2, Tightening::UB ), + + Tightening( 8, -2, Tightening::LB ), Tightening( 8, 11, Tightening::UB ), + Tightening( 9, 0, Tightening::LB ), Tightening( 9, 11, Tightening::UB ), + + Tightening( 10, -3, Tightening::LB ), Tightening( 10, 10, Tightening::UB ), + Tightening( 11, 0, Tightening::LB ), Tightening( 11, 10, Tightening::UB ), + + Tightening( 12, 0, Tightening::LB ), Tightening( 12, 11, Tightening::UB ), + Tightening( 13, 0, Tightening::LB ), Tightening( 13, 41, Tightening::UB ), + } ); List bounds; TS_ASSERT_THROWS_NOTHING( nlr.getConstraintTightenings( bounds ) ); @@ -755,18 +755,30 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite tableau.setLowerBound( 1, -1 ); tableau.setUpperBound( 1, 2 ); - tableau.setLowerBound( 2, -large ); tableau.setUpperBound( 2, large ); - tableau.setLowerBound( 3, -large ); tableau.setUpperBound( 3, large ); - tableau.setLowerBound( 4, -large ); tableau.setUpperBound( 4, large ); - tableau.setLowerBound( 5, -large ); tableau.setUpperBound( 5, large ); - tableau.setLowerBound( 6, -large ); tableau.setUpperBound( 6, large ); - tableau.setLowerBound( 7, -large ); tableau.setUpperBound( 7, large ); - tableau.setLowerBound( 8, -large ); tableau.setUpperBound( 8, large ); - tableau.setLowerBound( 9, -large ); tableau.setUpperBound( 9, large ); - tableau.setLowerBound( 10, -large ); tableau.setUpperBound( 10, large ); - tableau.setLowerBound( 11, -large ); tableau.setUpperBound( 11, large ); - tableau.setLowerBound( 12, -large ); tableau.setUpperBound( 12, large ); - tableau.setLowerBound( 13, -large ); tableau.setUpperBound( 13, large ); + tableau.setLowerBound( 2, -large ); + tableau.setUpperBound( 2, large ); + tableau.setLowerBound( 3, -large ); + tableau.setUpperBound( 3, large ); + tableau.setLowerBound( 4, -large ); + tableau.setUpperBound( 4, large ); + tableau.setLowerBound( 5, -large ); + tableau.setUpperBound( 5, large ); + tableau.setLowerBound( 6, -large ); + tableau.setUpperBound( 6, large ); + tableau.setLowerBound( 7, -large ); + tableau.setUpperBound( 7, large ); + tableau.setLowerBound( 8, -large ); + tableau.setUpperBound( 8, large ); + tableau.setLowerBound( 9, -large ); + tableau.setUpperBound( 9, large ); + tableau.setLowerBound( 10, -large ); + tableau.setUpperBound( 10, large ); + tableau.setLowerBound( 11, -large ); + tableau.setUpperBound( 11, large ); + tableau.setLowerBound( 12, -large ); + tableau.setUpperBound( 12, large ); + tableau.setLowerBound( 13, -large ); + tableau.setUpperBound( 13, large ); // Initialize TS_ASSERT_THROWS_NOTHING( nlr.obtainCurrentBounds() ); @@ -774,43 +786,30 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite // Perform the tightening pass TS_ASSERT_THROWS_NOTHING( nlr.intervalArithmeticBoundPropagation() ); - List expectedBounds2({ - Tightening( 2, -2, Tightening::LB ), - Tightening( 2, 2, Tightening::UB ), - Tightening( 3, 0, Tightening::LB ), - Tightening( 3, 2, Tightening::UB ), - - Tightening( 4, -12, Tightening::LB ), - Tightening( 4, 5, Tightening::UB ), - Tightening( 5, 0, Tightening::LB ), - Tightening( 5, 12, Tightening::UB ), - - Tightening( 6, -1, Tightening::LB ), - Tightening( 6, 2, Tightening::UB ), - Tightening( 7, 0, Tightening::LB ), - Tightening( 7, 2, Tightening::UB ), - - Tightening( 8, -2, Tightening::LB ), - Tightening( 8, 14, Tightening::UB ), - Tightening( 9, 0, Tightening::LB ), - Tightening( 9, 14, Tightening::UB ), - - Tightening( 10, -2, Tightening::LB ), - Tightening( 10, 14, Tightening::UB ), - Tightening( 11, 0, Tightening::LB ), - Tightening( 11, 14, Tightening::UB ), - - Tightening( 12, 0, Tightening::LB ), - Tightening( 12, 14, Tightening::UB ), - Tightening( 13, 0, Tightening::LB ), - Tightening( 13, 56, Tightening::UB ), - }); + List expectedBounds2( { + Tightening( 2, -2, Tightening::LB ), Tightening( 2, 2, Tightening::UB ), + Tightening( 3, 0, Tightening::LB ), Tightening( 3, 2, Tightening::UB ), + + Tightening( 4, -12, Tightening::LB ), Tightening( 4, 5, Tightening::UB ), + Tightening( 5, 0, Tightening::LB ), Tightening( 5, 12, Tightening::UB ), + + Tightening( 6, -1, Tightening::LB ), Tightening( 6, 2, Tightening::UB ), + Tightening( 7, 0, Tightening::LB ), Tightening( 7, 2, Tightening::UB ), + + Tightening( 8, -2, Tightening::LB ), Tightening( 8, 14, Tightening::UB ), + Tightening( 9, 0, Tightening::LB ), Tightening( 9, 14, Tightening::UB ), + + Tightening( 10, -2, Tightening::LB ), Tightening( 10, 14, Tightening::UB ), + Tightening( 11, 0, Tightening::LB ), Tightening( 11, 14, Tightening::UB ), + + Tightening( 12, 0, Tightening::LB ), Tightening( 12, 14, Tightening::UB ), + Tightening( 13, 0, Tightening::LB ), Tightening( 13, 56, Tightening::UB ), + } ); TS_ASSERT_THROWS_NOTHING( nlr.getConstraintTightenings( bounds ) ); TS_ASSERT_EQUALS( expectedBounds2.size(), bounds.size() ); for ( const auto &bound : expectedBounds2 ) TS_ASSERT( bounds.exists( bound ) ); - } void populateNetworkSBT( NLR::NetworkLevelReasoner &nlr, MockTableau &tableau ) @@ -866,17 +865,21 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite double large = 1000000; tableau.getBoundManager().initialize( 7 ); - tableau.setLowerBound( 2, -large ); tableau.setUpperBound( 2, large ); - tableau.setLowerBound( 3, -large ); tableau.setUpperBound( 3, large ); - tableau.setLowerBound( 4, -large ); tableau.setUpperBound( 4, large ); - tableau.setLowerBound( 5, -large ); tableau.setUpperBound( 5, large ); - tableau.setLowerBound( 6, -large ); tableau.setUpperBound( 6, large ); + tableau.setLowerBound( 2, -large ); + tableau.setUpperBound( 2, large ); + tableau.setLowerBound( 3, -large ); + tableau.setUpperBound( 3, large ); + tableau.setLowerBound( 4, -large ); + tableau.setUpperBound( 4, large ); + tableau.setLowerBound( 5, -large ); + tableau.setUpperBound( 5, large ); + tableau.setLowerBound( 6, -large ); + tableau.setUpperBound( 6, large ); } void test_sbt_relus_all_active() { - Options::get()->setString( Options::SYMBOLIC_BOUND_TIGHTENING_TYPE, - "sbt" ); + Options::get()->setString( Options::SYMBOLIC_BOUND_TIGHTENING_TYPE, "sbt" ); NLR::NetworkLevelReasoner nlr; MockTableau tableau; @@ -920,20 +923,20 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite x6.ub = x0 + 2x1 : [6, 16] */ - List expectedBounds({ - Tightening( 2, 11, Tightening::LB ), - Tightening( 2, 27, Tightening::UB ), - Tightening( 3, 5, Tightening::LB ), - Tightening( 3, 11, Tightening::UB ), + List expectedBounds( { + Tightening( 2, 11, Tightening::LB ), + Tightening( 2, 27, Tightening::UB ), + Tightening( 3, 5, Tightening::LB ), + Tightening( 3, 11, Tightening::UB ), - Tightening( 4, 11, Tightening::LB ), - Tightening( 4, 27, Tightening::UB ), - Tightening( 5, 5, Tightening::LB ), - Tightening( 5, 11, Tightening::UB ), + Tightening( 4, 11, Tightening::LB ), + Tightening( 4, 27, Tightening::UB ), + Tightening( 5, 5, Tightening::LB ), + Tightening( 5, 11, Tightening::UB ), - Tightening( 6, 6, Tightening::LB ), - Tightening( 6, 16, Tightening::UB ), - }); + Tightening( 6, 6, Tightening::LB ), + Tightening( 6, 16, Tightening::UB ), + } ); List bounds; TS_ASSERT_THROWS_NOTHING( nlr.getConstraintTightenings( bounds ) ); @@ -945,8 +948,7 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite void test_sbt_relus_active_and_inactive() { - Options::get()->setString( Options::SYMBOLIC_BOUND_TIGHTENING_TYPE, - "sbt" ); + Options::get()->setString( Options::SYMBOLIC_BOUND_TIGHTENING_TYPE, "sbt" ); NLR::NetworkLevelReasoner nlr; MockTableau tableau; @@ -994,20 +996,20 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite x6.ub = - x0 - x1 : [-11, -5] */ - List expectedBounds({ - Tightening( 2, -19, Tightening::LB ), - Tightening( 2, -3, Tightening::UB ), - Tightening( 3, 5, Tightening::LB ), - Tightening( 3, 11, Tightening::UB ), + List expectedBounds( { + Tightening( 2, -19, Tightening::LB ), + Tightening( 2, -3, Tightening::UB ), + Tightening( 3, 5, Tightening::LB ), + Tightening( 3, 11, Tightening::UB ), - Tightening( 4, 0, Tightening::LB ), - Tightening( 4, 0, Tightening::UB ), - Tightening( 5, 5, Tightening::LB ), - Tightening( 5, 11, Tightening::UB ), + Tightening( 4, 0, Tightening::LB ), + Tightening( 4, 0, Tightening::UB ), + Tightening( 5, 5, Tightening::LB ), + Tightening( 5, 11, Tightening::UB ), - Tightening( 6, -11, Tightening::LB ), - Tightening( 6, -5, Tightening::UB ), - }); + Tightening( 6, -11, Tightening::LB ), + Tightening( 6, -5, Tightening::UB ), + } ); List bounds; TS_ASSERT_THROWS_NOTHING( nlr.getConstraintTightenings( bounds ) ); @@ -1019,8 +1021,7 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite void test_sbt_relus_active_and_not_fixed() { - Options::get()->setString( Options::SYMBOLIC_BOUND_TIGHTENING_TYPE, - "sbt" ); + Options::get()->setString( Options::SYMBOLIC_BOUND_TIGHTENING_TYPE, "sbt" ); NLR::NetworkLevelReasoner nlr; MockTableau tableau; @@ -1072,20 +1073,20 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite x6 range: [2 + 1.25 - 11.25 = -8, 3 + 6.25 - 8.25 = 1] = [-8, 1] */ - List expectedBounds({ - Tightening( 2, -4, Tightening::LB ), - Tightening( 2, 12, Tightening::UB ), - Tightening( 3, 5, Tightening::LB ), - Tightening( 3, 11, Tightening::UB ), + List expectedBounds( { + Tightening( 2, -4, Tightening::LB ), + Tightening( 2, 12, Tightening::UB ), + Tightening( 3, 5, Tightening::LB ), + Tightening( 3, 11, Tightening::UB ), - Tightening( 4, 0, Tightening::LB ), - Tightening( 4, 12, Tightening::UB ), - Tightening( 5, 5, Tightening::LB ), - Tightening( 5, 11, Tightening::UB ), + Tightening( 4, 0, Tightening::LB ), + Tightening( 4, 12, Tightening::UB ), + Tightening( 5, 5, Tightening::LB ), + Tightening( 5, 11, Tightening::UB ), - Tightening( 6, -8, Tightening::LB ), - Tightening( 6, 1, Tightening::UB ), - }); + Tightening( 6, -8, Tightening::LB ), + Tightening( 6, 1, Tightening::UB ), + } ); List bounds; TS_ASSERT_THROWS_NOTHING( nlr.getConstraintTightenings( bounds ) ); @@ -1097,8 +1098,7 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite void test_sbt_relus_active_and_externally_fixed() { - Options::get()->setString( Options::SYMBOLIC_BOUND_TIGHTENING_TYPE, - "sbt" ); + Options::get()->setString( Options::SYMBOLIC_BOUND_TIGHTENING_TYPE, "sbt" ); NLR::NetworkLevelReasoner nlr; MockTableau tableau; @@ -1149,20 +1149,20 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite x6.ub = - x0 - x1 : [-11, -5] */ - List expectedBounds({ - // x2 does not appear, because it has been eliminated + List expectedBounds( { + // x2 does not appear, because it has been eliminated - Tightening( 3, 5, Tightening::LB ), - Tightening( 3, 11, Tightening::UB ), + Tightening( 3, 5, Tightening::LB ), + Tightening( 3, 11, Tightening::UB ), - Tightening( 4, 0, Tightening::LB ), - Tightening( 4, 0, Tightening::UB ), - Tightening( 5, 5, Tightening::LB ), - Tightening( 5, 11, Tightening::UB ), + Tightening( 4, 0, Tightening::LB ), + Tightening( 4, 0, Tightening::UB ), + Tightening( 5, 5, Tightening::LB ), + Tightening( 5, 11, Tightening::UB ), - Tightening( 6, -11, Tightening::LB ), - Tightening( 6, -5, Tightening::UB ), - }); + Tightening( 6, -11, Tightening::LB ), + Tightening( 6, -5, Tightening::UB ), + } ); List bounds; TS_ASSERT_THROWS_NOTHING( nlr.getConstraintTightenings( bounds ) ); @@ -1174,8 +1174,7 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite void test_sbt_abs_all_positive() { - Options::get()->setString( Options::SYMBOLIC_BOUND_TIGHTENING_TYPE, - "sbt" ); + Options::get()->setString( Options::SYMBOLIC_BOUND_TIGHTENING_TYPE, "sbt" ); NLR::NetworkLevelReasoner nlr; MockTableau tableau; @@ -1219,11 +1218,16 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite // Very loose bounds for neurons except inputs double large = 1000000; - tableau.setLowerBound( 2, -large ); tableau.setUpperBound( 2, large ); - tableau.setLowerBound( 3, -large ); tableau.setUpperBound( 3, large ); - tableau.setLowerBound( 4, -large ); tableau.setUpperBound( 4, large ); - tableau.setLowerBound( 5, -large ); tableau.setUpperBound( 5, large ); - tableau.setLowerBound( 6, -large ); tableau.setUpperBound( 6, large ); + tableau.setLowerBound( 2, -large ); + tableau.setUpperBound( 2, large ); + tableau.setLowerBound( 3, -large ); + tableau.setUpperBound( 3, large ); + tableau.setLowerBound( 4, -large ); + tableau.setUpperBound( 4, large ); + tableau.setLowerBound( 5, -large ); + tableau.setUpperBound( 5, large ); + tableau.setLowerBound( 6, -large ); + tableau.setUpperBound( 6, large ); tableau.setLowerBound( 0, 4 ); tableau.setUpperBound( 0, 6 ); @@ -1262,20 +1266,20 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite x6.ub = x0 + 2x1 : [6, 16] */ - List expectedBounds({ - Tightening( 2, 11, Tightening::LB ), - Tightening( 2, 27, Tightening::UB ), - Tightening( 3, 5, Tightening::LB ), - Tightening( 3, 11, Tightening::UB ), + List expectedBounds( { + Tightening( 2, 11, Tightening::LB ), + Tightening( 2, 27, Tightening::UB ), + Tightening( 3, 5, Tightening::LB ), + Tightening( 3, 11, Tightening::UB ), - Tightening( 4, 11, Tightening::LB ), - Tightening( 4, 27, Tightening::UB ), - Tightening( 5, 5, Tightening::LB ), - Tightening( 5, 11, Tightening::UB ), + Tightening( 4, 11, Tightening::LB ), + Tightening( 4, 27, Tightening::UB ), + Tightening( 5, 5, Tightening::LB ), + Tightening( 5, 11, Tightening::UB ), - Tightening( 6, 6, Tightening::LB ), - Tightening( 6, 16, Tightening::UB ), - }); + Tightening( 6, 6, Tightening::LB ), + Tightening( 6, 16, Tightening::UB ), + } ); List bounds; TS_ASSERT_THROWS_NOTHING( nlr.getConstraintTightenings( bounds ) ); @@ -1287,8 +1291,7 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite void test_sbt_abs_positive_and_negative() { - Options::get()->setString( Options::SYMBOLIC_BOUND_TIGHTENING_TYPE, - "sbt" ); + Options::get()->setString( Options::SYMBOLIC_BOUND_TIGHTENING_TYPE, "sbt" ); NLR::NetworkLevelReasoner nlr; MockTableau tableau; @@ -1332,11 +1335,16 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite // Very loose bounds for neurons except inputs double large = 1000000; - tableau.setLowerBound( 2, -large ); tableau.setUpperBound( 2, large ); - tableau.setLowerBound( 3, -large ); tableau.setUpperBound( 3, large ); - tableau.setLowerBound( 4, -large ); tableau.setUpperBound( 4, large ); - tableau.setLowerBound( 5, -large ); tableau.setUpperBound( 5, large ); - tableau.setLowerBound( 6, -large ); tableau.setUpperBound( 6, large ); + tableau.setLowerBound( 2, -large ); + tableau.setUpperBound( 2, large ); + tableau.setLowerBound( 3, -large ); + tableau.setUpperBound( 3, large ); + tableau.setLowerBound( 4, -large ); + tableau.setUpperBound( 4, large ); + tableau.setLowerBound( 5, -large ); + tableau.setUpperBound( 5, large ); + tableau.setLowerBound( 6, -large ); + tableau.setUpperBound( 6, large ); tableau.setLowerBound( 0, 4 ); tableau.setUpperBound( 0, 6 ); @@ -1379,20 +1387,20 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite x6.ub = - 3x0 - 4x1 + 30 : [-8, 14] */ - List expectedBounds({ - Tightening( 2, -19, Tightening::LB ), - Tightening( 2, -3, Tightening::UB ), - Tightening( 3, 5, Tightening::LB ), - Tightening( 3, 11, Tightening::UB ), + List expectedBounds( { + Tightening( 2, -19, Tightening::LB ), + Tightening( 2, -3, Tightening::UB ), + Tightening( 3, 5, Tightening::LB ), + Tightening( 3, 11, Tightening::UB ), - Tightening( 4, 3, Tightening::LB ), - Tightening( 4, 19, Tightening::UB ), - Tightening( 5, 5, Tightening::LB ), - Tightening( 5, 11, Tightening::UB ), + Tightening( 4, 3, Tightening::LB ), + Tightening( 4, 19, Tightening::UB ), + Tightening( 5, 5, Tightening::LB ), + Tightening( 5, 11, Tightening::UB ), - Tightening( 6, -8, Tightening::LB ), - Tightening( 6, 14, Tightening::UB ), - }); + Tightening( 6, -8, Tightening::LB ), + Tightening( 6, 14, Tightening::UB ), + } ); List bounds; TS_ASSERT_THROWS_NOTHING( nlr.getConstraintTightenings( bounds ) ); @@ -1404,8 +1412,7 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite void test_sbt_absolute_values_positive_and_not_fixed() { - Options::get()->setString( Options::SYMBOLIC_BOUND_TIGHTENING_TYPE, - "sbt" ); + Options::get()->setString( Options::SYMBOLIC_BOUND_TIGHTENING_TYPE, "sbt" ); NLR::NetworkLevelReasoner nlr; MockTableau tableau; @@ -1449,11 +1456,16 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite // Very loose bounds for neurons except inputs double large = 1000000; - tableau.setLowerBound( 2, -large ); tableau.setUpperBound( 2, large ); - tableau.setLowerBound( 3, -large ); tableau.setUpperBound( 3, large ); - tableau.setLowerBound( 4, -large ); tableau.setUpperBound( 4, large ); - tableau.setLowerBound( 5, -large ); tableau.setUpperBound( 5, large ); - tableau.setLowerBound( 6, -large ); tableau.setUpperBound( 6, large ); + tableau.setLowerBound( 2, -large ); + tableau.setUpperBound( 2, large ); + tableau.setLowerBound( 3, -large ); + tableau.setUpperBound( 3, large ); + tableau.setLowerBound( 4, -large ); + tableau.setUpperBound( 4, large ); + tableau.setLowerBound( 5, -large ); + tableau.setUpperBound( 5, large ); + tableau.setLowerBound( 6, -large ); + tableau.setUpperBound( 6, large ); tableau.setLowerBound( 0, 4 ); tableau.setUpperBound( 0, 6 ); @@ -1499,20 +1511,20 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite x6 range: [-11, 7] */ - List expectedBounds({ - Tightening( 2, -4, Tightening::LB ), - Tightening( 2, 12, Tightening::UB ), - Tightening( 3, 5, Tightening::LB ), - Tightening( 3, 11, Tightening::UB ), + List expectedBounds( { + Tightening( 2, -4, Tightening::LB ), + Tightening( 2, 12, Tightening::UB ), + Tightening( 3, 5, Tightening::LB ), + Tightening( 3, 11, Tightening::UB ), - Tightening( 4, 0, Tightening::LB ), - Tightening( 4, 12, Tightening::UB ), - Tightening( 5, 5, Tightening::LB ), - Tightening( 5, 11, Tightening::UB ), + Tightening( 4, 0, Tightening::LB ), + Tightening( 4, 12, Tightening::UB ), + Tightening( 5, 5, Tightening::LB ), + Tightening( 5, 11, Tightening::UB ), - Tightening( 6, -11, Tightening::LB ), - Tightening( 6, 7, Tightening::UB ), - }); + Tightening( 6, -11, Tightening::LB ), + Tightening( 6, 7, Tightening::UB ), + } ); List bounds; TS_ASSERT_THROWS_NOTHING( nlr.getConstraintTightenings( bounds ) ); @@ -1524,9 +1536,7 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite void test_sbt_absolute_values_active_and_externally_fixed() { - - Options::get()->setString( Options::SYMBOLIC_BOUND_TIGHTENING_TYPE, - "sbt" ); + Options::get()->setString( Options::SYMBOLIC_BOUND_TIGHTENING_TYPE, "sbt" ); NLR::NetworkLevelReasoner nlr; MockTableau tableau; @@ -1570,11 +1580,16 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite // Very loose bounds for neurons except inputs double large = 1000000; - tableau.setLowerBound( 2, -large ); tableau.setUpperBound( 2, large ); - tableau.setLowerBound( 3, -large ); tableau.setUpperBound( 3, large ); - tableau.setLowerBound( 4, -large ); tableau.setUpperBound( 4, large ); - tableau.setLowerBound( 5, -large ); tableau.setUpperBound( 5, large ); - tableau.setLowerBound( 6, -large ); tableau.setUpperBound( 6, large ); + tableau.setLowerBound( 2, -large ); + tableau.setUpperBound( 2, large ); + tableau.setLowerBound( 3, -large ); + tableau.setUpperBound( 3, large ); + tableau.setLowerBound( 4, -large ); + tableau.setUpperBound( 4, large ); + tableau.setLowerBound( 5, -large ); + tableau.setUpperBound( 5, large ); + tableau.setLowerBound( 6, -large ); + tableau.setUpperBound( 6, large ); tableau.setLowerBound( 0, 4 ); tableau.setUpperBound( 0, 6 ); @@ -1617,20 +1632,20 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite x6.ub = - x0 - x1 + 3 : [-8, -2] */ - List expectedBounds({ - // x2 does not appear, because it has been eliminated + List expectedBounds( { + // x2 does not appear, because it has been eliminated - Tightening( 3, 5, Tightening::LB ), - Tightening( 3, 11, Tightening::UB ), + Tightening( 3, 5, Tightening::LB ), + Tightening( 3, 11, Tightening::UB ), - Tightening( 4, 3, Tightening::LB ), - Tightening( 4, 3, Tightening::UB ), - Tightening( 5, 5, Tightening::LB ), - Tightening( 5, 11, Tightening::UB ), + Tightening( 4, 3, Tightening::LB ), + Tightening( 4, 3, Tightening::UB ), + Tightening( 5, 5, Tightening::LB ), + Tightening( 5, 11, Tightening::UB ), - Tightening( 6, -8, Tightening::LB ), - Tightening( 6, -2, Tightening::UB ), - }); + Tightening( 6, -8, Tightening::LB ), + Tightening( 6, -2, Tightening::UB ), + } ); List bounds; TS_ASSERT_THROWS_NOTHING( nlr.getConstraintTightenings( bounds ) ); @@ -1760,8 +1775,16 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite for ( unsigned i = 0; i < simulationSize; ++i ) { - TS_ASSERT( FloatUtils::areEqual( ( *( nlr.getLayer( nlr.getNumberOfLayers() - 1 )->getSimulations() ) ).get( 0 ).get( i ), 1 ) ); - TS_ASSERT( FloatUtils::areEqual( ( *( nlr.getLayer( nlr.getNumberOfLayers() - 1 )->getSimulations() ) ).get( 1 ).get( i ), 4 ) ); + TS_ASSERT( FloatUtils::areEqual( + ( *( nlr.getLayer( nlr.getNumberOfLayers() - 1 )->getSimulations() ) ) + .get( 0 ) + .get( i ), + 1 ) ); + TS_ASSERT( FloatUtils::areEqual( + ( *( nlr.getLayer( nlr.getNumberOfLayers() - 1 )->getSimulations() ) ) + .get( 1 ) + .get( i ), + 4 ) ); } // With ReLUs, case 1 @@ -1773,8 +1796,16 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite for ( unsigned i = 0; i < simulationSize; ++i ) { - TS_ASSERT( FloatUtils::areEqual( ( *( nlr.getLayer( nlr.getNumberOfLayers() - 1 )->getSimulations() ) ).get( 0 ).get( i ), 1 ) ); - TS_ASSERT( FloatUtils::areEqual( ( *( nlr.getLayer( nlr.getNumberOfLayers() - 1 )->getSimulations() ) ).get( 1 ).get( i ), 1 ) ); + TS_ASSERT( FloatUtils::areEqual( + ( *( nlr.getLayer( nlr.getNumberOfLayers() - 1 )->getSimulations() ) ) + .get( 0 ) + .get( i ), + 1 ) ); + TS_ASSERT( FloatUtils::areEqual( + ( *( nlr.getLayer( nlr.getNumberOfLayers() - 1 )->getSimulations() ) ) + .get( 1 ) + .get( i ), + 1 ) ); } // With ReLUs, case 1 and 2 @@ -1786,8 +1817,16 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite for ( unsigned i = 0; i < simulationSize; ++i ) { - TS_ASSERT( FloatUtils::areEqual( ( *( nlr.getLayer( nlr.getNumberOfLayers() - 1 )->getSimulations() ) ).get( 0 ).get( i ), 0 ) ); - TS_ASSERT( FloatUtils::areEqual( ( *( nlr.getLayer( nlr.getNumberOfLayers() - 1 )->getSimulations() ) ).get( 1 ).get( i ), 0 ) ); + TS_ASSERT( FloatUtils::areEqual( + ( *( nlr.getLayer( nlr.getNumberOfLayers() - 1 )->getSimulations() ) ) + .get( 0 ) + .get( i ), + 0 ) ); + TS_ASSERT( FloatUtils::areEqual( + ( *( nlr.getLayer( nlr.getNumberOfLayers() - 1 )->getSimulations() ) ) + .get( 1 ) + .get( i ), + 0 ) ); } } @@ -1808,8 +1847,18 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite for ( unsigned i = 0; i < simulationSize; ++i ) { - TS_ASSERT( FloatUtils::areEqual( ( *( nlr.getLayer( nlr.getNumberOfLayers() - 1 )->getSimulations() ) ).get( 0 ).get( i ), 0.6750, 0.0001 ) ); - TS_ASSERT( FloatUtils::areEqual( ( *( nlr.getLayer( nlr.getNumberOfLayers() - 1 )->getSimulations() ) ).get( 1 ).get( i ), 3.0167, 0.0001 ) ); + TS_ASSERT( FloatUtils::areEqual( + ( *( nlr.getLayer( nlr.getNumberOfLayers() - 1 )->getSimulations() ) ) + .get( 0 ) + .get( i ), + 0.6750, + 0.0001 ) ); + TS_ASSERT( FloatUtils::areEqual( + ( *( nlr.getLayer( nlr.getNumberOfLayers() - 1 )->getSimulations() ) ) + .get( 1 ) + .get( i ), + 3.0167, + 0.0001 ) ); } // case 2 @@ -1821,8 +1870,18 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite for ( unsigned i = 0; i < simulationSize; ++i ) { - TS_ASSERT( FloatUtils::areEqual( ( *( nlr.getLayer( nlr.getNumberOfLayers() - 1 )->getSimulations() ) ).get( 0 ).get( i ), 0.6032, 0.0001 ) ); - TS_ASSERT( FloatUtils::areEqual( ( *( nlr.getLayer( nlr.getNumberOfLayers() - 1 )->getSimulations() ) ).get( 1 ).get( i ), 2.5790, 0.0001 ) ); + TS_ASSERT( FloatUtils::areEqual( + ( *( nlr.getLayer( nlr.getNumberOfLayers() - 1 )->getSimulations() ) ) + .get( 0 ) + .get( i ), + 0.6032, + 0.0001 ) ); + TS_ASSERT( FloatUtils::areEqual( + ( *( nlr.getLayer( nlr.getNumberOfLayers() - 1 )->getSimulations() ) ) + .get( 1 ) + .get( i ), + 2.5790, + 0.0001 ) ); } // case 3 @@ -1834,8 +1893,18 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite for ( unsigned i = 0; i < simulationSize; ++i ) { - TS_ASSERT( FloatUtils::areEqual( ( *( nlr.getLayer( nlr.getNumberOfLayers() - 1 )->getSimulations() ) ).get( 0 ).get( i ), 0.5045, 0.0001 ) ); - TS_ASSERT( FloatUtils::areEqual( ( *( nlr.getLayer( nlr.getNumberOfLayers() - 1 )->getSimulations() ) ).get( 1 ).get( i ), 2.1957, 0.0001 ) ); + TS_ASSERT( FloatUtils::areEqual( + ( *( nlr.getLayer( nlr.getNumberOfLayers() - 1 )->getSimulations() ) ) + .get( 0 ) + .get( i ), + 0.5045, + 0.0001 ) ); + TS_ASSERT( FloatUtils::areEqual( + ( *( nlr.getLayer( nlr.getNumberOfLayers() - 1 )->getSimulations() ) ) + .get( 1 ) + .get( i ), + 2.1957, + 0.0001 ) ); } } @@ -1893,7 +1962,11 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite TS_ASSERT_THROWS_NOTHING( nlr.simulate( &simulations1 ) ); for ( unsigned i = 0; i < simulationSize; ++i ) - TS_ASSERT( FloatUtils::areEqual( ( *( nlr.getLayer( nlr.getNumberOfLayers() - 1 )->getSimulations() ) ).get( 0 ).get( i ), 2 ) ); + TS_ASSERT( FloatUtils::areEqual( + ( *( nlr.getLayer( nlr.getNumberOfLayers() - 1 )->getSimulations() ) ) + .get( 0 ) + .get( i ), + 2 ) ); // Simulate2 Vector> simulations2; @@ -1903,7 +1976,11 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite TS_ASSERT_THROWS_NOTHING( nlr.simulate( &simulations2 ) ); for ( unsigned i = 0; i < simulationSize; ++i ) - TS_ASSERT( FloatUtils::areEqual( ( *( nlr.getLayer( nlr.getNumberOfLayers() - 1 )->getSimulations() ) ).get( 0 ).get( i ), 0 ) ); + TS_ASSERT( FloatUtils::areEqual( + ( *( nlr.getLayer( nlr.getNumberOfLayers() - 1 )->getSimulations() ) ) + .get( 0 ) + .get( i ), + 0 ) ); } void test_simulate_relus_and_abs() @@ -1961,8 +2038,16 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite for ( unsigned i = 0; i < simulationSize; ++i ) { - TS_ASSERT( FloatUtils::areEqual( ( *( nlr.getLayer( nlr.getNumberOfLayers() - 1 )->getSimulations() ) ).get( 0 ).get( i ), 2 ) ); - TS_ASSERT( FloatUtils::areEqual( ( *( nlr.getLayer( nlr.getNumberOfLayers() - 1 )->getSimulations() ) ).get( 1 ).get( i ), 2 ) ); + TS_ASSERT( FloatUtils::areEqual( + ( *( nlr.getLayer( nlr.getNumberOfLayers() - 1 )->getSimulations() ) ) + .get( 0 ) + .get( i ), + 2 ) ); + TS_ASSERT( FloatUtils::areEqual( + ( *( nlr.getLayer( nlr.getNumberOfLayers() - 1 )->getSimulations() ) ) + .get( 1 ) + .get( i ), + 2 ) ); } // Simulate2 @@ -1974,8 +2059,16 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite for ( unsigned i = 0; i < simulationSize; ++i ) { - TS_ASSERT( FloatUtils::areEqual( ( *( nlr.getLayer( nlr.getNumberOfLayers() - 1 )->getSimulations() ) ).get( 0 ).get( i ), 4 ) ); - TS_ASSERT( FloatUtils::areEqual( ( *( nlr.getLayer( nlr.getNumberOfLayers() - 1 )->getSimulations() ) ).get( 1 ).get( i ), 4 ) ); + TS_ASSERT( FloatUtils::areEqual( + ( *( nlr.getLayer( nlr.getNumberOfLayers() - 1 )->getSimulations() ) ) + .get( 0 ) + .get( i ), + 4 ) ); + TS_ASSERT( FloatUtils::areEqual( + ( *( nlr.getLayer( nlr.getNumberOfLayers() - 1 )->getSimulations() ) ) + .get( 1 ) + .get( i ), + 4 ) ); } } @@ -2034,7 +2127,7 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite populateNetwork( nlr ); InputQuery inputQuery; - inputQuery.setNumberOfVariables(14); + inputQuery.setNumberOfVariables( 14 ); // Initialize the bounds @@ -2044,18 +2137,30 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite inputQuery.setUpperBound( 1, 1 ); double large = 1000; - inputQuery.setLowerBound( 2, -large ); inputQuery.setUpperBound( 2, large ); - inputQuery.setLowerBound( 3, -large ); inputQuery.setUpperBound( 3, large ); - inputQuery.setLowerBound( 4, -large ); inputQuery.setUpperBound( 4, large ); - inputQuery.setLowerBound( 5, -large ); inputQuery.setUpperBound( 5, large ); - inputQuery.setLowerBound( 6, -large ); inputQuery.setUpperBound( 6, large ); - inputQuery.setLowerBound( 7, -large ); inputQuery.setUpperBound( 7, large ); - inputQuery.setLowerBound( 8, -large ); inputQuery.setUpperBound( 8, large ); - inputQuery.setLowerBound( 9, -large ); inputQuery.setUpperBound( 9, large ); - inputQuery.setLowerBound( 10, -large ); inputQuery.setUpperBound( 10, large ); - inputQuery.setLowerBound( 11, -large ); inputQuery.setUpperBound( 11, large ); - inputQuery.setLowerBound( 12, -large ); inputQuery.setUpperBound( 12, large ); - inputQuery.setLowerBound( 13, -large ); inputQuery.setUpperBound( 13, large ); + inputQuery.setLowerBound( 2, -large ); + inputQuery.setUpperBound( 2, large ); + inputQuery.setLowerBound( 3, -large ); + inputQuery.setUpperBound( 3, large ); + inputQuery.setLowerBound( 4, -large ); + inputQuery.setUpperBound( 4, large ); + inputQuery.setLowerBound( 5, -large ); + inputQuery.setUpperBound( 5, large ); + inputQuery.setLowerBound( 6, -large ); + inputQuery.setUpperBound( 6, large ); + inputQuery.setLowerBound( 7, -large ); + inputQuery.setUpperBound( 7, large ); + inputQuery.setLowerBound( 8, -large ); + inputQuery.setUpperBound( 8, large ); + inputQuery.setLowerBound( 9, -large ); + inputQuery.setUpperBound( 9, large ); + inputQuery.setLowerBound( 10, -large ); + inputQuery.setUpperBound( 10, large ); + inputQuery.setLowerBound( 11, -large ); + inputQuery.setUpperBound( 11, large ); + inputQuery.setLowerBound( 12, -large ); + inputQuery.setUpperBound( 12, large ); + inputQuery.setLowerBound( 13, -large ); + inputQuery.setUpperBound( 13, large ); // Initialize TS_ASSERT_THROWS_NOTHING( nlr.obtainCurrentBounds( inputQuery ) ); @@ -2063,37 +2168,25 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite // Perform the tightening pass TS_ASSERT_THROWS_NOTHING( nlr.intervalArithmeticBoundPropagation() ); - List expectedBounds({ - Tightening( 2, 0, Tightening::LB ), - Tightening( 2, 2, Tightening::UB ), - Tightening( 3, 0, Tightening::LB ), - Tightening( 3, 2, Tightening::UB ), - - Tightening( 4, -5, Tightening::LB ), - Tightening( 4, 5, Tightening::UB ), - Tightening( 5, 0, Tightening::LB ), - Tightening( 5, 5, Tightening::UB ), - - Tightening( 6, -1, Tightening::LB ), - Tightening( 6, 1, Tightening::UB ), - Tightening( 7, 0, Tightening::LB ), - Tightening( 7, 1, Tightening::UB ), - - Tightening( 8, -1, Tightening::LB ), - Tightening( 8, 7, Tightening::UB ), - Tightening( 9, 0, Tightening::LB ), - Tightening( 9, 7, Tightening::UB ), - - Tightening( 10, -1, Tightening::LB ), - Tightening( 10, 7, Tightening::UB ), - Tightening( 11, 0, Tightening::LB ), - Tightening( 11, 7, Tightening::UB ), - - Tightening( 12, 0, Tightening::LB ), - Tightening( 12, 7, Tightening::UB ), - Tightening( 13, 0, Tightening::LB ), - Tightening( 13, 28, Tightening::UB ), - }); + List expectedBounds( { + Tightening( 2, 0, Tightening::LB ), Tightening( 2, 2, Tightening::UB ), + Tightening( 3, 0, Tightening::LB ), Tightening( 3, 2, Tightening::UB ), + + Tightening( 4, -5, Tightening::LB ), Tightening( 4, 5, Tightening::UB ), + Tightening( 5, 0, Tightening::LB ), Tightening( 5, 5, Tightening::UB ), + + Tightening( 6, -1, Tightening::LB ), Tightening( 6, 1, Tightening::UB ), + Tightening( 7, 0, Tightening::LB ), Tightening( 7, 1, Tightening::UB ), + + Tightening( 8, -1, Tightening::LB ), Tightening( 8, 7, Tightening::UB ), + Tightening( 9, 0, Tightening::LB ), Tightening( 9, 7, Tightening::UB ), + + Tightening( 10, -1, Tightening::LB ), Tightening( 10, 7, Tightening::UB ), + Tightening( 11, 0, Tightening::LB ), Tightening( 11, 7, Tightening::UB ), + + Tightening( 12, 0, Tightening::LB ), Tightening( 12, 7, Tightening::UB ), + Tightening( 13, 0, Tightening::LB ), Tightening( 13, 28, Tightening::UB ), + } ); List bounds; TS_ASSERT_THROWS_NOTHING( nlr.getConstraintTightenings( bounds ) ); diff --git a/src/nlr/tests/Test_ParallelSolver.h b/src/nlr/tests/Test_ParallelSolver.h index 3e9c66ed45..b62a97de6f 100644 --- a/src/nlr/tests/Test_ParallelSolver.h +++ b/src/nlr/tests/Test_ParallelSolver.h @@ -13,12 +13,13 @@ **/ -#include #include "GurobiWrapper.h" #include "IterativePropagator.h" #include "NetworkLevelReasoner.h" #include "ParallelSolver.h" +#include + class MockForNetworkLevelReasoner { public: @@ -27,7 +28,6 @@ class MockForNetworkLevelReasoner class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite { public: - void setUp() { } @@ -41,9 +41,9 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite NLR::NetworkLevelReasoner nlr; NLR::IterativePropagator mock = NLR::IterativePropagator( &nlr ); unsigned numberOfWorkers = 4; - NLR::ParallelSolver::SolverQueue solvers ( numberOfWorkers ); + NLR::ParallelSolver::SolverQueue solvers( numberOfWorkers ); GurobiWrapper *gurobi = new GurobiWrapper(); - TS_ASSERT_THROWS_NOTHING( mock.enqueueSolver( solvers, gurobi) ); + TS_ASSERT_THROWS_NOTHING( mock.enqueueSolver( solvers, gurobi ) ); TS_ASSERT( !solvers.empty() ); GurobiWrapper *gurobiPtr = NULL; TS_ASSERT_THROWS_NOTHING( solvers.pop( gurobiPtr ) ); @@ -56,11 +56,11 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite NLR::NetworkLevelReasoner nlr; NLR::IterativePropagator mock = NLR::IterativePropagator( &nlr ); unsigned numberOfWorkers = 4; - NLR::ParallelSolver::SolverQueue solvers ( numberOfWorkers ); + NLR::ParallelSolver::SolverQueue solvers( numberOfWorkers ); for ( unsigned i = 0; i < numberOfWorkers; ++i ) { GurobiWrapper *gurobi = new GurobiWrapper(); - TS_ASSERT_THROWS_NOTHING( mock.enqueueSolver( solvers, gurobi) ); + TS_ASSERT_THROWS_NOTHING( mock.enqueueSolver( solvers, gurobi ) ); } TS_ASSERT( !solvers.empty() ); TS_ASSERT_THROWS_NOTHING( mock.clearSolverQueue( solvers ) ); diff --git a/src/nlr/tests/Test_WsLayerElimination.h b/src/nlr/tests/Test_WsLayerElimination.h index 058c6ac999..7336aa6649 100644 --- a/src/nlr/tests/Test_WsLayerElimination.h +++ b/src/nlr/tests/Test_WsLayerElimination.h @@ -13,7 +13,6 @@ **/ -#include #include "FloatUtils.h" #include "InputQuery.h" #include "Layer.h" @@ -21,6 +20,8 @@ #include "NetworkLevelReasoner.h" #include "Tightening.h" +#include + class MockForNetworkLevelReasoner { public: @@ -93,8 +94,8 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite nlr.addActivationSource( 3, 1, 4, 1 ); // Variable indexing - nlr.setNeuronVariable( NLR::NeuronIndex( 0, 0 ), 0); - nlr.setNeuronVariable( NLR::NeuronIndex( 0, 1 ), 1); + nlr.setNeuronVariable( NLR::NeuronIndex( 0, 0 ), 0 ); + nlr.setNeuronVariable( NLR::NeuronIndex( 0, 1 ), 1 ); nlr.setNeuronVariable( NLR::NeuronIndex( 1, 0 ), 2 ); nlr.setNeuronVariable( NLR::NeuronIndex( 1, 1 ), 3 ); @@ -140,8 +141,8 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite double *expectedOutput = new double[2]; for ( int i = -250; i < 250; ++i ) { - input[0] = ( i+4 ) / 2; - input[1] = ( 2*i ) / 3 - 3; + input[0] = ( i + 4 ) / 2; + input[1] = ( 2 * i ) / 3 - 3; nlr.evaluate( input, output ); expectedNlr.evaluate( input, expectedOutput ); @@ -373,7 +374,7 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite nlr.addLayer( 8, NLR::Layer::WEIGHTED_SUM, 2 ); nlr.addLayer( 9, NLR::Layer::SIGN, 2 ); - nlr.addLayer(10, NLR::Layer::WEIGHTED_SUM, 2); + nlr.addLayer( 10, NLR::Layer::WEIGHTED_SUM, 2 ); // Mark layer dependencies nlr.addLayerDependency( 0, 1 ); @@ -599,8 +600,8 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite double *expectedOutput = new double[2]; for ( int i = -250; i < 250; ++i ) { - input[0] = ( i+4 ) / 2; - input[1] = ( 2*i ) / 3 -3; + input[0] = ( i + 4 ) / 2; + input[1] = ( 2 * i ) / 3 - 3; input[2] = 15; nlr.evaluate( input, output ); @@ -663,8 +664,8 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite nlr.setWeight( 5, 1, 6, 1, 3 ); // [WS] 6 -> [WS] 7 - nlr.setWeight( 6, 0, 7, 0,-1 ); - nlr.setWeight( 6, 0, 7, 1,-2 ); + nlr.setWeight( 6, 0, 7, 0, -1 ); + nlr.setWeight( 6, 0, 7, 1, -2 ); nlr.setWeight( 6, 1, 7, 1, 5 ); nlr.setWeight( 6, 1, 7, 2, 1 ); @@ -814,8 +815,8 @@ class NetworkLevelReasonerTestSuite : public CxxTest::TestSuite for ( int i = -250; i < 250; ++i ) { - input[0] = ( i+19 ) / 2 -7; - input[1] = ( 3*i ) / 4 -1; + input[0] = ( i + 19 ) / 2 - 7; + input[1] = ( 3 * i ) / 4 - 1; nlr.evaluate( input, output ); expectedNlr.evaluate( input, expectedOutput ); diff --git a/src/proofs/BoundExplainer.cpp b/src/proofs/BoundExplainer.cpp index 1bf2852e2f..652995b02e 100644 --- a/src/proofs/BoundExplainer.cpp +++ b/src/proofs/BoundExplainer.cpp @@ -17,8 +17,8 @@ using namespace CVC4::context; BoundExplainer::BoundExplainer( unsigned numberOfVariables, unsigned numberOfRows, Context &ctx ) - : _context( ctx ), - _numberOfVariables( numberOfVariables ) + : _context( ctx ) + , _numberOfVariables( numberOfVariables ) , _numberOfRows( numberOfRows ) , _upperBoundExplanations( 0 ) , _lowerBoundExplanations( 0 ) @@ -30,7 +30,7 @@ BoundExplainer::BoundExplainer( unsigned numberOfVariables, unsigned numberOfRow _upperBoundExplanations.append( new ( true ) CDO( &ctx ) ); _lowerBoundExplanations.append( new ( true ) CDO( &ctx ) ); - _trivialUpperBoundExplanation.append( new ( true ) CDO( &ctx, true ) ) ; + _trivialUpperBoundExplanation.append( new ( true ) CDO( &ctx, true ) ); _trivialLowerBoundExplanation.append( new ( true ) CDO( &ctx, true ) ); } } @@ -58,7 +58,7 @@ BoundExplainer &BoundExplainer::operator=( const BoundExplainer &other ) for ( unsigned i = 0; i < _numberOfVariables; ++i ) { _upperBoundExplanations[i]->set( *other._upperBoundExplanations[i] ); - _lowerBoundExplanations[i]->set( *other._lowerBoundExplanations[i]); + _lowerBoundExplanations[i]->set( *other._lowerBoundExplanations[i] ); _trivialUpperBoundExplanation[i]->set( other._trivialUpperBoundExplanation[i]->get() ); _trivialLowerBoundExplanation[i]->set( other._trivialLowerBoundExplanation[i]->get() ); @@ -79,7 +79,7 @@ unsigned BoundExplainer::getNumberOfVariables() const const SparseUnsortedList &BoundExplainer::getExplanation( unsigned var, bool isUpper ) { - ASSERT ( var < _numberOfVariables ); + ASSERT( var < _numberOfVariables ); return isUpper ? _upperBoundExplanations[var]->get() : _lowerBoundExplanations[var]->get(); } @@ -96,7 +96,7 @@ void BoundExplainer::updateBoundExplanation( const TableauRow &row, bool isUpper if ( row._size == 0 ) return; - ASSERT ( var < _numberOfVariables ); + ASSERT( var < _numberOfVariables ); double curCoefficient; double ci = 0; double realCoefficient; @@ -135,11 +135,13 @@ void BoundExplainer::updateBoundExplanation( const TableauRow &row, bool isUpper if ( FloatUtils::isZero( realCoefficient ) ) continue; - // If we're currently explaining an upper bound, we use upper bound explanation iff variable's coefficient is positive - // If we're currently explaining a lower bound, we use upper bound explanation iff variable's coefficient is negative + // If we're currently explaining an upper bound, we use upper bound explanation iff + // variable's coefficient is positive If we're currently explaining a lower bound, we use + // upper bound explanation iff variable's coefficient is negative tempUpper = ( isUpper && realCoefficient > 0 ) || ( !isUpper && realCoefficient < 0 ); - if ( ( tempUpper && *_trivialUpperBoundExplanation[curVar] ) || ( !tempUpper && *_trivialLowerBoundExplanation[curVar] ) ) + if ( ( tempUpper && *_trivialUpperBoundExplanation[curVar] ) || + ( !tempUpper && *_trivialLowerBoundExplanation[curVar] ) ) continue; tempBound = tempUpper ? *_upperBoundExplanations[curVar] : *_lowerBoundExplanations[curVar]; @@ -153,9 +155,11 @@ void BoundExplainer::updateBoundExplanation( const TableauRow &row, bool isUpper if ( !FloatUtils::isZero( realCoefficient ) ) { tempUpper = ( isUpper && realCoefficient > 0 ) || ( !isUpper && realCoefficient < 0 ); - if ( !( tempUpper && *_trivialUpperBoundExplanation[row._lhs] ) && !( !tempUpper && *_trivialLowerBoundExplanation[row._lhs] ) ) + if ( !( tempUpper && *_trivialUpperBoundExplanation[row._lhs] ) && + !( !tempUpper && *_trivialLowerBoundExplanation[row._lhs] ) ) { - tempBound = tempUpper ? *_upperBoundExplanations[row._lhs] : *_lowerBoundExplanations[row._lhs]; + tempBound = tempUpper ? *_upperBoundExplanations[row._lhs] + : *_lowerBoundExplanations[row._lhs]; addVecTimesScalar( sum, tempBound, realCoefficient ); } } @@ -168,7 +172,9 @@ void BoundExplainer::updateBoundExplanation( const TableauRow &row, bool isUpper setExplanation( sum, var, isUpper ); } -void BoundExplainer::updateBoundExplanationSparse( const SparseUnsortedList &row, bool isUpper, unsigned var ) +void BoundExplainer::updateBoundExplanationSparse( const SparseUnsortedList &row, + bool isUpper, + unsigned var ) { if ( row.empty() ) return; @@ -204,14 +210,17 @@ void BoundExplainer::updateBoundExplanationSparse( const SparseUnsortedList &row if ( FloatUtils::isZero( realCoefficient ) ) continue; - // If we're currently explaining an upper bound, we use upper bound explanation iff variable's coefficient is positive - // If we're currently explaining a lower bound, we use upper bound explanation iff variable's coefficient is negative + // If we're currently explaining an upper bound, we use upper bound explanation iff + // variable's coefficient is positive If we're currently explaining a lower bound, we use + // upper bound explanation iff variable's coefficient is negative tempUpper = ( isUpper && realCoefficient > 0 ) || ( !isUpper && realCoefficient < 0 ); - if ( ( tempUpper && *_trivialUpperBoundExplanation[entry._index] ) || ( !tempUpper && *_trivialLowerBoundExplanation[entry._index] ) ) + if ( ( tempUpper && *_trivialUpperBoundExplanation[entry._index] ) || + ( !tempUpper && *_trivialLowerBoundExplanation[entry._index] ) ) continue; - tempBound = tempUpper ? *_upperBoundExplanations[entry._index] : *_lowerBoundExplanations[entry._index]; + tempBound = tempUpper ? *_upperBoundExplanations[entry._index] + : *_lowerBoundExplanations[entry._index]; addVecTimesScalar( sum, tempBound, realCoefficient ); } @@ -222,7 +231,9 @@ void BoundExplainer::updateBoundExplanationSparse( const SparseUnsortedList &row setExplanation( sum, var, isUpper ); } -void BoundExplainer::addVecTimesScalar( Vector &sum, const SparseUnsortedList &input, double scalar ) const +void BoundExplainer::addVecTimesScalar( Vector &sum, + const SparseUnsortedList &input, + double scalar ) const { if ( input.empty() || FloatUtils::isZero( scalar ) ) return; @@ -233,7 +244,9 @@ void BoundExplainer::addVecTimesScalar( Vector &sum, const SparseUnsorte sum[entry._index] += scalar * entry._value; } -void BoundExplainer::addVecTimesScalar( Vector &sum, const Vector &input, double scalar ) const +void BoundExplainer::addVecTimesScalar( Vector &sum, + const Vector &input, + double scalar ) const { if ( input.empty() || FloatUtils::isZero( scalar ) ) return; @@ -244,7 +257,9 @@ void BoundExplainer::addVecTimesScalar( Vector &sum, const Vector &coefficients, double ci ) const +void BoundExplainer::extractRowCoefficients( const TableauRow &row, + Vector &coefficients, + double ci ) const { ASSERT( coefficients.size() == _numberOfRows && row._size <= _numberOfVariables ); ASSERT( !FloatUtils::isZero( ci ) ); @@ -252,8 +267,10 @@ void BoundExplainer::extractRowCoefficients( const TableauRow &row, Vector= _numberOfVariables - _numberOfRows && !FloatUtils::isZero( row._row[i]._coefficient ) ) - coefficients[row._row[i]._var - _numberOfVariables + _numberOfRows] = row._row[i]._coefficient / ci; + if ( row._row[i]._var >= _numberOfVariables - _numberOfRows && + !FloatUtils::isZero( row._row[i]._coefficient ) ) + coefficients[row._row[i]._var - _numberOfVariables + _numberOfRows] = + row._row[i]._coefficient / ci; } // If the lhs was part of original basis, its coefficient is -1 / ci @@ -261,7 +278,9 @@ void BoundExplainer::extractRowCoefficients( const TableauRow &row, Vector &coefficients, double ci ) const +void BoundExplainer::extractSparseRowCoefficients( const SparseUnsortedList &row, + Vector &coefficients, + double ci ) const { ASSERT( coefficients.size() == _numberOfRows ); ASSERT( !FloatUtils::isZero( ci ) ); @@ -269,7 +288,8 @@ void BoundExplainer::extractSparseRowCoefficients( const SparseUnsortedList &row // The coefficients of the row m highest-indices vars are the coefficients of slack variables for ( const auto &entry : row ) { - if ( entry._index >= _numberOfVariables - _numberOfRows && !FloatUtils::isZero( entry._value ) ) + if ( entry._index >= _numberOfVariables - _numberOfRows && + !FloatUtils::isZero( entry._value ) ) coefficients[entry._index - _numberOfVariables + _numberOfRows] = entry._value / ci; } } @@ -294,30 +314,39 @@ void BoundExplainer::addVariable() void BoundExplainer::resetExplanation( unsigned var, bool isUpper ) { ASSERT( var < _numberOfVariables ); - isUpper ? _upperBoundExplanations[var]->set( SparseUnsortedList() ) : _lowerBoundExplanations[var]->set( SparseUnsortedList() ); + isUpper ? _upperBoundExplanations[var]->set( SparseUnsortedList() ) + : _lowerBoundExplanations[var]->set( SparseUnsortedList() ); - isUpper ? _trivialUpperBoundExplanation[var]->set( true ) : _trivialLowerBoundExplanation[var]->set( true ); + isUpper ? _trivialUpperBoundExplanation[var]->set( true ) + : _trivialLowerBoundExplanation[var]->set( true ); } void BoundExplainer::setExplanation( const Vector &explanation, unsigned var, bool isUpper ) { - ASSERT( var < _numberOfVariables && ( explanation.empty() || explanation.size() == _numberOfRows ) ); - CDO *temp = isUpper ? _upperBoundExplanations[var] : _lowerBoundExplanations[var]; + ASSERT( var < _numberOfVariables && + ( explanation.empty() || explanation.size() == _numberOfRows ) ); + CDO *temp = + isUpper ? _upperBoundExplanations[var] : _lowerBoundExplanations[var]; if ( explanation.empty() ) temp->set( SparseUnsortedList() ); else temp->set( SparseUnsortedList( explanation.data(), explanation.size() ) ); - isUpper ? _trivialUpperBoundExplanation[var]->set( false ) : _trivialLowerBoundExplanation[var]->set( false ); + isUpper ? _trivialUpperBoundExplanation[var]->set( false ) + : _trivialLowerBoundExplanation[var]->set( false ); } -void BoundExplainer::setExplanation( const SparseUnsortedList &explanation, unsigned var, bool isUpper ) +void BoundExplainer::setExplanation( const SparseUnsortedList &explanation, + unsigned var, + bool isUpper ) { ASSERT( var < _numberOfVariables ); - isUpper ? _upperBoundExplanations[var]->set( explanation ) : _lowerBoundExplanations[var]->set( explanation ); + isUpper ? _upperBoundExplanations[var]->set( explanation ) + : _lowerBoundExplanations[var]->set( explanation ); - isUpper ? _trivialUpperBoundExplanation[var]->set( false ) : _trivialLowerBoundExplanation[var]->set( false ); + isUpper ? _trivialUpperBoundExplanation[var]->set( false ) + : _trivialLowerBoundExplanation[var]->set( false ); } bool BoundExplainer::isExplanationTrivial( unsigned var, bool isUpper ) const diff --git a/src/proofs/BoundExplainer.h b/src/proofs/BoundExplainer.h index a60bb4eab9..929fa2117f 100644 --- a/src/proofs/BoundExplainer.h +++ b/src/proofs/BoundExplainer.h @@ -15,11 +15,11 @@ #ifndef __BoundsExplainer_h__ #define __BoundsExplainer_h__ -#include "context/cdo.h" -#include "context/context.h" #include "SparseUnsortedList.h" #include "TableauRow.h" #include "Vector.h" +#include "context/cdo.h" +#include "context/context.h" /* A class which encapsulates bounds explanations of all variables of a tableau @@ -27,7 +27,9 @@ class BoundExplainer { public: - BoundExplainer( unsigned numberOfVariables, unsigned numberOfRows, CVC4::context::Context &ctx ); + BoundExplainer( unsigned numberOfVariables, + unsigned numberOfRows, + CVC4::context::Context &ctx ); ~BoundExplainer(); BoundExplainer &operator=( const BoundExplainer &other ); @@ -57,7 +59,8 @@ class BoundExplainer void updateBoundExplanation( const TableauRow &row, bool isUpper, unsigned var ); /* - Given a row as SparseUnsortedList, updates the values of the bound explanations of a var according to the row + Given a row as SparseUnsortedList, updates the values of the bound explanations of a var + according to the row */ void updateBoundExplanationSparse( const SparseUnsortedList &row, bool isUpper, unsigned var ); @@ -98,24 +101,28 @@ class BoundExplainer /* Adds a multiplication of an array by scalar to another array */ - void addVecTimesScalar( Vector &sum, const SparseUnsortedList &input, double scalar ) const; + void + addVecTimesScalar( Vector &sum, const SparseUnsortedList &input, double scalar ) const; void addVecTimesScalar( Vector &sum, const Vector &input, double scalar ) const; /* - Upon receiving a row, extract coefficients of the original tableau's equations that create the row - Equivalently, extract the coefficients of the slack variables. - Assumption - the slack variables indices are always the last m. - All coefficients are divided by ci, the coefficient of the explained var, for normalization. + Upon receiving a row, extract coefficients of the original tableau's equations that create the + row Equivalently, extract the coefficients of the slack variables. Assumption - the slack + variables indices are always the last m. All coefficients are divided by ci, the coefficient + of the explained var, for normalization. */ - void extractRowCoefficients( const TableauRow &row, Vector &coefficients, double ci ) const; + void + extractRowCoefficients( const TableauRow &row, Vector &coefficients, double ci ) const; /* - Upon receiving a row given as a SparseUnsortedList, extract coefficients of the original tableau's equations that create the row - Equivalently, extract the coefficients of the slack variables. - Assumption - the slack variables indices are always the last m. - All coefficients are divided by ci, the coefficient of the explained var, for normalization. + Upon receiving a row given as a SparseUnsortedList, extract coefficients of the original + tableau's equations that create the row Equivalently, extract the coefficients of the slack + variables. Assumption - the slack variables indices are always the last m. All coefficients + are divided by ci, the coefficient of the explained var, for normalization. */ - void extractSparseRowCoefficients( const SparseUnsortedList &row, Vector &coefficients, double ci ) const; + void extractSparseRowCoefficients( const SparseUnsortedList &row, + Vector &coefficients, + double ci ) const; }; #endif // __BoundsExplainer_h__ diff --git a/src/proofs/Checker.cpp b/src/proofs/Checker.cpp index 4c136aacad..7f6c9b2d55 100644 --- a/src/proofs/Checker.cpp +++ b/src/proofs/Checker.cpp @@ -29,7 +29,7 @@ Checker::Checker( const UnsatCertificateNode *root, , _delegationCounter( 0 ) { for ( auto constraint : problemConstraints ) - constraint->setPhaseStatus( PHASE_NOT_FIXED ); + constraint->setPhaseStatus( PHASE_NOT_FIXED ); } bool Checker::check() @@ -51,7 +51,9 @@ bool Checker::checkNode( const UnsatCertificateNode *node ) auto &temp = tightening._type == Tightening::UB ? _groundUpperBounds : _groundLowerBounds; temp[tightening._variable] = tightening._value; - tightening._type == Tightening::UB ? _upperBoundChanges.top().insert( tightening._variable ) : _lowerBoundChanges.top().insert( tightening._variable ); + tightening._type == Tightening::UB + ? _upperBoundChanges.top().insert( tightening._variable ) + : _lowerBoundChanges.top().insert( tightening._variable ); } // Check all PLC bound propagations @@ -63,7 +65,8 @@ bool Checker::checkNode( const UnsatCertificateNode *node ) writeToFile(); // Skip if leaf has the SAT solution, or if was marked to delegate - if ( node->getSATSolutionFlag() || node->getDelegationStatus() != DelegationStatus::DONT_DELEGATE ) + if ( node->getSATSolutionFlag() || + node->getDelegationStatus() != DelegationStatus::DONT_DELEGATE ) return true; // Check if it is a leaf, and if so use contradiction to check @@ -87,7 +90,8 @@ bool Checker::checkNode( const UnsatCertificateNode *node ) for ( const auto &child : node->getChildren() ) childrenSplits.append( child->getSplit() ); - PiecewiseLinearConstraint *childrenSplitConstraint = getCorrespondingConstraint( childrenSplits ); + PiecewiseLinearConstraint *childrenSplitConstraint = + getCorrespondingConstraint( childrenSplits ); if ( !checkSingleVarSplits( childrenSplits ) && !childrenSplitConstraint ) return false; @@ -104,10 +108,12 @@ bool Checker::checkNode( const UnsatCertificateNode *node ) if ( childrenSplitConstraint ) childrenSplitConstraint->setPhaseStatus( PHASE_NOT_FIXED ); - if ( childrenSplitConstraint && childrenSplitConstraint->getType() == PiecewiseLinearFunctionType::DISJUNCTION ) + if ( childrenSplitConstraint && + childrenSplitConstraint->getType() == PiecewiseLinearFunctionType::DISJUNCTION ) { for ( const auto &child : node->getChildren() ) - ( ( DisjunctionConstraint * )childrenSplitConstraint )->addFeasibleDisjunct( child->getSplit() ); + ( (DisjunctionConstraint *)childrenSplitConstraint ) + ->addFeasibleDisjunct( child->getSplit() ); } // Revert only bounds that where changed during checking the current node @@ -123,25 +129,30 @@ bool Checker::checkNode( const UnsatCertificateNode *node ) return answer; } -void Checker::fixChildSplitPhase( UnsatCertificateNode *child, PiecewiseLinearConstraint *childrenSplitConstraint ) +void Checker::fixChildSplitPhase( UnsatCertificateNode *child, + PiecewiseLinearConstraint *childrenSplitConstraint ) { - if ( childrenSplitConstraint && childrenSplitConstraint->getType() == PiecewiseLinearFunctionType::RELU ) + if ( childrenSplitConstraint && + childrenSplitConstraint->getType() == PiecewiseLinearFunctionType::RELU ) { List tightenings = child->getSplit().getBoundTightenings(); - if ( tightenings.front()._type == Tightening::LB || tightenings.back()._type == Tightening::LB ) + if ( tightenings.front()._type == Tightening::LB || + tightenings.back()._type == Tightening::LB ) childrenSplitConstraint->setPhaseStatus( RELU_PHASE_ACTIVE ); else childrenSplitConstraint->setPhaseStatus( RELU_PHASE_INACTIVE ); } - else if ( childrenSplitConstraint && childrenSplitConstraint->getType() == PiecewiseLinearFunctionType::SIGN ) + else if ( childrenSplitConstraint && + childrenSplitConstraint->getType() == PiecewiseLinearFunctionType::SIGN ) { List tightenings = child->getSplit().getBoundTightenings(); - if ( tightenings.front()._type == Tightening::LB ) + if ( tightenings.front()._type == Tightening::LB ) childrenSplitConstraint->setPhaseStatus( SIGN_PHASE_POSITIVE ); else childrenSplitConstraint->setPhaseStatus( SIGN_PHASE_NEGATIVE ); } - else if ( childrenSplitConstraint && childrenSplitConstraint->getType() == PiecewiseLinearFunctionType::ABSOLUTE_VALUE ) + else if ( childrenSplitConstraint && + childrenSplitConstraint->getType() == PiecewiseLinearFunctionType::ABSOLUTE_VALUE ) { List tightenings = child->getSplit().getBoundTightenings(); if ( tightenings.front()._type == Tightening::LB ) @@ -149,19 +160,23 @@ void Checker::fixChildSplitPhase( UnsatCertificateNode *child, PiecewiseLinearC else childrenSplitConstraint->setPhaseStatus( ABS_PHASE_NEGATIVE ); } - else if ( childrenSplitConstraint && childrenSplitConstraint->getType() == PiecewiseLinearFunctionType::MAX ) + else if ( childrenSplitConstraint && + childrenSplitConstraint->getType() == PiecewiseLinearFunctionType::MAX ) { List tightenings = child->getSplit().getBoundTightenings(); if ( tightenings.size() == 2 ) childrenSplitConstraint->setPhaseStatus( MAX_PHASE_ELIMINATED ); else { - PhaseStatus phase = ( ( MaxConstraint * )childrenSplitConstraint )->variableToPhase( tightenings.back()._variable ); + PhaseStatus phase = ( (MaxConstraint *)childrenSplitConstraint ) + ->variableToPhase( tightenings.back()._variable ); childrenSplitConstraint->setPhaseStatus( phase ); } } - else if ( childrenSplitConstraint && childrenSplitConstraint->getType() == PiecewiseLinearFunctionType::DISJUNCTION ) - ( ( DisjunctionConstraint * )childrenSplitConstraint )->removeFeasibleDisjunct( child->getSplit() ); + else if ( childrenSplitConstraint && + childrenSplitConstraint->getType() == PiecewiseLinearFunctionType::DISJUNCTION ) + ( (DisjunctionConstraint *)childrenSplitConstraint ) + ->removeFeasibleDisjunct( child->getSplit() ); } bool Checker::checkContradiction( const UnsatCertificateNode *node ) const @@ -172,10 +187,16 @@ bool Checker::checkContradiction( const UnsatCertificateNode *node ) const if ( contradiction.empty() ) { unsigned infeasibleVar = node->getContradiction()->getVar(); - return FloatUtils::isNegative( _groundUpperBounds[infeasibleVar] - _groundLowerBounds[infeasibleVar] ); + return FloatUtils::isNegative( _groundUpperBounds[infeasibleVar] - + _groundLowerBounds[infeasibleVar] ); } - double contradictionUpperBound = UNSATCertificateUtils::computeCombinationUpperBound( contradiction, _initialTableau, _groundUpperBounds.data(), _groundLowerBounds.data(), _groundUpperBounds.size() ); + double contradictionUpperBound = + UNSATCertificateUtils::computeCombinationUpperBound( contradiction, + _initialTableau, + _groundUpperBounds.data(), + _groundLowerBounds.data(), + _groundUpperBounds.size() ); return FloatUtils::isNegative( contradictionUpperBound ); } @@ -189,7 +210,9 @@ bool Checker::checkAllPLCExplanations( const UnsatCertificateNode *node, double { PiecewiseLinearConstraint *matchedConstraint = NULL; BoundType affectedVarBound = plcLemma->getAffectedVarBound(); - double explainedBound = affectedVarBound == BoundType::UPPER ? FloatUtils::infinity() : FloatUtils::negativeInfinity(); + double explainedBound = affectedVarBound == BoundType::UPPER + ? FloatUtils::infinity() + : FloatUtils::negativeInfinity(); const List causingVars = plcLemma->getCausingVars(); unsigned affectedVar = plcLemma->getAffectedVar(); List participatingVars; @@ -205,7 +228,7 @@ bool Checker::checkAllPLCExplanations( const UnsatCertificateNode *node, double // If the constraint is max, then lemma variables might have been eliminated if ( constraint->getType() == MAX ) { - MaxConstraint *maxConstraint = ( MaxConstraint * ) constraint; + MaxConstraint *maxConstraint = (MaxConstraint *)constraint; for ( auto const &element : maxConstraint->getEliminatedElements() ) { participatingVars.append( element ); @@ -236,23 +259,34 @@ bool Checker::checkAllPLCExplanations( const UnsatCertificateNode *node, double // If so, update the ground bounds and continue auto &temp = affectedVarBound == BoundType::UPPER ? _groundUpperBounds : _groundLowerBounds; - bool isTighter = affectedVarBound == BoundType::UPPER ? FloatUtils::lt( explainedBound, temp[affectedVar] ) : FloatUtils::gt( explainedBound, temp[affectedVar] ); + bool isTighter = affectedVarBound == BoundType::UPPER + ? FloatUtils::lt( explainedBound, temp[affectedVar] ) + : FloatUtils::gt( explainedBound, temp[affectedVar] ); if ( isTighter ) { temp[affectedVar] = explainedBound; ASSERT( !_upperBoundChanges.empty() && !_lowerBoundChanges.empty() ); - affectedVarBound == BoundType::UPPER ? _upperBoundChanges.top().insert( affectedVar ) : _lowerBoundChanges.top().insert( affectedVar ); + affectedVarBound == BoundType::UPPER ? _upperBoundChanges.top().insert( affectedVar ) + : _lowerBoundChanges.top().insert( affectedVar ); } } return true; } -double Checker::explainBound( unsigned var, bool isUpper, const SparseUnsortedList &explanation ) const +double +Checker::explainBound( unsigned var, bool isUpper, const SparseUnsortedList &explanation ) const { - return UNSATCertificateUtils::computeBound( var, isUpper, explanation, _initialTableau, _groundUpperBounds.data(), _groundLowerBounds.data(), _groundUpperBounds.size() ); + return UNSATCertificateUtils::computeBound( var, + isUpper, + explanation, + _initialTableau, + _groundUpperBounds.data(), + _groundLowerBounds.data(), + _groundUpperBounds.size() ); } -PiecewiseLinearConstraint *Checker::getCorrespondingConstraint( const List &splits ) +PiecewiseLinearConstraint * +Checker::getCorrespondingConstraint( const List &splits ) { PiecewiseLinearConstraint *constraint = getCorrespondingReluConstraint( splits ); if ( !constraint ) @@ -289,10 +323,10 @@ void Checker::writeToFile() // Fix correct size if ( !tableauRow.getSize() && !tableauRow.empty() ) - for ( auto it = tableauRow.begin(); it != tableauRow.end(); ++it ) - tableauRow.incrementSize(); + for ( auto it = tableauRow.begin(); it != tableauRow.end(); ++it ) + tableauRow.incrementSize(); - SmtLibWriter::addTableauRow( tableauRow , leafInstance ); + SmtLibWriter::addTableauRow( tableauRow, leafInstance ); } for ( auto &constraint : _problemConstraints ) @@ -319,7 +353,7 @@ void Checker::writeToFile() } else if ( constraint->getType() == MAX ) { - MaxConstraint *maxConstraint = ( MaxConstraint * ) constraint; + MaxConstraint *maxConstraint = (MaxConstraint *)constraint; Set elements = maxConstraint->getParticipatingElements(); double info = 0; @@ -332,14 +366,19 @@ void Checker::writeToFile() for ( const auto &element : maxConstraint->getParticipatingVariables() ) elements.erase( element ); - SmtLibWriter::addMaxConstraint( constraint->getParticipatingVariables().back(), elements, constraint->getPhaseStatus(), info ,leafInstance ); + SmtLibWriter::addMaxConstraint( constraint->getParticipatingVariables().back(), + elements, + constraint->getPhaseStatus(), + info, + leafInstance ); } else if ( constraint->getType() == DISJUNCTION ) - SmtLibWriter::addDisjunctionConstraint( ( ( DisjunctionConstraint * )constraint )->getFeasibleDisjuncts(), leafInstance ); + SmtLibWriter::addDisjunctionConstraint( + ( (DisjunctionConstraint *)constraint )->getFeasibleDisjuncts(), leafInstance ); } SmtLibWriter::addFooter( leafInstance ); - File file ( "delegated" + std::to_string( _delegationCounter ) + ".smtlib" ); + File file( "delegated" + std::to_string( _delegationCounter ) + ".smtlib" ); SmtLibWriter::writeInstanceToFile( file, leafInstance ); ++_delegationCounter; @@ -361,11 +400,13 @@ bool Checker::checkSingleVarSplits( const List &splits auto &frontSplitOnlyTightening = frontSplitTightenings.front(); auto &backSplitOnlyTightening = backSplitTightenings.front(); - // Check that cases are of the same var and bound, where the for one the bound is UB, and for the other is LB + // Check that cases are of the same var and bound, where the for one the bound is UB, and for + // the other is LB if ( frontSplitOnlyTightening._variable != backSplitOnlyTightening._variable ) return false; - if ( FloatUtils::areDisequal( frontSplitOnlyTightening._value, backSplitOnlyTightening._value ) ) + if ( FloatUtils::areDisequal( frontSplitOnlyTightening._value, + backSplitOnlyTightening._value ) ) return false; if ( frontSplitOnlyTightening._type == backSplitOnlyTightening._type ) @@ -374,7 +415,8 @@ bool Checker::checkSingleVarSplits( const List &splits return true; } -PiecewiseLinearConstraint *Checker::getCorrespondingReluConstraint( const List &splits ) +PiecewiseLinearConstraint * +Checker::getCorrespondingReluConstraint( const List &splits ) { if ( splits.size() != 2 ) return NULL; @@ -383,8 +425,12 @@ PiecewiseLinearConstraint *Checker::getCorrespondingReluConstraint( const List

getParticipatingVariables(); - if ( constraint->getType() == PiecewiseLinearFunctionType::RELU && constraintVars.front() == b && constraintVars.exists( f ) && ( activeSplit.size() == 1 || constraintVars.back() == aux ) ) + if ( constraint->getType() == PiecewiseLinearFunctionType::RELU && + constraintVars.front() == b && constraintVars.exists( f ) && + ( activeSplit.size() == 1 || constraintVars.back() == aux ) ) correspondingConstraint = constraint; } @@ -410,7 +461,8 @@ PiecewiseLinearConstraint *Checker::getCorrespondingReluConstraint( const List

&splits ) +PiecewiseLinearConstraint * +Checker::getCorrespondingSignConstraint( const List &splits ) { if ( splits.size() != 2 ) return NULL; @@ -419,17 +471,28 @@ PiecewiseLinearConstraint *Checker::getCorrespondingSignConstraint( const List

getParticipatingVariables(); - if ( constraint->getType() == PiecewiseLinearFunctionType::SIGN && constraintVars.back() == b && constraintVars.front() == f ) + if ( constraint->getType() == PiecewiseLinearFunctionType::SIGN && + constraintVars.back() == b && constraintVars.front() == f ) correspondingConstraint = constraint; } @@ -445,7 +509,8 @@ PiecewiseLinearConstraint *Checker::getCorrespondingSignConstraint( const List

&splits ) +PiecewiseLinearConstraint * +Checker::getCorrespondingAbsConstraint( const List &splits ) { if ( splits.size() != 2 ) return NULL; @@ -454,18 +519,29 @@ PiecewiseLinearConstraint *Checker::getCorrespondingAbsConstraint( const ListgetParticipatingVariables(); - if ( constraint->getType() == PiecewiseLinearFunctionType::ABSOLUTE_VALUE && constraintVars.front() == b && constraintVars.back() == negAux && constraintVars.exists( posAux ) ) + if ( constraint->getType() == PiecewiseLinearFunctionType::ABSOLUTE_VALUE && + constraintVars.front() == b && constraintVars.back() == negAux && + constraintVars.exists( posAux ) ) correspondingConstraint = constraint; } @@ -481,7 +559,8 @@ PiecewiseLinearConstraint *Checker::getCorrespondingAbsConstraint( const List &splits ) +PiecewiseLinearConstraint * +Checker::getCorrespondingMaxConstraint( const List &splits ) { for ( auto &constraint : _problemConstraints ) { @@ -490,13 +569,15 @@ PiecewiseLinearConstraint *Checker::getCorrespondingMaxConstraint( const List constraintSplits = constraint->getCaseSplits(); - MaxConstraint *maxConstraint = ( MaxConstraint * ) constraint; + MaxConstraint *maxConstraint = (MaxConstraint *)constraint; for ( auto const &element : maxConstraint->getEliminatedElements() ) { PiecewiseLinearCaseSplit eliminatedElementCaseSplit; - eliminatedElementCaseSplit.storeBoundTightening( Tightening( element, 0, Tightening::UB ) ); + eliminatedElementCaseSplit.storeBoundTightening( + Tightening( element, 0, Tightening::UB ) ); constraintSplits.append( eliminatedElementCaseSplit ); } @@ -505,10 +586,13 @@ PiecewiseLinearConstraint *Checker::getCorrespondingMaxConstraint( const ListgetF() && - splits.back().getBoundTightenings().back()._type != splits.front().getBoundTightenings().back()._type ) + if ( splits.size() == 2 && splits.back().getBoundTightenings().size() == 1 && + splits.front().getBoundTightenings().size() == 1 && + splits.back().getBoundTightenings().back()._variable == + splits.front().getBoundTightenings().back()._variable && + splits.back().getBoundTightenings().back()._variable == maxConstraint->getF() && + splits.back().getBoundTightenings().back()._type != + splits.front().getBoundTightenings().back()._type ) return constraint; if ( constraintMatched ) @@ -517,7 +601,8 @@ PiecewiseLinearConstraint *Checker::getCorrespondingMaxConstraint( const List & splits ) +PiecewiseLinearConstraint * +Checker::getCorrespondingDisjunctionConstraint( const List &splits ) { for ( auto &constraint : _problemConstraints ) { @@ -526,7 +611,8 @@ PiecewiseLinearConstraint *Checker::getCorrespondingDisjunctionConstraint( const bool constraintMatched = true; - // constraintMatched will remain true iff the splits list is the same as the list of disjuncts (up to order) + // constraintMatched will remain true iff the splits list is the same as the list of + // disjuncts (up to order) for ( const auto &split : constraint->getCaseSplits() ) if ( !splits.exists( split ) ) constraintMatched = false; @@ -541,7 +627,9 @@ PiecewiseLinearConstraint *Checker::getCorrespondingDisjunctionConstraint( const return NULL; } -double Checker::checkReluLemma( const PLCLemma &expl, PiecewiseLinearConstraint &constraint, double epsilon ) +double Checker::checkReluLemma( const PLCLemma &expl, + PiecewiseLinearConstraint &constraint, + double epsilon ) { ASSERT( constraint.getType() == RELU && expl.getConstraintType() == RELU && epsilon > 0 ); ASSERT( expl.getCausingVars().size() == 1 ); @@ -554,7 +642,14 @@ double Checker::checkReluLemma( const PLCLemma &expl, PiecewiseLinearConstraint BoundType affectedVarBound = expl.getAffectedVarBound(); ASSERT( explanations.size() == 1 ); - double explainedBound = UNSATCertificateUtils::computeBound( causingVar, causingVarBound == BoundType::UPPER, explanations.back(), _initialTableau, _groundUpperBounds.data(), _groundLowerBounds.data(), _groundUpperBounds.size() ); + double explainedBound = + UNSATCertificateUtils::computeBound( causingVar, + causingVarBound == BoundType::UPPER, + explanations.back(), + _initialTableau, + _groundUpperBounds.data(), + _groundLowerBounds.data(), + _groundUpperBounds.size() ); List constraintVars = constraint.getParticipatingVariables(); ASSERT( constraintVars.size() == 3 ); @@ -565,58 +660,87 @@ double Checker::checkReluLemma( const PLCLemma &expl, PiecewiseLinearConstraint unsigned aux = conVec[2]; // If explanation is phase fixing, mark it - if ( ( affectedVarBound == BoundType::LOWER && affectedVar == f && FloatUtils::isPositive( bound ) ) || ( affectedVarBound == BoundType::UPPER && affectedVar == aux && FloatUtils::isZero( bound ) ) ) + if ( ( affectedVarBound == BoundType::LOWER && affectedVar == f && + FloatUtils::isPositive( bound ) ) || + ( affectedVarBound == BoundType::UPPER && affectedVar == aux && + FloatUtils::isZero( bound ) ) ) constraint.setPhaseStatus( RELU_PHASE_ACTIVE ); - else if ( ( affectedVarBound == BoundType::LOWER && affectedVar == aux && FloatUtils::isPositive( bound ) ) || ( affectedVarBound == BoundType::UPPER && affectedVar == f && FloatUtils::isZero( bound ) ) ) + else if ( ( affectedVarBound == BoundType::LOWER && affectedVar == aux && + FloatUtils::isPositive( bound ) ) || + ( affectedVarBound == BoundType::UPPER && affectedVar == f && + FloatUtils::isZero( bound ) ) ) constraint.setPhaseStatus( RELU_PHASE_INACTIVE ); - // Make sure the explanation is explained using a ReLU bound tightening. Cases are matching each rule in ReluConstraint.cpp - // We allow explained bound to be tighter than the ones recorded (since an explanation can explain tighter bounds), and an epsilon sized error is tolerated. + // Make sure the explanation is explained using a ReLU bound tightening. Cases are matching each + // rule in ReluConstraint.cpp We allow explained bound to be tighter than the ones recorded + // (since an explanation can explain tighter bounds), and an epsilon sized error is tolerated. // If lb of b is non negative, then ub of aux is 0 - if ( causingVar == b && causingVarBound == BoundType::LOWER && affectedVar == aux && affectedVarBound == BoundType::UPPER && !FloatUtils::isNegative( explainedBound + epsilon ) ) + if ( causingVar == b && causingVarBound == BoundType::LOWER && affectedVar == aux && + affectedVarBound == BoundType::UPPER && + !FloatUtils::isNegative( explainedBound + epsilon ) ) return 0; // If lb of f is positive, then ub if aux is 0 - else if ( causingVar == f && causingVarBound == BoundType::LOWER && affectedVar == aux && affectedVarBound == BoundType::UPPER && FloatUtils::isPositive( explainedBound + epsilon ) ) + else if ( causingVar == f && causingVarBound == BoundType::LOWER && affectedVar == aux && + affectedVarBound == BoundType::UPPER && + FloatUtils::isPositive( explainedBound + epsilon ) ) return 0; // If lb of b is negative x, then ub of aux is -x - else if ( causingVar == b && causingVarBound == BoundType::LOWER && affectedVar == aux && affectedVarBound == BoundType::UPPER && FloatUtils::isNegative( explainedBound - epsilon ) ) + else if ( causingVar == b && causingVarBound == BoundType::LOWER && affectedVar == aux && + affectedVarBound == BoundType::UPPER && + FloatUtils::isNegative( explainedBound - epsilon ) ) return -explainedBound; // If lb of aux is positive, then ub of f is 0 - else if ( causingVar == aux && causingVarBound == BoundType::LOWER && affectedVar == f && affectedVarBound == BoundType::UPPER && FloatUtils::isPositive( explainedBound + epsilon ) ) + else if ( causingVar == aux && causingVarBound == BoundType::LOWER && affectedVar == f && + affectedVarBound == BoundType::UPPER && + FloatUtils::isPositive( explainedBound + epsilon ) ) return 0; // If lb of f is negative, then it is 0 - else if ( causingVar == f && causingVarBound == BoundType::LOWER && affectedVar == f && affectedVarBound == BoundType::LOWER && FloatUtils::isNegative( explainedBound - epsilon ) ) + else if ( causingVar == f && causingVarBound == BoundType::LOWER && affectedVar == f && + affectedVarBound == BoundType::LOWER && + FloatUtils::isNegative( explainedBound - epsilon ) ) return 0; // Propagate ub from f to b - else if ( causingVar == f && causingVarBound == BoundType::UPPER && affectedVar == b && affectedVarBound ==BoundType::UPPER ) + else if ( causingVar == f && causingVarBound == BoundType::UPPER && affectedVar == b && + affectedVarBound == BoundType::UPPER ) return explainedBound; // If ub of b is non positive, then ub of f is 0 - else if ( causingVar == b && causingVarBound == BoundType::UPPER && affectedVar == f && affectedVarBound == BoundType::UPPER && !FloatUtils::isPositive( explainedBound - epsilon ) ) + else if ( causingVar == b && causingVarBound == BoundType::UPPER && affectedVar == f && + affectedVarBound == BoundType::UPPER && + !FloatUtils::isPositive( explainedBound - epsilon ) ) return 0; // If ub of b is non positive x, then lb of aux is -x - else if ( causingVar == b && causingVarBound == BoundType::UPPER && affectedVar == aux && affectedVarBound == BoundType::LOWER && !FloatUtils::isPositive( explainedBound - epsilon ) ) + else if ( causingVar == b && causingVarBound == BoundType::UPPER && affectedVar == aux && + affectedVarBound == BoundType::LOWER && + !FloatUtils::isPositive( explainedBound - epsilon ) ) return -explainedBound; - // If ub of b is positive, then propagate to f ( positivity of explained bound is not checked since negative explained ub can always explain positive bound ) - else if ( causingVar == b && causingVarBound == BoundType::UPPER && affectedVar == f && affectedVarBound == BoundType::UPPER && FloatUtils::isPositive( explainedBound + epsilon ) ) + // If ub of b is positive, then propagate to f ( positivity of explained bound is not checked + // since negative explained ub can always explain positive bound ) + else if ( causingVar == b && causingVarBound == BoundType::UPPER && affectedVar == f && + affectedVarBound == BoundType::UPPER && + FloatUtils::isPositive( explainedBound + epsilon ) ) return explainedBound; // If ub of aux is x, then lb of b is -x - else if ( causingVar == aux && causingVarBound == BoundType::UPPER && affectedVar == b && affectedVarBound == BoundType::LOWER ) + else if ( causingVar == aux && causingVarBound == BoundType::UPPER && affectedVar == b && + affectedVarBound == BoundType::LOWER ) return -explainedBound; - return affectedVarBound == BoundType::UPPER ? FloatUtils::infinity() : FloatUtils::negativeInfinity(); + return affectedVarBound == BoundType::UPPER ? FloatUtils::infinity() + : FloatUtils::negativeInfinity(); } -double Checker::checkSignLemma( const PLCLemma &expl, PiecewiseLinearConstraint &constraint, double epsilon ) +double Checker::checkSignLemma( const PLCLemma &expl, + PiecewiseLinearConstraint &constraint, + double epsilon ) { ASSERT( constraint.getType() == SIGN && expl.getConstraintType() == SIGN && epsilon > 0 ); ASSERT( expl.getCausingVars().size() == 1 ); @@ -629,50 +753,79 @@ double Checker::checkSignLemma( const PLCLemma &expl, PiecewiseLinearConstraint BoundType affectedVarBound = expl.getAffectedVarBound(); ASSERT( explanations.size() == 1 ); - double explainedBound = UNSATCertificateUtils::computeBound( causingVar, causingVarBound == BoundType::UPPER, explanations.front(), _initialTableau, _groundUpperBounds.data(), _groundLowerBounds.data(), _groundUpperBounds.size() ); + double explainedBound = + UNSATCertificateUtils::computeBound( causingVar, + causingVarBound == BoundType::UPPER, + explanations.front(), + _initialTableau, + _groundUpperBounds.data(), + _groundLowerBounds.data(), + _groundUpperBounds.size() ); List constraintVars = constraint.getParticipatingVariables(); - ASSERT(constraintVars.size() == 2 ); + ASSERT( constraintVars.size() == 2 ); unsigned b = constraintVars.front(); unsigned f = constraintVars.back(); // Any explanation is phase fixing - if ( ( affectedVarBound == BoundType::LOWER && affectedVar == f && FloatUtils::gt( bound, -1 ) ) || ( affectedVarBound == BoundType::LOWER && affectedVar == b && !FloatUtils::isNegative( bound ) ) ) + if ( ( affectedVarBound == BoundType::LOWER && affectedVar == f && + FloatUtils::gt( bound, -1 ) ) || + ( affectedVarBound == BoundType::LOWER && affectedVar == b && + !FloatUtils::isNegative( bound ) ) ) constraint.setPhaseStatus( SIGN_PHASE_POSITIVE ); - else if ( ( affectedVarBound == BoundType::UPPER && affectedVar == f && FloatUtils::gt( bound, 1 ) ) || ( affectedVarBound == BoundType::UPPER && affectedVar == b && FloatUtils::isNegative( bound ) ) ) + else if ( ( affectedVarBound == BoundType::UPPER && affectedVar == f && + FloatUtils::gt( bound, 1 ) ) || + ( affectedVarBound == BoundType::UPPER && affectedVar == b && + FloatUtils::isNegative( bound ) ) ) constraint.setPhaseStatus( SIGN_PHASE_NEGATIVE ); - // Make sure the explanation is explained using a sign bound tightening. Cases are matching each rule in SignConstraint.cpp - // We allow explained bound to be tighter than the ones recorded (since an explanation can explain tighter bounds), and an epsilon sized error is tolerated. + // Make sure the explanation is explained using a sign bound tightening. Cases are matching each + // rule in SignConstraint.cpp We allow explained bound to be tighter than the ones recorded + // (since an explanation can explain tighter bounds), and an epsilon sized error is tolerated. // If lb of f is > -1, then lb of f is 1 - if ( causingVar == f && causingVarBound == BoundType::LOWER && affectedVar == f && affectedVarBound == BoundType::LOWER && FloatUtils::areEqual( bound, 1 ) && FloatUtils::gte( explainedBound + epsilon, -1 ) ) + if ( causingVar == f && causingVarBound == BoundType::LOWER && affectedVar == f && + affectedVarBound == BoundType::LOWER && FloatUtils::areEqual( bound, 1 ) && + FloatUtils::gte( explainedBound + epsilon, -1 ) ) return 1; // If lb of f is > -1, then lb of b is 0 - else if ( causingVar == f && causingVarBound == BoundType::LOWER && affectedVar == b && affectedVarBound == BoundType::LOWER && FloatUtils::isZero( bound ) && FloatUtils::gte( explainedBound + epsilon, -1 ) ) + else if ( causingVar == f && causingVarBound == BoundType::LOWER && affectedVar == b && + affectedVarBound == BoundType::LOWER && FloatUtils::isZero( bound ) && + FloatUtils::gte( explainedBound + epsilon, -1 ) ) return 0; // If lb of b is non negative, then lb of f is 1 - else if ( causingVar == b && causingVarBound == BoundType::LOWER && affectedVar == f && affectedVarBound == BoundType::LOWER && FloatUtils::areEqual( bound, 1 ) && !FloatUtils::isNegative( explainedBound + epsilon ) ) + else if ( causingVar == b && causingVarBound == BoundType::LOWER && affectedVar == f && + affectedVarBound == BoundType::LOWER && FloatUtils::areEqual( bound, 1 ) && + !FloatUtils::isNegative( explainedBound + epsilon ) ) return 1; // If ub of f is < 1, then ub of f is -1 - else if ( causingVar == f && causingVarBound == BoundType::UPPER && affectedVar == f && affectedVarBound == BoundType::UPPER && FloatUtils::areEqual( bound, -1 ) && FloatUtils::lte( explainedBound - epsilon, 1 ) ) + else if ( causingVar == f && causingVarBound == BoundType::UPPER && affectedVar == f && + affectedVarBound == BoundType::UPPER && FloatUtils::areEqual( bound, -1 ) && + FloatUtils::lte( explainedBound - epsilon, 1 ) ) return -1; // If ub of f is < 1, then ub of b is 0 - else if ( causingVar == f && causingVarBound == BoundType::UPPER && affectedVar == b && affectedVarBound == BoundType::UPPER && FloatUtils::isZero( bound ) && FloatUtils::lte( explainedBound - epsilon, 1 ) ) + else if ( causingVar == f && causingVarBound == BoundType::UPPER && affectedVar == b && + affectedVarBound == BoundType::UPPER && FloatUtils::isZero( bound ) && + FloatUtils::lte( explainedBound - epsilon, 1 ) ) return 0; // If ub of b is negative, then ub of f is -1 - else if ( causingVar == b && causingVarBound == BoundType::UPPER && affectedVar == f && affectedVarBound == BoundType::UPPER && FloatUtils::areEqual( bound, -1 ) && FloatUtils::isNegative( explainedBound - epsilon ) ) + else if ( causingVar == b && causingVarBound == BoundType::UPPER && affectedVar == f && + affectedVarBound == BoundType::UPPER && FloatUtils::areEqual( bound, -1 ) && + FloatUtils::isNegative( explainedBound - epsilon ) ) return -1; - return affectedVarBound == BoundType::UPPER ? FloatUtils::infinity() : FloatUtils::negativeInfinity(); + return affectedVarBound == BoundType::UPPER ? FloatUtils::infinity() + : FloatUtils::negativeInfinity(); } -double Checker::checkAbsLemma( const PLCLemma &expl, PiecewiseLinearConstraint &constraint, double epsilon ) +double Checker::checkAbsLemma( const PLCLemma &expl, + PiecewiseLinearConstraint &constraint, + double epsilon ) { ASSERT( constraint.getType() == ABSOLUTE_VALUE && expl.getConstraintType() == ABSOLUTE_VALUE ); ASSERT( expl.getCausingVars().size() == 2 || expl.getCausingVars().size() == 1 ); @@ -682,7 +835,7 @@ double Checker::checkAbsLemma( const PLCLemma &expl, PiecewiseLinearConstraint & unsigned affectedVar = expl.getAffectedVar(); double bound = expl.getBound(); List constraintVars = constraint.getParticipatingVariables(); - ASSERT(constraintVars.size() == 4 ); + ASSERT( constraintVars.size() == 4 ); Vector conVec( constraintVars.begin(), constraintVars.end() ); unsigned b = conVec[0]; @@ -690,8 +843,9 @@ double Checker::checkAbsLemma( const PLCLemma &expl, PiecewiseLinearConstraint & unsigned pos = conVec[2]; unsigned neg = conVec[3]; - // Make sure the explanation is explained using an absolute value bound tightening. Cases are matching each rule in AbsolutValueConstraint.cpp - // We allow explained bound to be tighter than the ones recorded (since an explanation can explain tighter bounds) + // Make sure the explanation is explained using an absolute value bound tightening. Cases are + // matching each rule in AbsolutValueConstraint.cpp We allow explained bound to be tighter than + // the ones recorded (since an explanation can explain tighter bounds) if ( expl.getCausingVars().size() == 2 ) { @@ -704,34 +858,67 @@ double Checker::checkAbsLemma( const PLCLemma &expl, PiecewiseLinearConstraint & // Case of a non phase-fixing lemma if ( firstCausingVar == secondCausingVar ) { - double explainedUpperBound = UNSATCertificateUtils::computeBound( firstCausingVar, BoundType::UPPER, firstExplanation, _initialTableau, _groundUpperBounds.data(), _groundLowerBounds.data(), _groundUpperBounds.size() ); - double explainedLowerBound = UNSATCertificateUtils::computeBound( secondCausingVar, BoundType::LOWER, secondExplanation, _initialTableau, _groundUpperBounds.data(), _groundLowerBounds.data(), _groundUpperBounds.size() ); + double explainedUpperBound = + UNSATCertificateUtils::computeBound( firstCausingVar, + BoundType::UPPER, + firstExplanation, + _initialTableau, + _groundUpperBounds.data(), + _groundLowerBounds.data(), + _groundUpperBounds.size() ); + double explainedLowerBound = + UNSATCertificateUtils::computeBound( secondCausingVar, + BoundType::LOWER, + secondExplanation, + _initialTableau, + _groundUpperBounds.data(), + _groundLowerBounds.data(), + _groundUpperBounds.size() ); // b is always the causing var, affecting the ub of f - if ( affectedVar == f && firstCausingVar == b && affectedVarBound == BoundType::UPPER && bound > 0 ) + if ( affectedVar == f && firstCausingVar == b && affectedVarBound == BoundType::UPPER && + bound > 0 ) return FloatUtils::max( explainedUpperBound, -explainedLowerBound ); - return affectedVarBound == BoundType::UPPER ? FloatUtils::infinity() : FloatUtils::negativeInfinity(); + return affectedVarBound == BoundType::UPPER ? FloatUtils::infinity() + : FloatUtils::negativeInfinity(); } // Cases of a phase-fixing lemma else { ASSERT( firstCausingVar == b && secondCausingVar == f ); - double explainedBBound = UNSATCertificateUtils::computeBound( firstCausingVar, causingVarBound == BoundType::UPPER, firstExplanation, _initialTableau, _groundUpperBounds.data(), _groundLowerBounds.data(), _groundUpperBounds.size() ); - double explainedFBound = UNSATCertificateUtils::computeBound( secondCausingVar, BoundType::LOWER, secondExplanation, _initialTableau, _groundUpperBounds.data(), _groundLowerBounds.data(), _groundUpperBounds.size() ); - - if ( affectedVar == neg && causingVarBound == BoundType::UPPER && explainedFBound > explainedBBound - epsilon && bound == 0 ) + double explainedBBound = + UNSATCertificateUtils::computeBound( firstCausingVar, + causingVarBound == BoundType::UPPER, + firstExplanation, + _initialTableau, + _groundUpperBounds.data(), + _groundLowerBounds.data(), + _groundUpperBounds.size() ); + double explainedFBound = + UNSATCertificateUtils::computeBound( secondCausingVar, + BoundType::LOWER, + secondExplanation, + _initialTableau, + _groundUpperBounds.data(), + _groundLowerBounds.data(), + _groundUpperBounds.size() ); + + if ( affectedVar == neg && causingVarBound == BoundType::UPPER && + explainedFBound > explainedBBound - epsilon && bound == 0 ) { constraint.setPhaseStatus( ABS_PHASE_NEGATIVE ); return 0; } - else if ( affectedVar == pos && causingVarBound == BoundType::LOWER && explainedFBound > -explainedBBound - epsilon && bound == 0 ) + else if ( affectedVar == pos && causingVarBound == BoundType::LOWER && + explainedFBound > -explainedBBound - epsilon && bound == 0 ) { constraint.setPhaseStatus( ABS_PHASE_POSITIVE ); return 0; } - return affectedVarBound == BoundType::UPPER ? FloatUtils::infinity() : FloatUtils::negativeInfinity(); + return affectedVarBound == BoundType::UPPER ? FloatUtils::infinity() + : FloatUtils::negativeInfinity(); } } @@ -739,36 +926,48 @@ double Checker::checkAbsLemma( const PLCLemma &expl, PiecewiseLinearConstraint & const List &explanation = expl.getExplanations(); unsigned causingVar = expl.getCausingVars().front(); - double explainedBound = UNSATCertificateUtils::computeBound( causingVar, causingVarBound == BoundType::UPPER, explanation.front(), _initialTableau, _groundUpperBounds.data(), _groundLowerBounds.data(), _groundUpperBounds.size() ); - - if ( affectedVar == pos && causingVar == b && causingVarBound == BoundType::LOWER && !FloatUtils::isNegative( explainedBound + epsilon ) && bound == 0 ) + double explainedBound = + UNSATCertificateUtils::computeBound( causingVar, + causingVarBound == BoundType::UPPER, + explanation.front(), + _initialTableau, + _groundUpperBounds.data(), + _groundLowerBounds.data(), + _groundUpperBounds.size() ); + + if ( affectedVar == pos && causingVar == b && causingVarBound == BoundType::LOWER && + !FloatUtils::isNegative( explainedBound + epsilon ) && bound == 0 ) { constraint.setPhaseStatus( ABS_PHASE_POSITIVE ); return 0; } - else if ( affectedVar == neg && causingVar == b && causingVarBound == BoundType::UPPER && !FloatUtils::isPositive( explainedBound - epsilon ) && bound == 0 ) + else if ( affectedVar == neg && causingVar == b && causingVarBound == BoundType::UPPER && + !FloatUtils::isPositive( explainedBound - epsilon ) && bound == 0 ) { constraint.setPhaseStatus( ABS_PHASE_NEGATIVE ); return 0; } - else if ( affectedVar == neg && causingVar == pos && causingVarBound == BoundType::LOWER && FloatUtils::isPositive( explainedBound + epsilon ) && bound == 0 ) + else if ( affectedVar == neg && causingVar == pos && causingVarBound == BoundType::LOWER && + FloatUtils::isPositive( explainedBound + epsilon ) && bound == 0 ) { constraint.setPhaseStatus( ABS_PHASE_NEGATIVE ); return 0; } - else if ( affectedVar == pos && causingVar == neg && causingVarBound == BoundType::LOWER && FloatUtils::isPositive( explainedBound + epsilon ) && bound == 0 ) + else if ( affectedVar == pos && causingVar == neg && causingVarBound == BoundType::LOWER && + FloatUtils::isPositive( explainedBound + epsilon ) && bound == 0 ) { constraint.setPhaseStatus( ABS_PHASE_POSITIVE ); return 0; } - return affectedVarBound == BoundType::UPPER ? FloatUtils::infinity() : FloatUtils::negativeInfinity(); + return affectedVarBound == BoundType::UPPER ? FloatUtils::infinity() + : FloatUtils::negativeInfinity(); } double Checker::checkMaxLemma( const PLCLemma &expl, PiecewiseLinearConstraint &constraint ) { ASSERT( constraint.getType() == MAX && expl.getConstraintType() == MAX ); - MaxConstraint *maxConstraint = ( MaxConstraint * ) &constraint; + MaxConstraint *maxConstraint = (MaxConstraint *)&constraint; double maxBound = maxConstraint->getMaxValueOfEliminatedPhases(); const List causingVars = expl.getCausingVars(); @@ -776,32 +975,42 @@ double Checker::checkMaxLemma( const PLCLemma &expl, PiecewiseLinearConstraint & const List &allExplanations = expl.getExplanations(); BoundType causingVarBound = expl.getCausingVarBound(); BoundType affectedVarBound = expl.getAffectedVarBound(); - double explainedBound = affectedVarBound == BoundType::UPPER ? FloatUtils::infinity() : FloatUtils::negativeInfinity(); + double explainedBound = affectedVarBound == BoundType::UPPER ? FloatUtils::infinity() + : FloatUtils::negativeInfinity(); unsigned f = maxConstraint->getF(); Set constraintElements = maxConstraint->getParticipatingElements(); - for( const auto &var : causingVars ) + for ( const auto &var : causingVars ) if ( !constraintElements.exists( var ) ) return explainedBound; - // Only tightening type is of the form f = element, for some element with the maximal upper bound + // Only tightening type is of the form f = element, for some element with the maximal upper + // bound unsigned counter = 0; Vector causingVarsVec = Vector( 0 ); - for( const auto &var : causingVars ) + for ( const auto &var : causingVars ) causingVarsVec.append( var ); - for( const auto &explanation : allExplanations ) + for ( const auto &explanation : allExplanations ) { - explainedBound = UNSATCertificateUtils::computeBound( causingVarsVec[counter], BoundType::UPPER, explanation, _initialTableau, _groundUpperBounds.data(), _groundLowerBounds.data(), _groundUpperBounds.size() ); + explainedBound = UNSATCertificateUtils::computeBound( causingVarsVec[counter], + BoundType::UPPER, + explanation, + _initialTableau, + _groundUpperBounds.data(), + _groundLowerBounds.data(), + _groundUpperBounds.size() ); maxBound = FloatUtils::max( maxBound, explainedBound ); ++counter; } - if ( causingVarBound == BoundType::UPPER && affectedVar == f && affectedVarBound == BoundType::UPPER ) + if ( causingVarBound == BoundType::UPPER && affectedVar == f && + affectedVarBound == BoundType::UPPER ) return maxBound; - return affectedVarBound == BoundType::UPPER ? FloatUtils::infinity() : FloatUtils::negativeInfinity(); + return affectedVarBound == BoundType::UPPER ? FloatUtils::infinity() + : FloatUtils::negativeInfinity(); } \ No newline at end of file diff --git a/src/proofs/Checker.h b/src/proofs/Checker.h index abfd704593..b3d1bf09ad 100644 --- a/src/proofs/Checker.h +++ b/src/proofs/Checker.h @@ -37,7 +37,8 @@ class Checker /* Checks if the tree is indeed a correct proof of unsatisfiability. - If called from a certificate of a satisfiable query, checks that all proofs for bound propagations and unsatisfiable leaves are correct + If called from a certificate of a satisfiable query, checks that all proofs for bound + propagations and unsatisfiable leaves are correct */ bool check(); @@ -56,7 +57,8 @@ class Checker unsigned _delegationCounter; - // Keeps track of bounds changes, so only stored bounds will be reverted when traversing the tree + // Keeps track of bounds changes, so only stored bounds will be reverted when traversing the + // tree Stack> _upperBoundChanges; Stack> _lowerBoundChanges; @@ -66,24 +68,28 @@ class Checker bool checkNode( const UnsatCertificateNode *node ); /* - Return true iff all changes in the ground bounds are certified, with tolerance to errors with at most size epsilon + Return true iff all changes in the ground bounds are certified, with tolerance to errors with + at most size epsilon */ bool checkAllPLCExplanations( const UnsatCertificateNode *node, double epsilon ); /* Return a change in the ground bounds caused by a ReLU constraint. */ - double checkReluLemma( const PLCLemma &expl, PiecewiseLinearConstraint &constraint, double epsilon ); + double + checkReluLemma( const PLCLemma &expl, PiecewiseLinearConstraint &constraint, double epsilon ); /* Return a change in the ground bounds caused by a Sign constraint. */ - double checkSignLemma( const PLCLemma &expl, PiecewiseLinearConstraint &constraint, double epsilon ); + double + checkSignLemma( const PLCLemma &expl, PiecewiseLinearConstraint &constraint, double epsilon ); /* Return a change in the ground bounds caused by a Absolute Value constraint. */ - double checkAbsLemma( const PLCLemma &expl, PiecewiseLinearConstraint &constraint, double epsilon ); + double + checkAbsLemma( const PLCLemma &expl, PiecewiseLinearConstraint &constraint, double epsilon ); /* Return a change in the ground bounds caused by a Max constraint. @@ -108,32 +114,38 @@ class Checker /* Return a pointer to the problem constraint representing the split */ - PiecewiseLinearConstraint *getCorrespondingConstraint( const List &splits ); + PiecewiseLinearConstraint * + getCorrespondingConstraint( const List &splits ); /* Return a pointer to a ReLU problem constraint representing the split */ - PiecewiseLinearConstraint *getCorrespondingReluConstraint( const List &splits ); + PiecewiseLinearConstraint * + getCorrespondingReluConstraint( const List &splits ); /* Return a pointer to a sign problem constraint representing the split */ - PiecewiseLinearConstraint *getCorrespondingSignConstraint( const List &splits ); + PiecewiseLinearConstraint * + getCorrespondingSignConstraint( const List &splits ); /* Return a pointer to a absolute value problem constraint representing the split */ - PiecewiseLinearConstraint *getCorrespondingAbsConstraint( const List &splits ); + PiecewiseLinearConstraint * + getCorrespondingAbsConstraint( const List &splits ); /* Return a pointer to a max problem constraint representing the split */ - PiecewiseLinearConstraint *getCorrespondingMaxConstraint( const List &splits ); + PiecewiseLinearConstraint * + getCorrespondingMaxConstraint( const List &splits ); /* Return a pointer to a disjunction problem constraint representing the split */ - PiecewiseLinearConstraint *getCorrespondingDisjunctionConstraint( const List &splits ); + PiecewiseLinearConstraint * + getCorrespondingDisjunctionConstraint( const List &splits ); /* Return true iff a list of splits represents a splits over a single variable @@ -143,7 +155,8 @@ class Checker /* Fix phase of the child split */ - void fixChildSplitPhase( UnsatCertificateNode *child, PiecewiseLinearConstraint *childrenSplitConstraint ); + void fixChildSplitPhase( UnsatCertificateNode *child, + PiecewiseLinearConstraint *childrenSplitConstraint ); }; #endif //__Checker_h__ \ No newline at end of file diff --git a/src/proofs/Contradiction.cpp b/src/proofs/Contradiction.cpp index dee6b1f029..edb958861c 100644 --- a/src/proofs/Contradiction.cpp +++ b/src/proofs/Contradiction.cpp @@ -24,7 +24,7 @@ Contradiction::Contradiction( const Vector &contradiction ) Contradiction::Contradiction( unsigned var ) : _var( var ) - , _contradiction( ) + , _contradiction() { } diff --git a/src/proofs/Contradiction.h b/src/proofs/Contradiction.h index 462b059fed..307c83a8d7 100644 --- a/src/proofs/Contradiction.h +++ b/src/proofs/Contradiction.h @@ -19,7 +19,8 @@ #include "Vector.h" /* - Contains all info relevant for a simple Marabou contradiction - i.e. explanations of contradicting bounds of a variable + Contains all info relevant for a simple Marabou contradiction - i.e. explanations of contradicting + bounds of a variable */ class Contradiction { diff --git a/src/proofs/JsonWriter.cpp b/src/proofs/JsonWriter.cpp index d0a37a82a5..a82dadde99 100644 --- a/src/proofs/JsonWriter.cpp +++ b/src/proofs/JsonWriter.cpp @@ -12,9 +12,10 @@ ** [[ Add lengthier description here ]] **/ -#include #include "JsonWriter.h" +#include + const char JsonWriter::AFFECTED_VAR[] = "\"affVar\" : "; const char JsonWriter::AFFECTED_BOUND[] = "\"affBound\" : "; const char JsonWriter::BOUND[] = "\"bound\" : "; @@ -41,16 +42,17 @@ const char JsonWriter::VARIABLE[] = "\"var\" : "; const char JsonWriter::VARIABLES[] = "\"vars\" : "; const bool JsonWriter::PROVE_LEMMAS = true; -const unsigned JsonWriter::JSONWRITER_PRECISION = ( unsigned ) std::log10( 1 / GlobalConfiguration::DEFAULT_EPSILON_FOR_COMPARISONS ); +const unsigned JsonWriter::JSONWRITER_PRECISION = + (unsigned)std::log10( 1 / GlobalConfiguration::DEFAULT_EPSILON_FOR_COMPARISONS ); const char JsonWriter::PROOF_FILENAME[] = "proof.json"; -void JsonWriter::writeProofToJson( const UnsatCertificateNode *root, - unsigned explanationSize, - const SparseMatrix *initialTableau, - const Vector &upperBounds, - const Vector &lowerBounds, - const List &problemConstraints, - IFile &file ) +void JsonWriter::writeProofToJson( const UnsatCertificateNode *root, + unsigned explanationSize, + const SparseMatrix *initialTableau, + const Vector &upperBounds, + const Vector &lowerBounds, + const List &problemConstraints, + IFile &file ) { ASSERT( root ); ASSERT( upperBounds.size() > 0 ); @@ -77,7 +79,9 @@ void JsonWriter::writeProofToJson( const UnsatCertificateNode *root, writeInstanceToFile( file, jsonLines ); } -void JsonWriter::writeBounds( const Vector &bounds, BoundType isUpper, List &instance ) +void JsonWriter::writeBounds( const Vector &bounds, + BoundType isUpper, + List &instance ) { String boundsString = isUpper == UPPER ? UPPER_BOUNDS : LOWER_BOUNDS; @@ -87,7 +91,9 @@ void JsonWriter::writeBounds( const Vector &bounds, BoundType isUpper, L instance.append( String( ",\n" ) ); } -void JsonWriter::writeInitialTableau( const SparseMatrix *initialTableau, unsigned explanationSize, List &instance ) +void JsonWriter::writeInitialTableau( const SparseMatrix *initialTableau, + unsigned explanationSize, + List &instance ) { instance.append( String( TABLEAU ) ); instance.append( "[\n" ); @@ -108,10 +114,12 @@ void JsonWriter::writeInitialTableau( const SparseMatrix *initialTableau, unsign instance.append( "]\n" ); } - instance.append ( "], \n" ); + instance.append( "], \n" ); } -void JsonWriter::writePiecewiseLinearConstraints( const List &problemConstraints, List &instance ) +void JsonWriter::writePiecewiseLinearConstraints( + const List &problemConstraints, + List &instance ) { instance.append( CONSTRAINTS ); instance.append( "[\n" ); @@ -132,17 +140,18 @@ void JsonWriter::writePiecewiseLinearConstraints( const List &instance ) +void JsonWriter::writeUnsatCertificateNode( const UnsatCertificateNode *node, + unsigned explanationSize, + List &instance ) { // For SAT examples only (used for debugging) if ( !node->getVisited() || node->getSATSolutionFlag() ) @@ -172,14 +183,14 @@ void JsonWriter::writeUnsatCertificateNode( const UnsatCertificateNode *node, un unsigned size = node->getChildren().size(); for ( auto child : node->getChildren() ) { - instance.append("{\n" ); + instance.append( "{\n" ); writeUnsatCertificateNode( child, explanationSize, instance ); // Not adding a comma after the last element - if (counter != size - 1) - instance.append("},\n" ); + if ( counter != size - 1 ) + instance.append( "},\n" ); else - instance.append("}\n" ); + instance.append( "}\n" ); ++counter; } @@ -200,13 +211,15 @@ void JsonWriter::writeHeadSplit( const PiecewiseLinearCaseSplit &headSplit, List instance.append( "[" ); for ( auto tightening : headSplit.getBoundTightenings() ) { - instance.append( String ( "{" ) + String( VARIABLE ) + std::to_string( tightening._variable ) + String(", " ) + \ - String ( VALUE ) + convertDoubleToString( tightening._value ) + String(", " ) + \ - String ( BOUND ) ); - boundTypeString = tightening._type == Tightening::UB ? String ( UPPER_BOUND ) : String ( LOWER_BOUND ); + instance.append( String( "{" ) + String( VARIABLE ) + + std::to_string( tightening._variable ) + String( ", " ) + String( VALUE ) + + convertDoubleToString( tightening._value ) + String( ", " ) + + String( BOUND ) ); + boundTypeString = + tightening._type == Tightening::UB ? String( UPPER_BOUND ) : String( LOWER_BOUND ); boundTypeString += String( "}" ); // Not adding a comma after the last element - if ( counter != size - 1 ) + if ( counter != size - 1 ) boundTypeString += ", "; instance.append( boundTypeString ); ++counter; @@ -219,12 +232,14 @@ void JsonWriter::writeContradiction( const Contradiction *contradiction, ListgetContradiction(); contradictionString += "[ "; - contradictionString += explanation.empty() ? std::to_string( contradiction->getVar() ) : convertSparseUnsortedListToString( explanation ); + contradictionString += explanation.empty() ? std::to_string( contradiction->getVar() ) + : convertSparseUnsortedListToString( explanation ); contradictionString += String( " ]\n" ); instance.append( contradictionString ); } -void JsonWriter::writePLCLemmas( const List> &PLCExplanations, List &instance ) +void JsonWriter::writePLCLemmas( const List> &PLCExplanations, + List &instance ) { unsigned counter = 0; unsigned size = PLCExplanations.size(); @@ -240,9 +255,11 @@ void JsonWriter::writePLCLemmas( const List> &PLCExpla for ( auto lemma : PLCExplanations ) { instance.append( String( "{" ) ); - instance.append( String( AFFECTED_VAR) + std::to_string( lemma->getAffectedVar() ) + String( ", " ) ); - affectedBoundType = lemma->getAffectedVarBound() == UPPER ? String ( UPPER_BOUND ) : String ( LOWER_BOUND ); - instance.append( String( AFFECTED_BOUND ) + affectedBoundType + String( ", " ) ); + instance.append( String( AFFECTED_VAR ) + std::to_string( lemma->getAffectedVar() ) + + String( ", " ) ); + affectedBoundType = + lemma->getAffectedVarBound() == UPPER ? String( UPPER_BOUND ) : String( LOWER_BOUND ); + instance.append( String( AFFECTED_BOUND ) + affectedBoundType + String( ", " ) ); instance.append( String( BOUND ) + convertDoubleToString( lemma->getBound() ) ); if ( PROVE_LEMMAS ) @@ -251,35 +268,39 @@ void JsonWriter::writePLCLemmas( const List> &PLCExpla List causingVars = lemma->getCausingVars(); if ( causingVars.size() == 1 ) - instance.append( String( CAUSING_VAR ) + std::to_string( causingVars.front() ) + String( ", " ) ); + instance.append( String( CAUSING_VAR ) + std::to_string( causingVars.front() ) + + String( ", " ) ); else { - instance.append( String( CAUSING_VARS ) + "[ "); + instance.append( String( CAUSING_VARS ) + "[ " ); for ( unsigned var : causingVars ) { instance.append( std::to_string( var ) ); if ( var != causingVars.back() ) instance.append( ", " ); } - instance.append( " ]\n"); + instance.append( " ]\n" ); } - causingBoundType = lemma->getCausingVarBound() == UPPER ? String( UPPER_BOUND ) : String( LOWER_BOUND ); + causingBoundType = lemma->getCausingVarBound() == UPPER ? String( UPPER_BOUND ) + : String( LOWER_BOUND ); instance.append( String( CAUSING_BOUND ) + causingBoundType + String( ", " ) ); - instance.append( String( CONSTRAINT ) + std::to_string( lemma->getConstraintType() ) + String( ",\n" ) ); + instance.append( String( CONSTRAINT ) + std::to_string( lemma->getConstraintType() ) + + String( ",\n" ) ); List expls = lemma->getExplanations(); if ( expls.size() == 1 ) - instance.append( String( EXPLANATION ) + "[ " + convertSparseUnsortedListToString( expls.front() ) + " ]"); + instance.append( String( EXPLANATION ) + "[ " + + convertSparseUnsortedListToString( expls.front() ) + " ]" ); else { - instance.append( String( EXPLANATIONS ) + "[ "); + instance.append( String( EXPLANATIONS ) + "[ " ); unsigned innerCounter = 0; for ( SparseUnsortedList &expl : expls ) { - instance.append( "[ "); + instance.append( "[ " ); instance.append( convertSparseUnsortedListToString( expl ) ); - instance.append( " ]"); + instance.append( " ]" ); if ( innerCounter != expls.size() - 1 ) instance.append( ",\n" ); @@ -314,7 +335,7 @@ String JsonWriter::convertDoubleToString( double value ) { std::stringstream s; s << std::fixed << std::setprecision( JSONWRITER_PRECISION ) << value; - String str = String ( s.str() ).trimZerosFromRight(); + String str = String( s.str() ).trimZerosFromRight(); // Add .0 for integers for some JSON parsers. if ( !str.contains( "." ) ) @@ -328,7 +349,7 @@ String JsonWriter::convertDoubleArrayToString( const double *arr, unsigned size for ( unsigned i = 0; i < size - 1; ++i ) arrString += convertDoubleToString( arr[i] ) + ", "; - arrString += convertDoubleToString( arr[size -1] ) + "]"; + arrString += convertDoubleToString( arr[size - 1] ) + "]"; return arrString; } @@ -338,14 +359,15 @@ String JsonWriter::convertSparseUnsortedListToString( SparseUnsortedList sparseL String sparseListString = ""; unsigned counter = 0; unsigned size = sparseList.getNnz(); - for ( auto entry = sparseList.begin() ; entry != sparseList.end(); ++entry ) + for ( auto entry = sparseList.begin(); entry != sparseList.end(); ++entry ) { - sparseListString += String( "{" ) + String( VARIABLE ) + std::to_string( entry->_index ) + String(", " ) + - String( VALUE ) + convertDoubleToString( entry->_value ) + String ( "}" ); + sparseListString += String( "{" ) + String( VARIABLE ) + std::to_string( entry->_index ) + + String( ", " ) + String( VALUE ) + + convertDoubleToString( entry->_value ) + String( "}" ); // Not adding a comma after the last element if ( counter != size - 1 ) - sparseListString += ", " ; + sparseListString += ", "; ++counter; } return sparseListString; diff --git a/src/proofs/JsonWriter.h b/src/proofs/JsonWriter.h index b93083ad6d..cff6bc4cbe 100644 --- a/src/proofs/JsonWriter.h +++ b/src/proofs/JsonWriter.h @@ -23,8 +23,8 @@ #include "PlcLemma.h" #include "SparseUnsortedList.h" #include "Tightening.h" -#include "Vector.h" #include "UnsatCertificateNode.h" +#include "Vector.h" /* A class responsible for writing Marabou proof instances into JSON format @@ -34,15 +34,16 @@ class JsonWriter public: /* Write an entire UNSAT proof to a JSON file. - General remark - empty JSON properties (such as empty contradiction for non-leaves) will not be written. + General remark - empty JSON properties (such as empty contradiction for non-leaves) will not + be written. */ - static void writeProofToJson( const UnsatCertificateNode *root, - unsigned explanationSize, - const SparseMatrix *initialTableau, - const Vector &upperBounds, - const Vector &lowerBounds, - const List &problemConstraints, - IFile &file ); + static void writeProofToJson( const UnsatCertificateNode *root, + unsigned explanationSize, + const SparseMatrix *initialTableau, + const Vector &upperBounds, + const Vector &lowerBounds, + const List &problemConstraints, + IFile &file ); /* Configure whether lemmas should be written proved as well */ @@ -90,27 +91,35 @@ class JsonWriter /* Write the initial tableau to a JSON list of Strings */ - static void writeInitialTableau( const SparseMatrix *initialTableau, unsigned explanationSize, List &instance ); + static void writeInitialTableau( const SparseMatrix *initialTableau, + unsigned explanationSize, + List &instance ); /* Write variables bounds to a JSON String */ - static void writeBounds( const Vector &bounds, BoundType isUpper, List &instance ); + static void + writeBounds( const Vector &bounds, BoundType isUpper, List &instance ); /* Write a list a piecewise-linear constraints to a JSON String */ - static void writePiecewiseLinearConstraints( const List &problemConstraints, List &instance ); + static void + writePiecewiseLinearConstraints( const List &problemConstraints, + List &instance ); /* Write an UNSAT certificate node to a JSON String */ - static void writeUnsatCertificateNode( const UnsatCertificateNode *node, unsigned explanationSize, List &instance ); + static void writeUnsatCertificateNode( const UnsatCertificateNode *node, + unsigned explanationSize, + List &instance ); /* Write a list of PLCLemmas to a JSON String */ - static void writePLCLemmas( const List> &PLCLemma, List &instance ); + static void writePLCLemmas( const List> &PLCLemma, + List &instance ); /* Write a contradiction object to a JSON String diff --git a/src/proofs/PlcLemma.cpp b/src/proofs/PlcLemma.cpp index 66b6102df4..57e04e4672 100644 --- a/src/proofs/PlcLemma.cpp +++ b/src/proofs/PlcLemma.cpp @@ -32,7 +32,7 @@ PLCLemma::PLCLemma( const List &causingVars, _explanations = List(); else { - ASSERT( causingVars.size() == explanations.size() ); + ASSERT( causingVars.size() == explanations.size() ); unsigned numOfExplanations = explanations.size(); @@ -58,7 +58,7 @@ PLCLemma::PLCLemma( const List &causingVars, PLCLemma::~PLCLemma() { if ( !_explanations.empty() ) - for ( auto &expl : _explanations ) + for ( auto &expl : _explanations ) expl.clear(); } diff --git a/src/proofs/SmtLibWriter.cpp b/src/proofs/SmtLibWriter.cpp index 2a40786fe2..f4ef0db1b2 100644 --- a/src/proofs/SmtLibWriter.cpp +++ b/src/proofs/SmtLibWriter.cpp @@ -12,10 +12,12 @@ ** [[ Add lengthier description here ]] **/ -#include #include "SmtLibWriter.h" -const unsigned SmtLibWriter::SMTLIBWRITER_PRECISION = ( unsigned ) std::log10( 1 / GlobalConfiguration::DEFAULT_EPSILON_FOR_COMPARISONS ); +#include + +const unsigned SmtLibWriter::SMTLIBWRITER_PRECISION = + (unsigned)std::log10( 1 / GlobalConfiguration::DEFAULT_EPSILON_FOR_COMPARISONS ); void SmtLibWriter::addHeader( unsigned numberOfVariables, List &instance ) { @@ -26,57 +28,80 @@ void SmtLibWriter::addHeader( unsigned numberOfVariables, List &instance void SmtLibWriter::addFooter( List &instance ) { - instance.append( "( check-sat )\n" ); - instance.append( "( exit )\n" ); + instance.append( "( check-sat )\n" ); + instance.append( "( exit )\n" ); } -void SmtLibWriter::addReLUConstraint( unsigned b, unsigned f, const PhaseStatus status, List &instance ) +void SmtLibWriter::addReLUConstraint( unsigned b, + unsigned f, + const PhaseStatus status, + List &instance ) { if ( status == PHASE_NOT_FIXED ) - instance.append( "( assert ( = x" + std::to_string( f ) + " ( ite ( >= x" + std::to_string( b ) + " 0 ) x" + std::to_string( b ) + " 0 ) ) )\n" ); + instance.append( "( assert ( = x" + std::to_string( f ) + " ( ite ( >= x" + + std::to_string( b ) + " 0 ) x" + std::to_string( b ) + " 0 ) ) )\n" ); else if ( status == RELU_PHASE_ACTIVE ) - instance.append( "( assert ( = x" + std::to_string( f ) + " x" + std::to_string( b ) + " ) )\n" ); + instance.append( "( assert ( = x" + std::to_string( f ) + " x" + std::to_string( b ) + + " ) )\n" ); else if ( status == RELU_PHASE_INACTIVE ) - instance.append( "( assert ( = x" + std::to_string( f ) + " 0 ) )\n" ); + instance.append( "( assert ( = x" + std::to_string( f ) + " 0 ) )\n" ); } -void SmtLibWriter::addSignConstraint( unsigned b, unsigned f, const PhaseStatus status, List &instance ) +void SmtLibWriter::addSignConstraint( unsigned b, + unsigned f, + const PhaseStatus status, + List &instance ) { if ( status == PHASE_NOT_FIXED ) - instance.append( "( assert ( = x" + std::to_string( f ) + " ( ite ( >= x" + std::to_string( b ) + " 0 ) 1 ( - 1 ) ) ) )\n" ); + instance.append( "( assert ( = x" + std::to_string( f ) + " ( ite ( >= x" + + std::to_string( b ) + " 0 ) 1 ( - 1 ) ) ) )\n" ); else if ( status == SIGN_PHASE_POSITIVE ) - instance.append( "( assert ( = x" + std::to_string( f ) + " 1 ) )\n" ); + instance.append( "( assert ( = x" + std::to_string( f ) + " 1 ) )\n" ); else if ( status == SIGN_PHASE_NEGATIVE ) - instance.append( "( assert ( = x" + std::to_string( f ) + " ( - 1 ) ) )\n" ); + instance.append( "( assert ( = x" + std::to_string( f ) + " ( - 1 ) ) )\n" ); } -void SmtLibWriter::addAbsConstraint( unsigned b, unsigned f, const PhaseStatus status, List &instance ) +void SmtLibWriter::addAbsConstraint( unsigned b, + unsigned f, + const PhaseStatus status, + List &instance ) { if ( status == PHASE_NOT_FIXED ) - instance.append( "( assert ( = x" + std::to_string( f ) + " ( ite ( >= x" + std::to_string( b ) + " 0 ) x" + std::to_string( b ) + " ( - x" + std::to_string( b ) + " ) ) ) )\n" ); + instance.append( "( assert ( = x" + std::to_string( f ) + " ( ite ( >= x" + + std::to_string( b ) + " 0 ) x" + std::to_string( b ) + " ( - x" + + std::to_string( b ) + " ) ) ) )\n" ); else if ( status == ABS_PHASE_POSITIVE ) - instance.append( "( assert ( = x" + std::to_string( f ) + " x" + std::to_string( b ) + " ) )\n" ); + instance.append( "( assert ( = x" + std::to_string( f ) + " x" + std::to_string( b ) + + " ) )\n" ); else if ( status == ABS_PHASE_NEGATIVE ) - instance.append( "( assert ( = x" + std::to_string( f ) + " ( - x" + std::to_string( b ) + " ) ) )\n" ); + instance.append( "( assert ( = x" + std::to_string( f ) + " ( - x" + std::to_string( b ) + + " ) ) )\n" ); } -void SmtLibWriter::addMaxConstraint( unsigned f, const Set &elements, const PhaseStatus status, double maxVal ,List &instance ) +void SmtLibWriter::addMaxConstraint( unsigned f, + const Set &elements, + const PhaseStatus status, + double maxVal, + List &instance ) { String assertRowLine; unsigned counter; unsigned size = elements.size(); // f equals to some value (the value of maxVal) - if ( status == MAX_PHASE_ELIMINATED ) - instance.append( String ( "( assert ( = x" + std::to_string( f ) + " " ) + signedValue( maxVal ) + " ) )\n" ); + if ( status == MAX_PHASE_ELIMINATED ) + instance.append( String( "( assert ( = x" + std::to_string( f ) + " " ) + + signedValue( maxVal ) + " ) )\n" ); // f equals to some element (maxVal is an index) else if ( status != PHASE_NOT_FIXED ) - instance.append( "( assert ( = x" + std::to_string( f ) + " x" + std::to_string( ( unsigned ) maxVal ) + " ) )\n" ); + instance.append( "( assert ( = x" + std::to_string( f ) + " x" + + std::to_string( (unsigned)maxVal ) + " ) )\n" ); else { - // For all elements (including eliminated), if an element is larger than all others, then f = element + // For all elements (including eliminated), if an element is larger than all others, then f + // = element for ( const auto &element : elements ) { counter = 0; @@ -92,30 +117,33 @@ void SmtLibWriter::addMaxConstraint( unsigned f, const Set &elements, ++counter; } - assertRowLine += " ( >= x" + std::to_string( element ) + " x" + std::to_string( otherElement ) + " )"; + assertRowLine += " ( >= x" + std::to_string( element ) + " x" + + std::to_string( otherElement ) + " )"; } - for ( unsigned i = 0; i < size - 2 ; ++i ) + for ( unsigned i = 0; i < size - 2; ++i ) assertRowLine += String( " )" ); - assertRowLine += " ( = x" + std::to_string( f ) + " x" + std::to_string( element ) + " )"; + assertRowLine += + " ( = x" + std::to_string( f ) + " x" + std::to_string( element ) + " )"; instance.append( assertRowLine + " ) )\n" ); } } } -void SmtLibWriter::addDisjunctionConstraint( const List &disjuncts, List &instance ) +void SmtLibWriter::addDisjunctionConstraint( const List &disjuncts, + List &instance ) { ASSERT( !disjuncts.empty() ); unsigned size; - instance.append( "( assert\n"); + instance.append( "( assert\n" ); for ( const auto &disjunct : disjuncts ) { if ( !( disjunct == disjuncts.back() ) ) - instance.append("( or\n"); + instance.append( "( or\n" ); size = disjunct.getEquations().size() + disjunct.getBoundTightenings().size(); ASSERT( size ) @@ -132,7 +160,7 @@ void SmtLibWriter::addDisjunctionConstraint( const List &instance ) { @@ -188,15 +215,16 @@ void SmtLibWriter::addTableauRow( const SparseUnsortedList &row, List &i // Coefficients +-1 can be dropped if ( entry->_value == 1 ) assertRowLine += String( "x" ) + std::to_string( entry->_index ); - else if (entry->_value == -1 ) + else if ( entry->_value == -1 ) assertRowLine += String( "( - x" ) + std::to_string( entry->_index ) + " )"; else - assertRowLine += String( "( * " ) + signedValue( entry->_value ) + " x" + std::to_string( entry->_index ) + " )"; + assertRowLine += String( "( * " ) + signedValue( entry->_value ) + " x" + + std::to_string( entry->_index ) + " )"; ++counter; } - for ( unsigned i = 0; i < counter + 1 ; ++i ) + for ( unsigned i = 0; i < counter + 1; ++i ) assertRowLine += String( " )" ); instance.append( assertRowLine + "\n" ); @@ -206,14 +234,16 @@ void SmtLibWriter::addGroundUpperBounds( Vector &bounds, List &i { unsigned n = bounds.size(); for ( unsigned i = 0; i < n; ++i ) - instance.append( String( "( assert ( <= x" + std::to_string( i ) ) + String( " " ) + signedValue( bounds[i] ) + " ) )\n" ); + instance.append( String( "( assert ( <= x" + std::to_string( i ) ) + String( " " ) + + signedValue( bounds[i] ) + " ) )\n" ); } void SmtLibWriter::addGroundLowerBounds( Vector &bounds, List &instance ) { unsigned n = bounds.size(); for ( unsigned i = 0; i < n; ++i ) - instance.append( String( "( assert ( >= x" + std::to_string( i ) ) + String( " " ) + signedValue( bounds[i] ) + " ) )\n" ); + instance.append( String( "( assert ( >= x" + std::to_string( i ) ) + String( " " ) + + signedValue( bounds[i] ) + " ) )\n" ); } void SmtLibWriter::writeInstanceToFile( IFile &file, const List &instance ) @@ -230,7 +260,8 @@ String SmtLibWriter::signedValue( double val ) { std::stringstream s; s << std::fixed << std::setprecision( SMTLIBWRITER_PRECISION ) << abs( val ); - return val >= 0 ? String( s.str() ).trimZerosFromRight() : String( "( - " + s.str() ).trimZerosFromRight() + " )"; + return val >= 0 ? String( s.str() ).trimZerosFromRight() + : String( "( - " + s.str() ).trimZerosFromRight() + " )"; } void SmtLibWriter::addEquation( const Equation &eq, List &instance ) @@ -253,11 +284,11 @@ void SmtLibWriter::addEquation( const Equation &eq, List &instance ) // Scalar should be <= than sum of addends assertRowLine += "( <= "; - assertRowLine += signedValue( eq._scalar ); + assertRowLine += signedValue( eq._scalar ); for ( const auto &addend : eq._addends ) { - if ( FloatUtils::isZero( addend._coefficient ) ) + if ( FloatUtils::isZero( addend._coefficient ) ) continue; if ( !( addend == eq._addends.back() ) ) @@ -269,24 +300,27 @@ void SmtLibWriter::addEquation( const Equation &eq, List &instance ) // Coefficients +-1 can be dropped if ( addend._coefficient == 1 ) assertRowLine += String( "x" ) + std::to_string( addend._variable ); - else if (addend._coefficient == -1 ) + else if ( addend._coefficient == -1 ) assertRowLine += String( "( - x" ) + std::to_string( addend._variable ) + " )"; else - assertRowLine += String( "( * " ) + signedValue( addend._coefficient ) + " x" + std::to_string( addend._variable ) + " )"; + assertRowLine += String( "( * " ) + signedValue( addend._coefficient ) + " x" + + std::to_string( addend._variable ) + " )"; ++counter; } - for ( unsigned i = 0; i < counter ; ++i ) + for ( unsigned i = 0; i < counter; ++i ) assertRowLine += String( " )" ); - instance.append( assertRowLine + " "); + instance.append( assertRowLine + " " ); } void SmtLibWriter::addTightening( Tightening bound, List &instance ) { if ( bound._type == Tightening::LB ) - instance.append( String( "( >= x" ) + std::to_string( bound._variable ) + " " + signedValue( bound._value ) + " )" ); + instance.append( String( "( >= x" ) + std::to_string( bound._variable ) + " " + + signedValue( bound._value ) + " )" ); else - instance.append( String( "( <= x" + std::to_string( bound._variable ) ) + String( " " ) + signedValue( bound._value ) + " )" ); + instance.append( String( "( <= x" + std::to_string( bound._variable ) ) + String( " " ) + + signedValue( bound._value ) + " )" ); } \ No newline at end of file diff --git a/src/proofs/SmtLibWriter.h b/src/proofs/SmtLibWriter.h index cb37bf559e..7bb0a564bf 100644 --- a/src/proofs/SmtLibWriter.h +++ b/src/proofs/SmtLibWriter.h @@ -23,8 +23,8 @@ #include "Vector.h" /* -* A class responsible for writing instances of LP+PLC into SMTLIB format -*/ + * A class responsible for writing instances of LP+PLC into SMTLIB format + */ class SmtLibWriter { public: @@ -46,27 +46,35 @@ class SmtLibWriter /* Adds a line representing a ReLU constraint, in SMTLIB format, to the SMTLIB instance */ - static void addReLUConstraint( unsigned b, unsigned f, const PhaseStatus status, List &instance ); + static void + addReLUConstraint( unsigned b, unsigned f, const PhaseStatus status, List &instance ); /* Adds a line representing a sign constraint, in SMTLIB format, to the SMTLIB instance */ - static void addSignConstraint( unsigned b, unsigned f, const PhaseStatus status, List &instance ); + static void + addSignConstraint( unsigned b, unsigned f, const PhaseStatus status, List &instance ); /* Adds a line representing an absolute value constraint, in SMTLIB format, to the SMTLIB instance */ - static void addAbsConstraint( unsigned b, unsigned f, const PhaseStatus status, List &instance ); + static void + addAbsConstraint( unsigned b, unsigned f, const PhaseStatus status, List &instance ); /* Adds a line representing a max constraint, in SMTLIB format, to the SMTLIB instance */ - static void addMaxConstraint( unsigned f, const Set &elements, const PhaseStatus status, double maxVal, List &instance ); + static void addMaxConstraint( unsigned f, + const Set &elements, + const PhaseStatus status, + double maxVal, + List &instance ); /* Adds a line representing a disjunction constraint, in SMTLIB format, to the SMTLIB instance */ - static void addDisjunctionConstraint( const List &disjuncts, List &instance ); + static void addDisjunctionConstraint( const List &disjuncts, + List &instance ); /* Adds a line representing a Tableau Row, in SMTLIB format, to the SMTLIB instance diff --git a/src/proofs/UnsatCertificateNode.cpp b/src/proofs/UnsatCertificateNode.cpp index 9f47a7524e..2d1c094509 100644 --- a/src/proofs/UnsatCertificateNode.cpp +++ b/src/proofs/UnsatCertificateNode.cpp @@ -12,10 +12,12 @@ ** [[ Add lengthier description here ]] **/ -#include #include "UnsatCertificateNode.h" -UnsatCertificateNode::UnsatCertificateNode( UnsatCertificateNode *parent, PiecewiseLinearCaseSplit split ) +#include + +UnsatCertificateNode::UnsatCertificateNode( UnsatCertificateNode *parent, + PiecewiseLinearCaseSplit split ) : _parent( parent ) , _contradiction( NULL ) , _headSplit( std::move( split ) ) @@ -70,7 +72,7 @@ const PiecewiseLinearCaseSplit &UnsatCertificateNode::getSplit() const return _headSplit; } -const List &UnsatCertificateNode::getChildren() const +const List &UnsatCertificateNode::getChildren() const { return _children; } @@ -86,7 +88,8 @@ void UnsatCertificateNode::addPLCLemma( std::shared_ptr &explanation ) } -UnsatCertificateNode *UnsatCertificateNode::getChildBySplit( const PiecewiseLinearCaseSplit &split ) const +UnsatCertificateNode * +UnsatCertificateNode::getChildBySplit( const PiecewiseLinearCaseSplit &split ) const { for ( UnsatCertificateNode *child : _children ) { diff --git a/src/proofs/UnsatCertificateNode.h b/src/proofs/UnsatCertificateNode.h index aad65c81a2..42d5048086 100644 --- a/src/proofs/UnsatCertificateNode.h +++ b/src/proofs/UnsatCertificateNode.h @@ -23,8 +23,7 @@ #include "SmtLibWriter.h" #include "UnsatCertificateUtils.h" -enum DelegationStatus : unsigned -{ +enum DelegationStatus : unsigned { DONT_DELEGATE = 0, DELEGATE_DONT_SAVE = 1, DELEGATE_SAVE = 2 @@ -62,7 +61,7 @@ class UnsatCertificateNode /* Returns the head split of a node */ - const List &getChildren() const; + const List &getChildren() const; /* Returns the list of PLC lemmas of the node @@ -130,7 +129,7 @@ class UnsatCertificateNode bool isValidNonLeaf() const; private: - List _children; + List _children; UnsatCertificateNode *_parent; List> _PLCExplanations; Contradiction *_contradiction; diff --git a/src/proofs/UnsatCertificateUtils.cpp b/src/proofs/UnsatCertificateUtils.cpp index 6b43469afe..f82dfe8377 100644 --- a/src/proofs/UnsatCertificateUtils.cpp +++ b/src/proofs/UnsatCertificateUtils.cpp @@ -44,7 +44,8 @@ double UNSATCertificateUtils::computeBound( unsigned var, Vector explanationRowCombination( numberOfVariables, 0 ); // Create linear combination of original rows implied from explanation - UNSATCertificateUtils::getExplanationRowCombination( var, explanation, explanationRowCombination, initialTableau, numberOfVariables ); + UNSATCertificateUtils::getExplanationRowCombination( + var, explanation, explanationRowCombination, initialTableau, numberOfVariables ); // Set the bound derived from the linear combination, using original bounds. for ( unsigned i = 0; i < numberOfVariables; ++i ) @@ -53,9 +54,13 @@ double UNSATCertificateUtils::computeBound( unsigned var, if ( !FloatUtils::isZero( temp ) ) { if ( isUpper ) - temp *= FloatUtils::isPositive( explanationRowCombination[i] ) ? groundUpperBounds[i] : groundLowerBounds[i]; + temp *= FloatUtils::isPositive( explanationRowCombination[i] ) + ? groundUpperBounds[i] + : groundLowerBounds[i]; else - temp *= FloatUtils::isPositive( explanationRowCombination[i] ) ? groundLowerBounds[i] : groundUpperBounds[i]; + temp *= FloatUtils::isPositive( explanationRowCombination[i] ) + ? groundLowerBounds[i] + : groundUpperBounds[i]; if ( !FloatUtils::isZero( temp ) ) derivedBound += temp; @@ -74,18 +79,19 @@ void UNSATCertificateUtils::getExplanationRowCombination( unsigned var, ASSERT( !explanation.empty() ); SparseUnsortedList tableauRow( numberOfVariables ); - explanationRowCombination = Vector ( numberOfVariables, 0 ); + explanationRowCombination = Vector( numberOfVariables, 0 ); for ( const auto &entry : explanation ) { - if ( FloatUtils::isZero( entry._value ) ) - continue; + if ( FloatUtils::isZero( entry._value ) ) + continue; initialTableau->getRow( entry._index, &tableauRow ); for ( const auto &tableauEntry : tableauRow ) { if ( !FloatUtils::isZero( tableauEntry._value ) ) - explanationRowCombination[tableauEntry._index] += entry._value * tableauEntry._value; + explanationRowCombination[tableauEntry._index] += + entry._value * tableauEntry._value; } } @@ -120,7 +126,8 @@ double UNSATCertificateUtils::computeCombinationUpperBound( const SparseUnsorted for ( const auto &tableauEntry : tableauRow ) { if ( !FloatUtils::isZero( tableauEntry._value ) ) - explanationRowCombination[tableauEntry._index] += tableauEntry._value * entry._value; + explanationRowCombination[tableauEntry._index] += + tableauEntry._value * entry._value; } } @@ -133,7 +140,8 @@ double UNSATCertificateUtils::computeCombinationUpperBound( const SparseUnsorted temp = explanationRowCombination[i]; if ( !FloatUtils::isZero( temp ) ) { - temp *= FloatUtils::isPositive( explanationRowCombination[i] ) ? groundUpperBounds[i] : groundLowerBounds[i]; + temp *= FloatUtils::isPositive( explanationRowCombination[i] ) ? groundUpperBounds[i] + : groundLowerBounds[i]; if ( !FloatUtils::isZero( temp ) ) derivedBound += temp; @@ -147,4 +155,3 @@ const Set UNSATCertificateUtils::getSupportedActiva { return { RELU, SIGN, ABSOLUTE_VALUE, MAX, DISJUNCTION }; } - diff --git a/src/proofs/UnsatCertificateUtils.h b/src/proofs/UnsatCertificateUtils.h index f016df3a20..c599758c7c 100644 --- a/src/proofs/UnsatCertificateUtils.h +++ b/src/proofs/UnsatCertificateUtils.h @@ -37,7 +37,8 @@ class UNSATCertificateUtils unsigned numberOfVariables ); /* - Given a var, a tableau and a column vector, create a linear combination used to explain a bound + Given a var, a tableau and a column vector, create a linear combination used to explain a + bound */ static void getExplanationRowCombination( unsigned var, const SparseUnsortedList &explanation, diff --git a/src/proofs/tests/Test_BoundExplainer.h b/src/proofs/tests/Test_BoundExplainer.h index 705ed43ca5..ca5c16c434 100644 --- a/src/proofs/tests/Test_BoundExplainer.h +++ b/src/proofs/tests/Test_BoundExplainer.h @@ -16,6 +16,7 @@ #include "context/cdlist.h" #include "context/cdo.h" #include "context/context.h" + #include using CVC4::context::Context; @@ -65,7 +66,8 @@ class BoundsExplainerTestSuite : public CxxTest::TestSuite double value = -2.55; BoundExplainer be( numberOfVariables, numberOfRows, *context ); - TS_ASSERT_THROWS_NOTHING( be.setExplanation( Vector( numberOfVariables, value ), 0, true ) ); + TS_ASSERT_THROWS_NOTHING( + be.setExplanation( Vector( numberOfVariables, value ), 0, true ) ); auto explanation = be.getExplanation( 0, true ); for ( const auto &entry : explanation ) @@ -75,7 +77,8 @@ class BoundsExplainerTestSuite : public CxxTest::TestSuite } /* - Test addition of an explanation of the new variable, and correct updates of all previous explanations + Test addition of an explanation of the new variable, and correct updates of all previous + explanations */ void test_variable_addition() { @@ -83,22 +86,26 @@ class BoundsExplainerTestSuite : public CxxTest::TestSuite unsigned numberOfRows = 2; BoundExplainer be( numberOfVariables, numberOfRows, *context ); - TS_ASSERT_THROWS_NOTHING( be.setExplanation( Vector( numberOfVariables, 1 ), numberOfVariables - 1, true ) ); - TS_ASSERT_THROWS_NOTHING( be.setExplanation( Vector( numberOfVariables, 5 ), numberOfVariables - 1, false ) ); + TS_ASSERT_THROWS_NOTHING( be.setExplanation( + Vector( numberOfVariables, 1 ), numberOfVariables - 1, true ) ); + TS_ASSERT_THROWS_NOTHING( be.setExplanation( + Vector( numberOfVariables, 5 ), numberOfVariables - 1, false ) ); be.addVariable(); TS_ASSERT_EQUALS( be.getNumberOfRows(), numberOfRows + 1 ); TS_ASSERT_EQUALS( be.getNumberOfVariables(), numberOfVariables + 1 ); - for ( unsigned i = 0; i < numberOfVariables; ++ i ) + for ( unsigned i = 0; i < numberOfVariables; ++i ) { // the sizes of explanations should not change - TS_ASSERT( be.isExplanationTrivial( i, true ) || be.getExplanation( i, true ).getSize() == numberOfVariables ); - TS_ASSERT( be.isExplanationTrivial( i, false ) || be.getExplanation( i, false ).getSize() == numberOfVariables ); + TS_ASSERT( be.isExplanationTrivial( i, true ) || + be.getExplanation( i, true ).getSize() == numberOfVariables ); + TS_ASSERT( be.isExplanationTrivial( i, false ) || + be.getExplanation( i, false ).getSize() == numberOfVariables ); } TS_ASSERT( be.isExplanationTrivial( numberOfVariables, true ) ); - TS_ASSERT( be.isExplanationTrivial( numberOfVariables, false ) ) ; + TS_ASSERT( be.isExplanationTrivial( numberOfVariables, false ) ); } /* @@ -125,9 +132,9 @@ class BoundsExplainerTestSuite : public CxxTest::TestSuite unsigned numberOfVariables = 6; unsigned numberOfRows = 3; BoundExplainer be( numberOfVariables, numberOfRows, *context ); - Vector row1 { 1, 0, 0 }; - Vector row2 { 0, -1, 0 }; - Vector row3 { 0, 0, 2.5 }; + Vector row1{ 1, 0, 0 }; + Vector row2{ 0, -1, 0 }; + Vector row3{ 0, 0, 2.5 }; TableauRow updateTableauRow( 6 ); // row1 + row2 := x2 = x0 + 2 x1 - x3 + x4 @@ -145,24 +152,25 @@ class BoundsExplainerTestSuite : public CxxTest::TestSuite TS_ASSERT_THROWS_NOTHING( be.setExplanation( row1, 0, true ) ); TS_ASSERT_THROWS_NOTHING( be.setExplanation( row2, 1, true ) ); - TS_ASSERT_THROWS_NOTHING( be.setExplanation( row3, 1, false ) ); // Will not be possible in an actual tableau + TS_ASSERT_THROWS_NOTHING( be.setExplanation( row3, 1, false ) ); // Will not be possible in + // an actual tableau be.updateBoundExplanation( updateTableauRow, true ); // Result is { 1, 0, 0 } + 2 * { 0, -1, 0 } + { 1, -1, 0} - Vector res1 { 2, -3, 0 }; + Vector res1{ 2, -3, 0 }; for ( unsigned i = 0; i < 3; ++i ) TS_ASSERT_EQUALS( be.getExplanation( 2, true ).get( i ), res1[i] ); be.updateBoundExplanation( updateTableauRow, false, 3 ); // Result is 2 * { 0, 0, 2.5 } + { -1, 1, 0 } - Vector res2 { -1, 2, 5 }; + Vector res2{ -1, 2, 5 }; for ( unsigned i = 0; i < 3; ++i ) TS_ASSERT_EQUALS( be.getExplanation( 3, false ).get( i ), res2[i] ); be.updateBoundExplanation( updateTableauRow, false, 1 ); // Result is -0.5 * { 1, 0, 0 } + 0.5 * { -1, 2, 5 } - 0.5 * { 1, -1, 0 } - Vector res3 { -1.5, 1.5, 2.5 }; + Vector res3{ -1.5, 1.5, 2.5 }; for ( unsigned i = 0; i < 3; ++i ) TS_ASSERT_EQUALS( be.getExplanation( 1, false ).get( i ), res3[i] ); @@ -175,8 +183,8 @@ class BoundsExplainerTestSuite : public CxxTest::TestSuite be.updateBoundExplanationSparse( updateSparseRow, true, 5 ); // Result is ( 1 / 2.5 ) * ( -2.5 ) * { -1.5, 1.5, 2.5 } + ( 1 / 2.5 ) * { 0, 0, 2.5 } - Vector res4 { 1.5, -1.5, -1.5 }; - for ( unsigned i = 0; i < 3; ++i) + Vector res4{ 1.5, -1.5, -1.5 }; + for ( unsigned i = 0; i < 3; ++i ) TS_ASSERT_EQUALS( be.getExplanation( 5, true ).get( i ), res4[i] ); } }; diff --git a/src/proofs/tests/Test_Checker.h b/src/proofs/tests/Test_Checker.h index 5ebcc3e9c4..57ff3f10fd 100644 --- a/src/proofs/tests/Test_Checker.h +++ b/src/proofs/tests/Test_Checker.h @@ -12,8 +12,8 @@ ** [[ Add lengthier description here ]] **/ -#include "Checker.h" #include "CSRMatrix.h" +#include "Checker.h" #include "cxxtest/TestSuite.h" class CheckerTestSuite : public CxxTest::TestSuite @@ -34,13 +34,14 @@ class CheckerTestSuite : public CxxTest::TestSuite groundUpperBounds[5] = 2; ReluConstraint relu1 = ReluConstraint( 0, 2 ); // aux var is 4 - ReluConstraint relu2 = ReluConstraint( 1, 3 ) ; // aux var is 5 + ReluConstraint relu2 = ReluConstraint( 1, 3 ); // aux var is 5 List constraintsList = { &relu1, &relu2 }; // Set a complete tree of depth 3, using 2 ReLUs auto *root = new UnsatCertificateNode( NULL, PiecewiseLinearCaseSplit() ); - Checker checker( root, m, &initialTableau, groundUpperBounds, groundLowerBounds, constraintsList ); + Checker checker( + root, m, &initialTableau, groundUpperBounds, groundLowerBounds, constraintsList ); auto splits1 = relu1.getCaseSplits(); auto splits2 = relu2.getCaseSplits(); diff --git a/src/proofs/tests/Test_SmtLibWriter.h b/src/proofs/tests/Test_SmtLibWriter.h index 7efd698e4f..05f035d58a 100644 --- a/src/proofs/tests/Test_SmtLibWriter.h +++ b/src/proofs/tests/Test_SmtLibWriter.h @@ -12,16 +12,17 @@ ** [[ Add lengthier description here ]] **/ +#include "MockFile.h" #include "SmtLibWriter.h" #include "context/cdlist.h" #include "context/context.h" + #include -#include "MockFile.h" class SmtLibWriterTestSuite : public CxxTest::TestSuite { public: - MockFile* file; + MockFile *file; /* Tests the whole functionality of the SmtLibWriter module @@ -32,7 +33,7 @@ class SmtLibWriterTestSuite : public CxxTest::TestSuite Vector row = { 1, 2 }; SparseUnsortedList sparseRow( row.data(), 2 ); Vector groundUpperBounds = { 1, 1 }; - Vector groundLowerBounds = { 1 , -1 }; + Vector groundLowerBounds = { 1, -1 }; List instance; SmtLibWriter::addHeader( 2, instance ); @@ -53,50 +54,50 @@ class SmtLibWriterTestSuite : public CxxTest::TestSuite PiecewiseLinearCaseSplit disjunct6; Equation equation1 = Equation(); - equation1.addAddend(1, 0); - equation1.addAddend(-2, 1); + equation1.addAddend( 1, 0 ); + equation1.addAddend( -2, 1 ); equation1._scalar = -4; disjunct1.addEquation( equation1 ); - disjunct1.storeBoundTightening( Tightening(1, -2, Tightening::UB ) ); + disjunct1.storeBoundTightening( Tightening( 1, -2, Tightening::UB ) ); - disjunct2.storeBoundTightening(Tightening(1, 2, Tightening::LB ) ); - disjunct2.storeBoundTightening(Tightening(0, -1.5, Tightening::UB ) ); + disjunct2.storeBoundTightening( Tightening( 1, 2, Tightening::LB ) ); + disjunct2.storeBoundTightening( Tightening( 0, -1.5, Tightening::UB ) ); - SmtLibWriter::addDisjunctionConstraint( {disjunct1, disjunct2} ,instance); + SmtLibWriter::addDisjunctionConstraint( { disjunct1, disjunct2 }, instance ); Equation equation2 = Equation(); - equation2.addAddend(0, 0); - equation2.addAddend(-1, 1); + equation2.addAddend( 0, 0 ); + equation2.addAddend( -1, 1 ); equation2._scalar = 1; Equation equation3 = Equation(); - equation3.addAddend(0, 0); - equation3.addAddend(-1, 2); + equation3.addAddend( 0, 0 ); + equation3.addAddend( -1, 2 ); equation3._scalar = 1; Equation equation4 = Equation(); - equation4.addAddend(0, 0); - equation4.addAddend(-1, 3); + equation4.addAddend( 0, 0 ); + equation4.addAddend( -1, 3 ); equation4._scalar = 1; disjunct3.addEquation( equation2 ); disjunct5.addEquation( equation3 ); disjunct6.addEquation( equation4 ); - SmtLibWriter::addDisjunctionConstraint( {disjunct3, disjunct5, disjunct6 } ,instance); + SmtLibWriter::addDisjunctionConstraint( { disjunct3, disjunct5, disjunct6 }, instance ); - disjunct4.storeBoundTightening(Tightening(1, 2, Tightening::LB ) ); - SmtLibWriter::addDisjunctionConstraint( {disjunct4} ,instance); - SmtLibWriter::addDisjunctionConstraint( {disjunct3, disjunct4} ,instance); + disjunct4.storeBoundTightening( Tightening( 1, 2, Tightening::LB ) ); + SmtLibWriter::addDisjunctionConstraint( { disjunct4 }, instance ); + SmtLibWriter::addDisjunctionConstraint( { disjunct3, disjunct4 }, instance ); - disjunct4.storeBoundTightening(Tightening(1, 2, Tightening::LB ) ); - disjunct4.storeBoundTightening(Tightening(0, -1.5, Tightening::UB ) ); - SmtLibWriter::addDisjunctionConstraint( {disjunct4} ,instance); + disjunct4.storeBoundTightening( Tightening( 1, 2, Tightening::LB ) ); + disjunct4.storeBoundTightening( Tightening( 0, -1.5, Tightening::UB ) ); + SmtLibWriter::addDisjunctionConstraint( { disjunct4 }, instance ); disjunct3.addEquation( equation2 ); disjunct3.addEquation( equation2 ); - SmtLibWriter::addDisjunctionConstraint( {disjunct3} ,instance); + SmtLibWriter::addDisjunctionConstraint( { disjunct3 }, instance ); SmtLibWriter::addFooter( instance ); @@ -119,24 +120,25 @@ class SmtLibWriterTestSuite : public CxxTest::TestSuite // Bounds line = file->readLine( '\n' ); - expectedLine = String("( assert ( <= x0 ") + SmtLibWriter::signedValue( 1 ) + " ) )"; + expectedLine = String( "( assert ( <= x0 " ) + SmtLibWriter::signedValue( 1 ) + " ) )"; TS_ASSERT_EQUALS( line, expectedLine ); line = file->readLine( '\n' ); - expectedLine = String("( assert ( <= x1 ") + SmtLibWriter::signedValue( 1 ) + " ) )"; + expectedLine = String( "( assert ( <= x1 " ) + SmtLibWriter::signedValue( 1 ) + " ) )"; TS_ASSERT_EQUALS( line, expectedLine ); line = file->readLine( '\n' ); - expectedLine = String("( assert ( >= x0 ") + SmtLibWriter::signedValue( 1 ) + " ) )"; + expectedLine = String( "( assert ( >= x0 " ) + SmtLibWriter::signedValue( 1 ) + " ) )"; TS_ASSERT_EQUALS( line, expectedLine ); line = file->readLine( '\n' ); - expectedLine = String("( assert ( >= x1 ") + SmtLibWriter::signedValue( -1 ) + " ) )"; + expectedLine = String( "( assert ( >= x1 " ) + SmtLibWriter::signedValue( -1 ) + " ) )"; TS_ASSERT_EQUALS( line, expectedLine ); // Tableau line = file->readLine( '\n' ); - expectedLine = String("( assert ( = 0 ( + x0 ( * " ) + SmtLibWriter::signedValue( 2 ) + " x1 ) ) ) )"; + expectedLine = + String( "( assert ( = 0 ( + x0 ( * " ) + SmtLibWriter::signedValue( 2 ) + " x1 ) ) ) )"; TS_ASSERT_EQUALS( line, expectedLine ); // Relu @@ -156,120 +158,122 @@ class SmtLibWriterTestSuite : public CxxTest::TestSuite // Max line = file->readLine( '\n' ); - expectedLine = String("( assert ( => ( and ( >= x2 x3 ) ( >= x2 x4 ) ) ( = x1 x2 ) ) )"); + expectedLine = String( "( assert ( => ( and ( >= x2 x3 ) ( >= x2 x4 ) ) ( = x1 x2 ) ) )" ); TS_ASSERT_EQUALS( line, expectedLine ); line = file->readLine( '\n' ); - expectedLine = String("( assert ( => ( and ( >= x3 x2 ) ( >= x3 x4 ) ) ( = x1 x3 ) ) )"); + expectedLine = String( "( assert ( => ( and ( >= x3 x2 ) ( >= x3 x4 ) ) ( = x1 x3 ) ) )" ); TS_ASSERT_EQUALS( line, expectedLine ); line = file->readLine( '\n' ); - expectedLine = String("( assert ( => ( and ( >= x4 x2 ) ( >= x4 x3 ) ) ( = x1 x4 ) ) )"); + expectedLine = String( "( assert ( => ( and ( >= x4 x2 ) ( >= x4 x3 ) ) ( = x1 x4 ) ) )" ); TS_ASSERT_EQUALS( line, expectedLine ); // Disjunctions (several cases) line = file->readLine( '\n' ); - expectedLine = String("( assert"); + expectedLine = String( "( assert" ); TS_ASSERT_EQUALS( line, expectedLine ); line = file->readLine( '\n' ); - expectedLine = String("( or"); + expectedLine = String( "( or" ); TS_ASSERT_EQUALS( line, expectedLine ); line = file->readLine( '\n' ); - expectedLine = String("( and ( = ( - 4 ) ( + x0 ( * ( - 2 ) x1 ) ) ) ( <= x1 ( - 2 ) ) )"); + expectedLine = + String( "( and ( = ( - 4 ) ( + x0 ( * ( - 2 ) x1 ) ) ) ( <= x1 ( - 2 ) ) )" ); TS_ASSERT_EQUALS( line, expectedLine ); line = file->readLine( '\n' ); - expectedLine = String("( and ( >= x1 2 )( <= x0 ( - 1.5 ) ) )"); - TS_ASSERT_EQUALS( line, expectedLine); + expectedLine = String( "( and ( >= x1 2 )( <= x0 ( - 1.5 ) ) )" ); + TS_ASSERT_EQUALS( line, expectedLine ); line = file->readLine( '\n' ); - expectedLine = String(" ) )"); - TS_ASSERT_EQUALS( line, expectedLine); + expectedLine = String( " ) )" ); + TS_ASSERT_EQUALS( line, expectedLine ); line = file->readLine( '\n' ); - expectedLine = String("( assert"); + expectedLine = String( "( assert" ); TS_ASSERT_EQUALS( line, expectedLine ); line = file->readLine( '\n' ); - expectedLine = String("( or"); + expectedLine = String( "( or" ); TS_ASSERT_EQUALS( line, expectedLine ); line = file->readLine( '\n' ); - expectedLine = String("( = 1 ( - x1 ) ) "); + expectedLine = String( "( = 1 ( - x1 ) ) " ); TS_ASSERT_EQUALS( line, expectedLine ); line = file->readLine( '\n' ); - expectedLine = String("( or"); + expectedLine = String( "( or" ); TS_ASSERT_EQUALS( line, expectedLine ); line = file->readLine( '\n' ); - expectedLine = String("( = 1 ( - x2 ) ) "); + expectedLine = String( "( = 1 ( - x2 ) ) " ); TS_ASSERT_EQUALS( line, expectedLine ); line = file->readLine( '\n' ); - expectedLine = String("( = 1 ( - x3 ) ) "); + expectedLine = String( "( = 1 ( - x3 ) ) " ); TS_ASSERT_EQUALS( line, expectedLine ); line = file->readLine( '\n' ); - expectedLine = String(" ) ) )"); + expectedLine = String( " ) ) )" ); TS_ASSERT_EQUALS( line, expectedLine ); line = file->readLine( '\n' ); - expectedLine = String("( assert"); + expectedLine = String( "( assert" ); TS_ASSERT_EQUALS( line, expectedLine ); line = file->readLine( '\n' ); - expectedLine = String("( >= x1 2 )"); + expectedLine = String( "( >= x1 2 )" ); TS_ASSERT_EQUALS( line, expectedLine ); line = file->readLine( '\n' ); - expectedLine = String(" )"); + expectedLine = String( " )" ); TS_ASSERT_EQUALS( line, expectedLine ); line = file->readLine( '\n' ); - expectedLine = String("( assert"); + expectedLine = String( "( assert" ); TS_ASSERT_EQUALS( line, expectedLine ); line = file->readLine( '\n' ); - expectedLine = String("( or"); + expectedLine = String( "( or" ); TS_ASSERT_EQUALS( line, expectedLine ); line = file->readLine( '\n' ); - expectedLine = String("( = 1 ( - x1 ) ) "); + expectedLine = String( "( = 1 ( - x1 ) ) " ); TS_ASSERT_EQUALS( line, expectedLine ); line = file->readLine( '\n' ); - expectedLine = String("( >= x1 2 )"); + expectedLine = String( "( >= x1 2 )" ); TS_ASSERT_EQUALS( line, expectedLine ); line = file->readLine( '\n' ); - expectedLine = String(" ) )"); + expectedLine = String( " ) )" ); TS_ASSERT_EQUALS( line, expectedLine ); line = file->readLine( '\n' ); - expectedLine = String("( assert"); + expectedLine = String( "( assert" ); TS_ASSERT_EQUALS( line, expectedLine ); line = file->readLine( '\n' ); - expectedLine = String("( and ( >= x1 2 )( and ( >= x1 2 )( <= x0 ( - 1.5 ) ) ) )"); + expectedLine = String( "( and ( >= x1 2 )( and ( >= x1 2 )( <= x0 ( - 1.5 ) ) ) )" ); TS_ASSERT_EQUALS( line, expectedLine ); line = file->readLine( '\n' ); - expectedLine = String(" )"); + expectedLine = String( " )" ); TS_ASSERT_EQUALS( line, expectedLine ); line = file->readLine( '\n' ); - expectedLine = String("( assert"); + expectedLine = String( "( assert" ); TS_ASSERT_EQUALS( line, expectedLine ); line = file->readLine( '\n' ); - expectedLine = String("( and ( = 1 ( - x1 ) ) ( and ( = 1 ( - x1 ) ) ( = 1 ( - x1 ) ) ) )"); + expectedLine = + String( "( and ( = 1 ( - x1 ) ) ( and ( = 1 ( - x1 ) ) ( = 1 ( - x1 ) ) ) )" ); TS_ASSERT_EQUALS( line, expectedLine ); line = file->readLine( '\n' ); - expectedLine = String(" )"); + expectedLine = String( " )" ); TS_ASSERT_EQUALS( line, expectedLine ); line = file->readLine( '\n' ); diff --git a/src/proofs/tests/Test_UnsatCertificateNode.h b/src/proofs/tests/Test_UnsatCertificateNode.h index f4d8d6712b..db778cb373 100644 --- a/src/proofs/tests/Test_UnsatCertificateNode.h +++ b/src/proofs/tests/Test_UnsatCertificateNode.h @@ -13,10 +13,11 @@ **/ #include "BoundExplainer.h" +#include "UnsatCertificateNode.h" #include "context/cdlist.h" #include "context/context.h" + #include -#include "UnsatCertificateNode.h" class UnsatCertificateNodeTestSuite : public CxxTest::TestSuite { @@ -65,10 +66,10 @@ class UnsatCertificateNodeTestSuite : public CxxTest::TestSuite { UnsatCertificateNode root = UnsatCertificateNode( NULL, PiecewiseLinearCaseSplit() ); - auto upperBoundExplanation = Vector(1, 1); - auto lowerBoundExplanation = Vector(1, 1); + auto upperBoundExplanation = Vector( 1, 1 ); + auto lowerBoundExplanation = Vector( 1, 1 ); - auto *contradiction = new Contradiction( Vector(1, 0 ) ); + auto *contradiction = new Contradiction( Vector( 1, 0 ) ); root.setContradiction( contradiction ); TS_ASSERT_EQUALS( root.getContradiction(), contradiction ); } @@ -81,11 +82,14 @@ class UnsatCertificateNodeTestSuite : public CxxTest::TestSuite UnsatCertificateNode root = UnsatCertificateNode( NULL, PiecewiseLinearCaseSplit() ); Vector emptyVec; - auto explanation1 = std::shared_ptr( new PLCLemma( { 1 }, 1, 0, BoundType::UPPER, BoundType::UPPER, emptyVec, RELU ) ); - auto explanation2 = std::shared_ptr( new PLCLemma( { 1 }, 1, -1, BoundType::UPPER, BoundType::UPPER, emptyVec, RELU ) ); - auto explanation3 = std::shared_ptr( new PLCLemma( { 1 }, 1, -4, BoundType::UPPER, BoundType::UPPER, emptyVec, RELU ) ); + auto explanation1 = std::shared_ptr( + new PLCLemma( { 1 }, 1, 0, BoundType::UPPER, BoundType::UPPER, emptyVec, RELU ) ); + auto explanation2 = std::shared_ptr( + new PLCLemma( { 1 }, 1, -1, BoundType::UPPER, BoundType::UPPER, emptyVec, RELU ) ); + auto explanation3 = std::shared_ptr( + new PLCLemma( { 1 }, 1, -4, BoundType::UPPER, BoundType::UPPER, emptyVec, RELU ) ); - TS_ASSERT(root.getPLCLemmas().empty() ); + TS_ASSERT( root.getPLCLemmas().empty() ); root.addPLCLemma( explanation1 ); root.addPLCLemma( explanation2 ); diff --git a/src/proofs/tests/Test_UnsatCertificateUtils.h b/src/proofs/tests/Test_UnsatCertificateUtils.h index 213e4d8d22..af6c8c7d1f 100644 --- a/src/proofs/tests/Test_UnsatCertificateUtils.h +++ b/src/proofs/tests/Test_UnsatCertificateUtils.h @@ -13,8 +13,8 @@ **/ #include "CSRMatrix.h" -#include "cxxtest/TestSuite.h" #include "UnsatCertificateUtils.h" +#include "cxxtest/TestSuite.h" class UnsatCertificateUtilsTestSuite : public CxxTest::TestSuite { @@ -22,21 +22,22 @@ class UnsatCertificateUtilsTestSuite : public CxxTest::TestSuite void test_bound_computation() { unsigned m = 3, n = 6; - double A[] = {1, 0, -1, 1, 0, 0, 0, -1, 2, 0, 1, 0, 0.5, 0, -1, 0, 0, 1 }; + double A[] = { 1, 0, -1, 1, 0, 0, 0, -1, 2, 0, 1, 0, 0.5, 0, -1, 0, 0, 1 }; auto initialTableau = CSRMatrix( A, m, n ); - Vector groundUpperBounds = { 1, 1 ,1 ,1 ,1 ,1 }; + Vector groundUpperBounds = { 1, 1, 1, 1, 1, 1 }; Vector groundLowerBounds = { 0, 0, 0, 0, 0, 0 }; Vector rowCombination; - const double expl[3] = {1, 1, 0}; + const double expl[3] = { 1, 1, 0 }; SparseUnsortedList explanation = SparseUnsortedList(); - explanation.initialize( expl, 3); - // Linear combination is x0 = 2x0 - x1 + x2 + x3 + x4, thus explanation combination is only lhs - // Checks computation method only, since no actual bound will be explained this way + explanation.initialize( expl, 3 ); + // Linear combination is x0 = 2x0 - x1 + x2 + x3 + x4, thus explanation combination is only + // lhs Checks computation method only, since no actual bound will be explained this way unsigned var = 0; - UNSATCertificateUtils::getExplanationRowCombination( var, explanation, rowCombination, &initialTableau, n ); + UNSATCertificateUtils::getExplanationRowCombination( + var, explanation, rowCombination, &initialTableau, n ); auto it = rowCombination.begin(); TS_ASSERT_EQUALS( *it, 2 ); @@ -53,7 +54,13 @@ class UnsatCertificateUtilsTestSuite : public CxxTest::TestSuite ++it; TS_ASSERT_EQUALS( it, rowCombination.end() ); - double explainedBound = UNSATCertificateUtils::computeBound( var, true, explanation, &initialTableau, groundUpperBounds.data(), groundLowerBounds.data(), groundUpperBounds.size() ); + double explainedBound = UNSATCertificateUtils::computeBound( var, + true, + explanation, + &initialTableau, + groundUpperBounds.data(), + groundLowerBounds.data(), + groundUpperBounds.size() ); TS_ASSERT_EQUALS( explainedBound, 5 ); } diff --git a/src/query_loader/QueryLoader.cpp b/src/query_loader/QueryLoader.cpp index 2dd9d30990..71406b5ef2 100644 --- a/src/query_loader/QueryLoader.cpp +++ b/src/query_loader/QueryLoader.cpp @@ -14,7 +14,10 @@ ** [[ Add lengthier description here ]] **/ +#include "QueryLoader.h" + #include "AutoFile.h" +#include "BilinearConstraint.h" #include "Debug.h" #include "DisjunctionConstraint.h" #include "Equation.h" @@ -24,8 +27,6 @@ #include "MStringf.h" #include "MarabouError.h" #include "MaxConstraint.h" -#include "BilinearConstraint.h" -#include "QueryLoader.h" #include "ReluConstraint.h" #include "RoundConstraint.h" #include "SignConstraint.h" @@ -35,7 +36,8 @@ InputQuery QueryLoader::loadQuery( const String &fileName ) { if ( !IFile::exists( fileName ) ) { - throw MarabouError( MarabouError::FILE_DOES_NOT_EXIST, Stringf( "File %s not found.\n", fileName.ascii() ).ascii() ); + throw MarabouError( MarabouError::FILE_DOES_NOT_EXIST, + Stringf( "File %s not found.\n", fileName.ascii() ).ascii() ); } InputQuery inputQuery; @@ -127,7 +129,7 @@ InputQuery QueryLoader::loadQuery( const String &fileName ) } // Equations - for( unsigned i = 0; i < numEquations; ++i ) + for ( unsigned i = 0; i < numEquations; ++i ) { QL_LOG( Stringf( "Equation: %u ", i ).ascii() ); String line = input->readLine(); @@ -140,7 +142,7 @@ InputQuery QueryLoader::loadQuery( const String &fileName ) // Skip equation number ++it; int eqType = atoi( it->ascii() ); - QL_LOG( Stringf("Type: %u ", eqType ).ascii() ); + QL_LOG( Stringf( "Type: %u ", eqType ).ascii() ); ++it; double eqScalar = atof( it->ascii() ); QL_LOG( Stringf( "Scalar: %f\n", eqScalar ).ascii() ); @@ -163,7 +165,8 @@ InputQuery QueryLoader::loadQuery( const String &fileName ) default: // Throw exception - throw MarabouError( MarabouError::INVALID_EQUATION_TYPE, Stringf( "Invalid Equation Type\n" ).ascii() ); + throw MarabouError( MarabouError::INVALID_EQUATION_TYPE, + Stringf( "Invalid Equation Type\n" ).ascii() ); break; } @@ -198,7 +201,8 @@ InputQuery QueryLoader::loadQuery( const String &fileName ) String coType = *it; String serializeConstraint; // include type in serializeConstraint as well - while ( it != tokens.end() ) { + while ( it != tokens.end() ) + { serializeConstraint += *it + String( "," ); it++; } @@ -212,7 +216,8 @@ InputQuery QueryLoader::loadQuery( const String &fileName ) } else if ( coType == "leaky_relu" ) { - inputQuery.addPiecewiseLinearConstraint( new LeakyReluConstraint( serializeConstraint ) ); + inputQuery.addPiecewiseLinearConstraint( + new LeakyReluConstraint( serializeConstraint ) ); } else if ( coType == "max" ) { @@ -220,7 +225,8 @@ InputQuery QueryLoader::loadQuery( const String &fileName ) } else if ( coType == "absoluteValue" ) { - inputQuery.addPiecewiseLinearConstraint( new AbsoluteValueConstraint( serializeConstraint ) ); + inputQuery.addPiecewiseLinearConstraint( + new AbsoluteValueConstraint( serializeConstraint ) ); } else if ( coType == "sign" ) { @@ -228,26 +234,27 @@ InputQuery QueryLoader::loadQuery( const String &fileName ) } else if ( coType == "disj" ) { - inputQuery.addPiecewiseLinearConstraint( new DisjunctionConstraint( serializeConstraint ) ); + inputQuery.addPiecewiseLinearConstraint( + new DisjunctionConstraint( serializeConstraint ) ); } - else if ( coType == "sigmoid") + else if ( coType == "sigmoid" ) { inputQuery.addNonlinearConstraint( new SigmoidConstraint( serializeConstraint ) ); } - else if ( coType == "softmax") + else if ( coType == "softmax" ) { SoftmaxConstraint *softmax = new SoftmaxConstraint( serializeConstraint ); - inputQuery.addNonlinearConstraint(softmax); + inputQuery.addNonlinearConstraint( softmax ); Equation eq; for ( const auto &output : softmax->getOutputs() ) - eq.addAddend(1, output); - eq.setScalar(1); - inputQuery.addEquation(eq); + eq.addAddend( 1, output ); + eq.setScalar( 1 ); + inputQuery.addEquation( eq ); } - else if ( coType == "bilinear") + else if ( coType == "bilinear" ) { BilinearConstraint *bilinear = new BilinearConstraint( serializeConstraint ); - inputQuery.addNonlinearConstraint(bilinear); + inputQuery.addNonlinearConstraint( bilinear ); } else if ( coType == "round" ) { @@ -255,7 +262,9 @@ InputQuery QueryLoader::loadQuery( const String &fileName ) } else { - throw MarabouError( MarabouError::UNSUPPORTED_NON_LINEAR_CONSTRAINT, Stringf( "Unsupported non-linear constraint: %s\n", coType.ascii() ).ascii() ); + throw MarabouError( + MarabouError::UNSUPPORTED_NON_LINEAR_CONSTRAINT, + Stringf( "Unsupported non-linear constraint: %s\n", coType.ascii() ).ascii() ); } } diff --git a/src/query_loader/QueryLoader.h b/src/query_loader/QueryLoader.h index 6a1cc042bd..0580c00a94 100644 --- a/src/query_loader/QueryLoader.h +++ b/src/query_loader/QueryLoader.h @@ -19,7 +19,7 @@ #include "InputQuery.h" -#define QL_LOG(x, ...) LOG(GlobalConfiguration::QUERY_LOADER_LOGGING, "QueryLoader: %s\n", x ) +#define QL_LOG( x, ... ) LOG( GlobalConfiguration::QUERY_LOADER_LOGGING, "QueryLoader: %s\n", x ) class QueryLoader { diff --git a/src/query_loader/tests/Test_QueryLoader.h b/src/query_loader/tests/Test_QueryLoader.h index 9cd3de2ed6..4ae9728703 100644 --- a/src/query_loader/tests/Test_QueryLoader.h +++ b/src/query_loader/tests/Test_QueryLoader.h @@ -13,8 +13,6 @@ **/ -#include - #include "AutoFile.h" #include "Equation.h" #include "InputQuery.h" @@ -23,6 +21,8 @@ #include "ReluConstraint.h" #include "T/unistd.h" +#include + const String QUERY_TEST_FILE( "QueryTest.txt" ); class MockForQueryLoader @@ -30,7 +30,7 @@ class MockForQueryLoader , public T::Base_stat { public: - int stat( const char */* path */, StructStat */* buf */ ) + int stat( const char * /* path */, StructStat * /* buf */ ) { // 0 means file exists return 0; diff --git a/src/system_tests/Test_AbsoluteValue.h b/src/system_tests/Test_AbsoluteValue.h index e855cf2f3f..1053f530bd 100644 --- a/src/system_tests/Test_AbsoluteValue.h +++ b/src/system_tests/Test_AbsoluteValue.h @@ -13,14 +13,14 @@ **/ -#include - #include "AbsoluteValueConstraint.h" #include "AcasParser.h" #include "Engine.h" #include "FloatUtils.h" #include "InputQuery.h" +#include + class AbsoluteValueTestSuite : public CxxTest::TestSuite { public: @@ -163,8 +163,8 @@ class AbsoluteValueTestSuite : public CxxTest::TestSuite for ( unsigned i = 0; i < 5; ++i ) { unsigned inputVariable = acasParser.getInputVariable( i ); - AbsoluteValueConstraint *abs = new AbsoluteValueConstraint - ( inputVariable, numVariables + i ); + AbsoluteValueConstraint *abs = + new AbsoluteValueConstraint( inputVariable, numVariables + i ); inputQuery.addPiecewiseLinearConstraint( abs ); } @@ -191,14 +191,14 @@ class AbsoluteValueTestSuite : public CxxTest::TestSuite equationOut.setType( Equation::LE ); // minimal - larger <= 0 --> larger >= minimal - equationOut.addAddend( 1 , minimalOutputVar ); + equationOut.addAddend( 1, minimalOutputVar ); equationOut.addAddend( -1, largerOutputVar ); equationOut.setScalar( 0 ); inputQuery.addEquation( equationOut ); // Run the query Engine engine; - if( !engine.processInputQuery( inputQuery ) ) + if ( !engine.processInputQuery( inputQuery ) ) { // No counter example found, this is acceptable return; @@ -206,8 +206,8 @@ class AbsoluteValueTestSuite : public CxxTest::TestSuite TS_ASSERT( engine.getInputQuery()->getNetworkLevelReasoner() ); - auto constraintsInTopologicalOrder = engine.getInputQuery()-> - getNetworkLevelReasoner()->getConstraintsInTopologicalOrder(); + auto constraintsInTopologicalOrder = + engine.getInputQuery()->getNetworkLevelReasoner()->getConstraintsInTopologicalOrder(); auto allConstraints = engine.getInputQuery()->getPiecewiseLinearConstraints(); TS_ASSERT_EQUALS( constraintsInTopologicalOrder.size(), allConstraints.size() ); diff --git a/src/system_tests/Test_Disjunction.h b/src/system_tests/Test_Disjunction.h index 2349c98c76..f653f3e970 100644 --- a/src/system_tests/Test_Disjunction.h +++ b/src/system_tests/Test_Disjunction.h @@ -13,12 +13,12 @@ **/ -#include - +#include "DisjunctionConstraint.h" #include "Engine.h" -#include "InputQuery.h" #include "FloatUtils.h" -#include "DisjunctionConstraint.h" +#include "InputQuery.h" + +#include class DisjunctionTestSuite : public CxxTest::TestSuite { diff --git a/src/system_tests/Test_acas.h b/src/system_tests/Test_acas.h index 508e61b3db..d3a815536d 100644 --- a/src/system_tests/Test_acas.h +++ b/src/system_tests/Test_acas.h @@ -13,8 +13,6 @@ **/ -#include - #include "AcasParser.h" #include "Engine.h" #include "FloatUtils.h" @@ -23,10 +21,11 @@ #include "MarabouError.h" #include "Preprocessor.h" +#include + class AcasTestSuite : public CxxTest::TestSuite { public: - void setUp() { } @@ -62,9 +61,10 @@ class AcasTestSuite : public CxxTest::TestSuite for ( unsigned i = 0; i < 5; ++i ) { unsigned variable = acasParser.getOutputVariable( i ); - double newError = FloatUtils::abs( outputs[i] - inputQuery.getSolutionValue( variable ) ); + double newError = + FloatUtils::abs( outputs[i] - inputQuery.getSolutionValue( variable ) ); if ( FloatUtils::gt( newError, maxError ) ) - maxError = newError; + maxError = newError; } TS_ASSERT( FloatUtils::lt( maxError, 0.00001 ) ); @@ -85,7 +85,7 @@ class AcasTestSuite : public CxxTest::TestSuite } Engine engine; - bool result = engine.processInputQuery( inputQuery ) ; + bool result = engine.processInputQuery( inputQuery ); TS_ASSERT( result ); TS_ASSERT_THROWS_NOTHING( engine.solve() ); @@ -106,9 +106,10 @@ class AcasTestSuite : public CxxTest::TestSuite for ( unsigned i = 0; i < 5; ++i ) { unsigned variable = acasParser.getOutputVariable( i ); - double newError = FloatUtils::abs( outputs[i] - inputQuery.getSolutionValue( variable ) ); + double newError = + FloatUtils::abs( outputs[i] - inputQuery.getSolutionValue( variable ) ); if ( FloatUtils::gt( newError, maxError ) ) - maxError = newError; + maxError = newError; } TS_ASSERT( FloatUtils::lt( maxError, 0.00001 ) ); @@ -149,13 +150,13 @@ class AcasTestSuite : public CxxTest::TestSuite for ( unsigned i = 0; i < 5; ++i ) { unsigned variable = acasParser.getOutputVariable( i ); - double newError = FloatUtils::abs( outputs[i] - inputQuery.getSolutionValue( variable ) ); + double newError = + FloatUtils::abs( outputs[i] - inputQuery.getSolutionValue( variable ) ); if ( FloatUtils::gt( newError, maxError ) ) - maxError = newError; + maxError = newError; } TS_ASSERT( FloatUtils::lt( maxError, 0.00001 ) ); - } }; diff --git a/src/system_tests/Test_lp.h b/src/system_tests/Test_lp.h index ddb2a14aae..8a89312623 100644 --- a/src/system_tests/Test_lp.h +++ b/src/system_tests/Test_lp.h @@ -13,17 +13,16 @@ **/ -#include - #include "Engine.h" #include "FloatUtils.h" #include "InputQuery.h" #include "LinearExpression.h" +#include + class LpTestSuite : public CxxTest::TestSuite { public: - void setUp() { } @@ -56,21 +55,21 @@ class LpTestSuite : public CxxTest::TestSuite equation2.setScalar( 0.5 ); inputQuery.addEquation( equation2 ); - Equation equation3( Equation:: GE ); + Equation equation3( Equation::GE ); equation3.addAddend( 1, 1 ); equation3.addAddend( -1, 2 ); equation3.setScalar( 0 ); inputQuery.addEquation( equation3 ); - Equation equation4( Equation:: GE ); + Equation equation4( Equation::GE ); equation4.addAddend( 1, 1 ); equation4.addAddend( -1, 3 ); equation4.setScalar( 0 ); inputQuery.addEquation( equation4 ); Engine engine; - TS_ASSERT_THROWS_NOTHING ( engine.processInputQuery( inputQuery )); - TS_ASSERT_THROWS_NOTHING ( engine.solve() ); + TS_ASSERT_THROWS_NOTHING( engine.processInputQuery( inputQuery ) ); + TS_ASSERT_THROWS_NOTHING( engine.solve() ); // Cost function: x0 - x1 Map heuristicCost; @@ -82,8 +81,7 @@ class LpTestSuite : public CxxTest::TestSuite engine.extractSolution( inputQuery ); - TS_ASSERT( FloatUtils::areEqual( engine.computeHeuristicCost - ( heuristicCost ), -0.5 ) ); + TS_ASSERT( FloatUtils::areEqual( engine.computeHeuristicCost( heuristicCost ), -0.5 ) ); heuristicCost.clear(); heuristicCost[0] = -2; @@ -95,8 +93,7 @@ class LpTestSuite : public CxxTest::TestSuite engine.extractSolution( inputQuery ); - TS_ASSERT( FloatUtils::areEqual( engine.computeHeuristicCost - ( cost ), -0.25 ) ); + TS_ASSERT( FloatUtils::areEqual( engine.computeHeuristicCost( cost ), -0.25 ) ); heuristicCost.clear(); heuristicCost[1] = -2; @@ -108,8 +105,7 @@ class LpTestSuite : public CxxTest::TestSuite engine.extractSolution( inputQuery ); - TS_ASSERT( FloatUtils::areEqual( engine.computeHeuristicCost - ( cost ), -6 ) ); + TS_ASSERT( FloatUtils::areEqual( engine.computeHeuristicCost( cost ), -6 ) ); } void test_fesiablbe() @@ -138,8 +134,8 @@ class LpTestSuite : public CxxTest::TestSuite Engine engine; - TS_ASSERT_THROWS_NOTHING ( engine.processInputQuery( inputQuery )); - TS_ASSERT_THROWS_NOTHING ( engine.solve() ); + TS_ASSERT_THROWS_NOTHING( engine.processInputQuery( inputQuery ) ); + TS_ASSERT_THROWS_NOTHING( engine.solve() ); engine.extractSolution( inputQuery ); @@ -152,24 +148,23 @@ class LpTestSuite : public CxxTest::TestSuite double value2 = inputQuery.getSolutionValue( 2 ); double value3 = inputQuery.getSolutionValue( 3 ); - value += 1 * value0; - value += 2 * value1; + value += 1 * value0; + value += 2 * value1; value += -1 * value2; - value += 1 * value3; + value += 1 * value3; TS_ASSERT_EQUALS( value, 11 ); - TS_ASSERT( value0 >= 0 ); + TS_ASSERT( value0 >= 0 ); TS_ASSERT( value0 <= 2 ); TS_ASSERT( value1 >= -3 ); TS_ASSERT( value1 <= 3 ); TS_ASSERT( value2 >= 4 ); TS_ASSERT( value2 <= 6 ); TS_ASSERT( value3 >= 0 ); - } - void test_infesiable() + void test_infesiable() { InputQuery inputQuery; inputQuery.setNumberOfVariables( 7 ); @@ -217,13 +212,13 @@ class LpTestSuite : public CxxTest::TestSuite inputQuery.addEquation( equation3 ); Engine engine; - bool result = engine.processInputQuery( inputQuery ) ; + bool result = engine.processInputQuery( inputQuery ); if ( !result ) { // got UNSAT from the preprocessing - TS_ASSERT(1); + TS_ASSERT( 1 ); } - else + else { result = engine.solve(); TS_ASSERT( !result ); diff --git a/src/system_tests/Test_max.h b/src/system_tests/Test_max.h index 21965de17a..5af09684b9 100644 --- a/src/system_tests/Test_max.h +++ b/src/system_tests/Test_max.h @@ -2,7 +2,7 @@ /*! \file Test_max.h ** \verbatim ** Top contributors (to current version): - ** Derek Huang, Guy Katz, Duligur Ibeling + ** Derek Huang, Guy Katz, Duligur Ibeling ** This file is part of the Marabou project. ** Copyright (c) 2017-2019 by the authors listed in the file AUTHORS ** in the top-level source directory) and their institutional affiliations. @@ -12,18 +12,17 @@ **/ -#include - #include "Engine.h" #include "FloatUtils.h" #include "InputQuery.h" #include "MaxConstraint.h" +#include + class MaxTestSuite : public CxxTest::TestSuite { public: - void setUp() { } @@ -32,13 +31,13 @@ class MaxTestSuite : public CxxTest::TestSuite { } - void test_max_infeasible() + void test_max_infeasible() { double large = 1000; InputQuery inputQuery; inputQuery.setNumberOfVariables( 9 ); - + inputQuery.setLowerBound( 0, -large ); inputQuery.setUpperBound( 0, 0 ); @@ -63,7 +62,7 @@ class MaxTestSuite : public CxxTest::TestSuite inputQuery.setUpperBound( 7, 0 ); inputQuery.setLowerBound( 8, 0 ); inputQuery.setUpperBound( 8, 0 ); - + Equation equation1; equation1.addAddend( 1, 0 ); equation1.addAddend( -1, 1 ); @@ -89,8 +88,8 @@ class MaxTestSuite : public CxxTest::TestSuite MaxConstraint *max1 = new MaxConstraint( 5, Set( { 0, 2, 3 } ) ); MaxConstraint *max2 = new MaxConstraint( 3, Set( { 0, 4 } ) ); - inputQuery.addPiecewiseLinearConstraint( max1 ); - inputQuery.addPiecewiseLinearConstraint( max2 ); + inputQuery.addPiecewiseLinearConstraint( max1 ); + inputQuery.addPiecewiseLinearConstraint( max2 ); Engine engine; if ( !engine.processInputQuery( inputQuery, true ) ) @@ -105,7 +104,7 @@ class MaxTestSuite : public CxxTest::TestSuite } } - void test_max_fesible() + void test_max_fesible() { double large = 1000; @@ -159,16 +158,16 @@ class MaxTestSuite : public CxxTest::TestSuite equation3.setScalar( 0 ); inputQuery.addEquation( equation3 ); - MaxConstraint *max1 = new MaxConstraint( 5, Set( { 0, 2, 3 } ) ); - MaxConstraint *max2 = new MaxConstraint( 3, Set( { 0, 4 } ) ); + MaxConstraint *max1 = new MaxConstraint( 5, Set( { 0, 2, 3 } ) ); + MaxConstraint *max2 = new MaxConstraint( 3, Set( { 0, 4 } ) ); - inputQuery.addPiecewiseLinearConstraint( max1 ); - inputQuery.addPiecewiseLinearConstraint( max2 ); + inputQuery.addPiecewiseLinearConstraint( max1 ); + inputQuery.addPiecewiseLinearConstraint( max2 ); Engine engine; TS_ASSERT_THROWS_NOTHING( engine.processInputQuery( inputQuery, true ) ) - TS_ASSERT_THROWS_NOTHING ( engine.solve() ); + TS_ASSERT_THROWS_NOTHING( engine.solve() ); engine.extractSolution( inputQuery ); @@ -188,19 +187,19 @@ class MaxTestSuite : public CxxTest::TestSuite TS_ASSERT( FloatUtils::areEqual( value_x3, value_x1f + value_x2f ) ) - TS_ASSERT( !FloatUtils::lt( value_x0, 0 ) ) - TS_ASSERT( !FloatUtils::gt( value_x0, 1 ) ) + TS_ASSERT( !FloatUtils::lt( value_x0, 0 ) ) + TS_ASSERT( !FloatUtils::gt( value_x0, 1 ) ) TS_ASSERT( !FloatUtils::lt( value_x1f, 0 ) ) TS_ASSERT( !FloatUtils::lt( value_x3, 0.5 ) ) TS_ASSERT( !FloatUtils::gt( value_x3, 1 ) ) TS_ASSERT( !FloatUtils::lt( value_x2f, 0.0 ) ) double x2_relu = FloatUtils::max( value_x2b, FloatUtils::max( value_x0, value_x2f ) ); - TS_ASSERT( FloatUtils::areEqual( x2_relu, value_x2b ) ) - - double x1_relu = FloatUtils::max( value_x1b, FloatUtils::max( value_x0, FloatUtils::max( value_x2b, value_x1f ) ) ); - TS_ASSERT ( FloatUtils::areEqual( x1_relu, value_x3 ) ) + TS_ASSERT( FloatUtils::areEqual( x2_relu, value_x2b ) ) + double x1_relu = FloatUtils::max( + value_x1b, FloatUtils::max( value_x0, FloatUtils::max( value_x2b, value_x1f ) ) ); + TS_ASSERT( FloatUtils::areEqual( x1_relu, value_x3 ) ) } }; diff --git a/src/system_tests/Test_mps.h b/src/system_tests/Test_mps.h index 50dfa402fe..70d58194b5 100644 --- a/src/system_tests/Test_mps.h +++ b/src/system_tests/Test_mps.h @@ -13,17 +13,16 @@ **/ -#include - #include "Engine.h" #include "InputQuery.h" -#include "MpsParser.h" #include "MString.h" +#include "MpsParser.h" + +#include class MpsTestSuite : public CxxTest::TestSuite { public: - void setUp() { } @@ -32,9 +31,9 @@ class MpsTestSuite : public CxxTest::TestSuite { } - void test_infesiable() + void test_infesiable() { - const String filename = RESOURCES_DIR "/mps/lp_infeasible_1.mps"; + const String filename = RESOURCES_DIR "/mps/lp_infeasible_1.mps"; // Extract an input query from the network InputQuery inputQuery; @@ -47,13 +46,14 @@ class MpsTestSuite : public CxxTest::TestSuite // Got infeasible in preprocess stage TS_ASSERT( 1 ); } - else { + else + { bool result = engine.solve(); - TS_ASSERT ( !result ); + TS_ASSERT( !result ); } } - void test_fesiable() + void test_fesiable() { const char *filename = RESOURCES_DIR "/mps/lp_feasible_1.mps"; @@ -63,8 +63,8 @@ class MpsTestSuite : public CxxTest::TestSuite MpsParser mpsParser( filename ); mpsParser.generateQuery( inputQuery ); Engine engine; - TS_ASSERT_THROWS_NOTHING ( engine.processInputQuery( inputQuery ) ); - TS_ASSERT_THROWS_NOTHING ( engine.solve() ); + TS_ASSERT_THROWS_NOTHING( engine.processInputQuery( inputQuery ) ); + TS_ASSERT_THROWS_NOTHING( engine.solve() ); engine.extractSolution( inputQuery ); // Sanity test @@ -74,18 +74,18 @@ class MpsTestSuite : public CxxTest::TestSuite double value1 = inputQuery.getSolutionValue( 1 ); double value2 = inputQuery.getSolutionValue( 2 ); - value += 1 * value0; - value += 2 * value1; + value += 1 * value0; + value += 2 * value1; value += -1 * value2; TS_ASSERT( FloatUtils::lte( value, 11 ) ) - TS_ASSERT( value0 >= 0 ); - TS_ASSERT( value0 <= 2 ); - TS_ASSERT( value1 >= -3 ); - TS_ASSERT( value1 <= 3 ); - TS_ASSERT( value2 >= 4 ); - TS_ASSERT( value2 <= 6 ); + TS_ASSERT( value0 >= 0 ); + TS_ASSERT( value0 <= 2 ); + TS_ASSERT( value1 >= -3 ); + TS_ASSERT( value1 <= 3 ); + TS_ASSERT( value2 >= 4 ); + TS_ASSERT( value2 <= 6 ); } }; diff --git a/src/system_tests/Test_relu.h b/src/system_tests/Test_relu.h index 4a23fee759..3e439a9398 100644 --- a/src/system_tests/Test_relu.h +++ b/src/system_tests/Test_relu.h @@ -13,13 +13,13 @@ **/ -#include - #include "Engine.h" -#include "InputQuery.h" #include "FloatUtils.h" +#include "InputQuery.h" #include "ReluConstraint.h" +#include + class ReluTestSuite : public CxxTest::TestSuite { @@ -177,7 +177,7 @@ class ReluTestSuite : public CxxTest::TestSuite Engine engine; TS_ASSERT_THROWS_NOTHING( engine.processInputQuery( inputQuery ) ); - TS_ASSERT_THROWS_NOTHING ( engine.solve() ); + TS_ASSERT_THROWS_NOTHING( engine.solve() ); engine.extractSolution( inputQuery ); diff --git a/src/system_tests/Test_sign.h b/src/system_tests/Test_sign.h index acc65fc44c..fcc7a1f5c0 100644 --- a/src/system_tests/Test_sign.h +++ b/src/system_tests/Test_sign.h @@ -13,13 +13,13 @@ **/ -#include - #include "Engine.h" #include "FloatUtils.h" #include "InputQuery.h" #include "SignConstraint.h" +#include + class SignTestSuite : public CxxTest::TestSuite { public: @@ -243,7 +243,7 @@ class SignTestSuite : public CxxTest::TestSuite // x3 = 0*x1 = 0 inputQuery.addEquation( equation3 ); - //equations of 2nd layer + // equations of 2nd layer Equation equation4; equation4.addAddend( 1, 1 ); equation4.addAddend( 2, 2 ); @@ -272,8 +272,8 @@ class SignTestSuite : public CxxTest::TestSuite // x6 = 1*x1 + 2*x2 +3*x3 inputQuery.addEquation( equation6 ); - //equations of 3rd layer (sign activation layer) - // x7 = sign (x4) + // equations of 3rd layer (sign activation layer) + // x7 = sign (x4) SignConstraint *sign1 = new SignConstraint( 4, 7 ); // x8 = sign (x5) @@ -286,7 +286,7 @@ class SignTestSuite : public CxxTest::TestSuite inputQuery.addPiecewiseLinearConstraint( sign2 ); inputQuery.addPiecewiseLinearConstraint( sign3 ); - //equation of 4th layer (output) + // equation of 4th layer (output) Equation equation7; equation7.addAddend( 1, 7 ); equation7.addAddend( 1, 8 ); @@ -341,7 +341,7 @@ class SignTestSuite : public CxxTest::TestSuite // x3 = 0*x1 = 0 inputQuery.addEquation( equation3 ); - //equations of 2nd layer + // equations of 2nd layer Equation equation4; equation4.addAddend( 1, 1 ); equation4.addAddend( 2, 2 ); @@ -384,7 +384,7 @@ class SignTestSuite : public CxxTest::TestSuite inputQuery.addPiecewiseLinearConstraint( sign2 ); inputQuery.addPiecewiseLinearConstraint( sign3 ); - //equation of 4th layer (output) + // equation of 4th layer (output) Equation equation7; equation7.addAddend( 1, 7 ); equation7.addAddend( 1, 8 ); @@ -438,7 +438,7 @@ class SignTestSuite : public CxxTest::TestSuite // x3 = 0*x1 = 0 inputQuery.addEquation( equation3 ); - //equations of 2nd layer + // equations of 2nd layer Equation equation4; equation4.addAddend( 1, 1 ); equation4.addAddend( 2, 2 ); @@ -467,8 +467,8 @@ class SignTestSuite : public CxxTest::TestSuite // x6 = 1*x1 + 2*x2 +3*x3 inputQuery.addEquation( equation6 ); - //equations of 3rd layer (sign activation layer) - // x7 = sign (x4) + // equations of 3rd layer (sign activation layer) + // x7 = sign (x4) SignConstraint *sign1 = new SignConstraint( 4, 7 ); // x8 = sign (x5) @@ -481,7 +481,7 @@ class SignTestSuite : public CxxTest::TestSuite inputQuery.addPiecewiseLinearConstraint( sign2 ); inputQuery.addPiecewiseLinearConstraint( sign3 ); - //equation of 4th layer (output) + // equation of 4th layer (output) Equation equation7; equation7.addAddend( 1, 7 ); equation7.addAddend( 1, 8 ); @@ -535,19 +535,19 @@ class SignTestSuite : public CxxTest::TestSuite // check 2nd layer variables // we want x4 = 1*x1 + 2*x2 + 3*x3 - if ( !FloatUtils::areEqual( value_x4, value_x1 + 2*value_x2 + 3*value_x3 ) ) + if ( !FloatUtils::areEqual( value_x4, value_x1 + 2 * value_x2 + 3 * value_x3 ) ) { correctSolution = false; } // we want x5 = 2*x2 - if ( !FloatUtils::areEqual( value_x5, 2*value_x2 ) ) + if ( !FloatUtils::areEqual( value_x5, 2 * value_x2 ) ) { correctSolution = false; } // we want x6 = 1*x1 + 2*x2 + 3*x3 - if ( !FloatUtils::areEqual( value_x6, value_x1 + 2*value_x2 + 3*value_x3 ) ) + if ( !FloatUtils::areEqual( value_x6, value_x1 + 2 * value_x2 + 3 * value_x3 ) ) { correctSolution = false; } @@ -657,7 +657,7 @@ class SignTestSuite : public CxxTest::TestSuite // x3 = 0*x1 = 0 inputQuery.addEquation( equation3 ); - //equations of 2nd layer + // equations of 2nd layer Equation equation4; equation4.addAddend( 1, 1 ); equation4.addAddend( 2, 2 ); @@ -700,7 +700,7 @@ class SignTestSuite : public CxxTest::TestSuite inputQuery.addPiecewiseLinearConstraint( sign2 ); inputQuery.addPiecewiseLinearConstraint( sign3 ); - //equation of 4th layer (output) + // equation of 4th layer (output) Equation equation7; equation7.addAddend( 1, 7 ); equation7.addAddend( 1, 8 ); @@ -754,19 +754,19 @@ class SignTestSuite : public CxxTest::TestSuite // check 2nd layer variables // want x4 = 1*x1 + 2*x2 + 3*x3 - if ( !FloatUtils::areEqual( value_x4, value_x1 + 2*value_x2 + 3*value_x3 ) ) + if ( !FloatUtils::areEqual( value_x4, value_x1 + 2 * value_x2 + 3 * value_x3 ) ) { correctSolution = false; } // want x5 = 2*x2 - if ( !FloatUtils::areEqual( value_x5, 2*value_x2 ) ) + if ( !FloatUtils::areEqual( value_x5, 2 * value_x2 ) ) { correctSolution = false; } // want x6 = 1*x1 + 2*x2 + 3*x3 - if ( !FloatUtils::areEqual( value_x6, value_x1 + 2*value_x2 + 3*value_x3 ) ) + if ( !FloatUtils::areEqual( value_x6, value_x1 + 2 * value_x2 + 3 * value_x3 ) ) { correctSolution = false; } diff --git a/src/system_tests/Test_wsElimination.h b/src/system_tests/Test_wsElimination.h index 6c9ef5217a..d41b4c11e7 100644 --- a/src/system_tests/Test_wsElimination.h +++ b/src/system_tests/Test_wsElimination.h @@ -13,7 +13,6 @@ **/ -#include #include "AcasParser.h" #include "Engine.h" #include "FloatUtils.h" @@ -23,10 +22,11 @@ #include "Preprocessor.h" #include "QueryLoader.h" +#include + class wsEliminationTestSuite : public CxxTest::TestSuite { public: - void setUp() { } @@ -38,11 +38,11 @@ class wsEliminationTestSuite : public CxxTest::TestSuite void test_nlr_to_query_and_back_1() { Engine engine; - InputQuery inputQuery = QueryLoader::loadQuery - ( RESOURCES_DIR "/bnn_queries/smallBNN_original" ); + InputQuery inputQuery = + QueryLoader::loadQuery( RESOURCES_DIR "/bnn_queries/smallBNN_original" ); // Fix the input - for ( unsigned inputVariable = 0; inputVariable < 784; ++ inputVariable ) + for ( unsigned inputVariable = 0; inputVariable < 784; ++inputVariable ) { double pixel = 0.5; @@ -71,11 +71,11 @@ class wsEliminationTestSuite : public CxxTest::TestSuite void test_nlr_to_query_and_back_2() { Engine engine; - InputQuery inputQuery = QueryLoader::loadQuery - ( RESOURCES_DIR "/bnn_queries/smallBNN_parsed" ); + InputQuery inputQuery = + QueryLoader::loadQuery( RESOURCES_DIR "/bnn_queries/smallBNN_parsed" ); // Fix the input - for ( unsigned inputVariable = 0; inputVariable < 784; ++ inputVariable ) + for ( unsigned inputVariable = 0; inputVariable < 784; ++inputVariable ) { double pixel = 0.5; @@ -104,11 +104,11 @@ class wsEliminationTestSuite : public CxxTest::TestSuite void test_nlr_to_query_and_back_3() { Engine engine; - InputQuery inputQuery = QueryLoader::loadQuery - ( RESOURCES_DIR "/bnn_queries/smallBNN_original" ); + InputQuery inputQuery = + QueryLoader::loadQuery( RESOURCES_DIR "/bnn_queries/smallBNN_original" ); // Fix the input - for ( unsigned inputVariable = 0; inputVariable < 784; ++ inputVariable ) + for ( unsigned inputVariable = 0; inputVariable < 784; ++inputVariable ) { double pixel = 0.123; @@ -137,11 +137,11 @@ class wsEliminationTestSuite : public CxxTest::TestSuite void test_nlr_to_query_and_back_4() { Engine engine; - InputQuery inputQuery = QueryLoader::loadQuery - ( RESOURCES_DIR "/bnn_queries/smallBNN_parsed" ); + InputQuery inputQuery = + QueryLoader::loadQuery( RESOURCES_DIR "/bnn_queries/smallBNN_parsed" ); // Fix the input - for ( unsigned inputVariable = 0; inputVariable < 784; ++ inputVariable ) + for ( unsigned inputVariable = 0; inputVariable < 784; ++inputVariable ) { double pixel = 0.123; diff --git a/tools/clang-format-src.sh b/tools/clang-format-src.sh new file mode 100755 index 0000000000..66f8729eec --- /dev/null +++ b/tools/clang-format-src.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash + +SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )" +SRC_DIR="$SCRIPT_DIR"/../src/ + +find $SRC_DIR -iname *.h -o -iname *.cpp | xargs clang-format -style=file -i