Nantes Université

Skip to content
Extraits de code Groupes Projets
gcdmodel.cpp 16,8 ko
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
#pragma once

#include "cmdline.h"
#include "gcdexcl.h"
#include "gcdmodel.h"
using namespace std;

namespace pictcli_gcd
{

//
// when constraints are too strict and entire parameters get excluded from
// generation, the process can't continue
//
bool CGcdData::CheckEntireParameterExcluded()
{
    // key is a parameter, parameter has a set of values
    map< Parameter*, set< int > > paramMap;
    set< int > emptySet;

    // walk through all exclusions, pick one-element ones, and add them to the map
    for( auto & exclusion : Exclusions )
    {
        if( 1 == exclusion.size() )
        {
            ExclusionTerm& term = const_cast<ExclusionTerm&> ( *( exclusion.begin() ) );
            auto result = paramMap.insert( make_pair( term.first, emptySet ) );

            set< int >& values = ( result.first )->second;
            values.insert( term.second );
        }
    }

    // if any of the params in the map contains all elements then the entire parameter is excluded
    for( auto & parameter : paramMap )
    {
        if( ( parameter.first )->GetValueCount() == static_cast<int> ( parameter.second.size() ))
        {
            auto found = _modelData.FindParameterByGcdPointer( parameter.first );
            assert( found != _modelData.Parameters.end() );

            wstring param = L"'" + found->Name + L"'";
            PrintMessage( InputDataError, L"Too restrictive constraints. All values of parameter",
                          (wchar_t*) param.c_str(), L"got excluded." );
            return( true );
        }
    }

    return( false );
}

//
//
//
wstrings CGcdData::GetSingleItemExclusions()
{
    wstrings collection;

    for( auto & exclusion : Exclusions )
    {
        if( 1 == exclusion.size() )
        {
            ExclusionTerm& term = const_cast<ExclusionTerm&> ( * exclusion.begin() );
            auto found = _modelData.FindParameterByGcdPointer( term.first );
            assert( found != _modelData.Parameters.end() );

            wstring text = found->Name;
            text += L": ";
            text += found->Values.at( term.second ).GetPrimaryName();
            collection.push_back( text );
        }
    }

    return collection;
}

//
//
//
bool CGcdData::FixParamOrder( IN Model* submodel )
{
    // clean order assignments for non-result params, set order of result params to 1
    for( auto & param : _modelData.Parameters )
    {
        if( param.IsResultParameter )
        {
            param.GcdPointer->SetOrder( 1 );
        }
        else
        {
            param.GcdPointer->SetOrder( UNDEFINED_ORDER );
        }
    }

    // If this is an actual submodel (a model other than the root), by now it will have its
    // order defined so use it across all its parameters
    if( submodel != _task.GetRootModel() )
    {
        for( auto & param : submodel->GetParameters() )
        {
            if( UNDEFINED_ORDER == param->GetOrder() )
            {
                param->SetOrder( submodel->GetOrder() );
            }
        }
    }

    // For the root model, use orders specified in parameter definitions or if none was
    // defined, use the default order of the model
    else
    {
        // order from param definitions
        for( auto & param : submodel->GetParameters() )
        {
            if( UNDEFINED_ORDER == param->GetOrder() )
            {
                auto p = _modelData.FindParameterByGcdPointer( param );
                assert( p != _modelData.Parameters.end() );
                if( p->Order != UNDEFINED_ORDER )
                {
                    // TODO: add verification of Order
                    // if p->Order > model->parmeters.count - model.ResultParameters.count then error out
                    param->SetOrder( p->Order );
                }
                else
                {
                    param->SetOrder( submodel->GetOrder() );
                }
            }
        }
    }

    return( true );
}

//
//
//
typedef map< CModelParameter*, Parameter* > CParamMap;

//
// the main proc translating the model gathered from the UI to one used by the engine
//
ErrorCode CGcdData::TranslateToGCD()
{
    Model* rootModel = new Model( L"", MixedOrder, _modelData.Order, _modelData.RandSeed );
    Models.push_back( rootModel );

    _task.SetRootModel( rootModel );
    _task.SetGenerationMode( _modelData.GenerationMode );
    if( _modelData.GenerationMode == Approximate )
    {
        _task.SetMaxRandomTries( _modelData.MaxApproxTries );
    }

    // first resolve all submodels:
    //  each submodel will be a new model linked to a root model
    //  all parameters not assigned to any submodel will be linked to the root

    // create a map of all parameter iterators, this will guide the rest of the translation
    CParamMap paramMap;

    for( size_t index = 0; index < _modelData.Parameters.size(); ++index )
    {
        CModelParameter& param = _modelData.Parameters[ index ];

        Parameter* gcdParam = new Parameter( UNDEFINED_ORDER, index, static_cast<int>( param.Values.size() ),
                                             param.Name, param.IsResultParameter );

        // find out and assign weights to values
        // we don't have to care for the clean-up of the structure, Parameter's destructor will clean it
        vector< int > weightVector;
        for( auto & value : param.Values )
        {
            weightVector.push_back( value.GetWeight() );
        }
        gcdParam->SetWeights( weightVector );

        // store the structure, update its back pointer and 
        Parameters.push_back( gcdParam );
        param.GcdPointer = gcdParam;
        
        // store the pointer in a safe place for later
        paramMap.insert( make_pair( &param, gcdParam ) );
    }

    // we will store all params assigned to submodels here
    set<Parameter*> usedInSubmodels;

    // now go through all the submodels and wire up parameters to models
    for( auto & submodel : _modelData.Submodels )
    {
        Model* gcdModel = new Model( L"", MixedOrder, submodel.Order, _modelData.RandSeed );
        Models.push_back( gcdModel );

        for( auto & idx_param : submodel.Parameters )
        {
            // idx_param is an index of a parameter in ModelData.Parameters collection
            // to find a submodel in a guiding map let's locate that parameter and get an iterator
            vector< CModelParameter >::iterator i_param = _modelData.Parameters.begin() + idx_param;
            CParamMap::iterator found = paramMap.find( &(*i_param) );
            assert( found != paramMap.end() );

            // insert
            gcdModel->AddParameter( found->second );
            usedInSubmodels.insert( found->second );
        }
    }

    // wire up all submodels to a root model
    for( auto & model : Models )
    {
        if( rootModel != model )
        {
            rootModel->AddSubmodel( model );
        }
    }

    // for outstanding parameters we have two options:
    // 1. if any submodels were explicitly defined by a user we should create a submodel for each
    //    outstanding parameter; all such submodels should be uplinked to the root
    // 2. if no submodels were defined we just put params directly to the root
    if( usedInSubmodels.size() != paramMap.size() )
    {
        if( _modelData.Submodels.size() > 0 )
        {
            for( auto & iparam : paramMap )
            {
                if( usedInSubmodels.find( iparam.second ) != usedInSubmodels.end() )
                {
                    continue;
                }

                Model* subModel = new Model( L"", MixedOrder, 1, _modelData.RandSeed );
                Models.push_back( subModel );
                rootModel->AddSubmodel( subModel );

                subModel->AddParameter( iparam.second );
            }
        }
        else
        {
            for( auto & iparam : paramMap )
            {
                rootModel->AddParameter( iparam.second );
            }
        }
    }

    // add seeding rows
    for( auto & seed : _modelData.RowSeeds )
    {
        RowSeed rowSeed;
        for( auto & item : seed )
        {
            // find a pointer to Parameter and ordinal number of the value
            vector<CModelParameter>::iterator param = _modelData.FindParameterByName( item.first );
            assert( param != _modelData.Parameters.end() );
            int nVal = param->GetValueOrdinal( item.second, _modelData.CaseSensitive );
            if( nVal >= 0 )
            {
                rowSeed.insert( make_pair( param->GcdPointer, nVal ) );
            }
        }
        _task.AddRowSeed( rowSeed );
    }

    // make sure all order fields in models are set appropriately
    if( !fixModelAndSubmodelOrder() )
    {
        return( ErrorCode_BadModel );
    }
    
    // add exclusions for negative values
    addExclusionsForNegativeRun();

    // add user-specified exclusions now
    
    // parse the constraints and make exclusions out of them
    ConstraintsInterpreter interpreter( _modelData, Parameters );
    if( !interpreter.ConvertToExclusions( Exclusions ) )
    {
        return( ErrorCode_BadConstraints );
    }
    _constraintWarnings.assign( interpreter.GetWarnings().begin(), interpreter.GetWarnings().end() );

    if( _modelData.Verbose )
    {
        PrintLogHeader( L"Initial set of exclusions" );
        PrintGcdExclusions();
    }

    // add each exclusion to that model in the hierarchy which is the most suitable:
    //  1. a subtree of that model must have all the parameters of the exclusion
    //  2. no lower subtree satisfies the condition 1)
    for( auto & excl : Exclusions )
    {
        _task.AddExclusion( const_cast<Exclusion&> ( excl ) );
    }

    _task.PrepareForGeneration();

    // at this point we don't need gcdData.Exclusions anymore
    Exclusions.clear();
    __insert( Exclusions, _task.GetExclusions().begin(), _task.GetExclusions().end() );

    if( _modelData.Verbose )
    {
        PrintLogHeader( L"After derivation" );
        PrintGcdExclusions();
    }

    return( ErrorCode_Success );
}

//
//
//
void CGcdData::PrintGcdExclusions()
{
    for( auto & exclusion : Exclusions )
    {
        for( auto & term : exclusion )
        {
            size_t paramIdx;
            for( paramIdx = 0; paramIdx < Parameters.size(); ++paramIdx )
            {
                Parameter* param = Parameters[ paramIdx ];
                if( param == term.first ) break;
            }
            CModelParameter& pp = _modelData.Parameters[ paramIdx ];
            CModelValue&     vv = pp.Values[ term.second ];
            wcerr << L"( " << pp.Name << L": " << vv.GetPrimaryName() << L" ) ";
        }
        wcerr << endl;
    }
    wcerr << L"Count: " << (unsigned int) Exclusions.size() << endl;
}

//
//
//
void CResult::PrintOutput( CModelData& modelData )
{
    wstring encodingPrefix;
    setEncodingType( modelData.GetEncoding(), encodingPrefix );
    wcout << encodingPrefix;

    for( vector< CModelParameter >::iterator i_param = modelData.Parameters.begin();
                                             i_param != modelData.Parameters.end();
                                             i_param++ )
    {
        if( i_param != modelData.Parameters.begin() ) wcout << RESULT_DELIMITER;
        wcout << i_param->Name;
    }
    wcout << endl;

    for( vector< CRow >::iterator i_row = TestCases.begin();
                                  i_row != TestCases.end();
                                  i_row++ )
    {
        for( wstrings::iterator i_value = i_row->DecoratedValues.begin();
                                i_value != i_row->DecoratedValues.end();
                                i_value++ )
        {
            if( i_value != i_row->DecoratedValues.begin() )
            {
                wcout << RESULT_DELIMITER;
            }
            wcout << *i_value;
        }
        wcout << endl;
    }
}

//
//
//
void CResult::PrintConstraintWarnings()
{
    if( SingleItemExclusions.size() > 0 )
    {
        wstring text = L"Restrictive constraints. Output will not contain following values: ";
        for( auto item : SingleItemExclusions )
        {
            text += L"\n  " + item;
        }
        PrintMessage( ConstraintsWarning, (wchar_t*) text.c_str() );
    }

    for( auto & warn : SolverWarnings )
    {
        PrintMessage( ConstraintsWarning, (wchar_t*) warn.c_str() );
    }
}

//
//
//
void CResult::PrintStatistics()
{
    PrintStatisticsCaption( static_cast<wstring&> ( wstring( L"Generated tests" ) ) );
    wcout << static_cast<int> ( TestCases.size() ) << endl;
}

//
// figures out order for all model elements with UNDEFINED_ORDER
//
bool CGcdData::fixModelAndSubmodelOrder()
{
    if( _modelData.Order < 1 )
    {
        PrintMessage( InputDataError, L"Order cannot be smaller than 1" );
        return( false );
    }

    Model* rootModel = _task.GetRootModel();

    // If the order given as arg to the program has not been explicitely defined it defaults to 2
    // If there's only one parameter or submodel in the model, the order of 2 will fail to execute
    // To aviod this, must switch to lower order behind the scenes
    size_t inputParamCount = _modelData.TotalParameterCount() - _modelData.ResultParameterCount();

    if( _modelData.ProvidedArguments.find( SWITCH_ORDER ) == _modelData.ProvidedArguments.end() )
    {
        // if submidels were defined, don't need any params, otherwise order = params without submodels
        if( _modelData.Submodels.size() > 0 )
        {
            if( _modelData.Order > static_cast<int>( rootModel->GetSubmodelCount() ) )
            {
                _modelData.Order = rootModel->GetSubmodelCount();
            }
        }
        else
        {
            if( inputParamCount > 0 && _modelData.Order > static_cast<int>( inputParamCount ) )
            {
                _modelData.Order = static_cast<int>( inputParamCount );
            }
        }

        rootModel->SetOrder( _modelData.Order );
    }

    // now perform standard check on the order
    if( _modelData.Submodels.size() > 0 )
    {
        // order of combinations provided to the tool cannot be bigger than number of submodels
        if( _modelData.Order > static_cast<int>( rootModel->GetSubmodelCount() ) )
        {
            PrintMessage( InputDataError, L"Order cannot be larger than total number of submodels and oustanding parameters" );
            return( false );
        }
    }
    else
    {
        // check that the order is at most the number of params
        if( _modelData.Order > (int) inputParamCount )
        {
            PrintMessage( InputDataError, L"Order cannot be larger than number of parameters" );
            return( false );
        }
    }

    // now that we have the model order calculated, fix all submodels in which order is still UNDEFINED
    for( auto & model : Models )
    {
        if( model != rootModel && UNDEFINED_ORDER == model->GetOrder() )
        {
            model->SetOrder( min( (int) model->GetParameters().size(), _modelData.Order ) );
        }
    }

    // perform checks on the submodels
    for( auto & model : Models )
    {
        if( model->GetOrder() < 1 )
        {
            PrintMessage( InputDataError, L"Order of a submodel should be at least 1" );
            return( false );
        }

        // only for models that do not contain other models
        if( 0 == model->GetSubmodelCount() )
        {
            if( model->GetOrder() > (int) ( model->GetParameters().size() ) )
            {
                PrintMessage( InputDataError, L"Order of a submodel cannot be larger than number of involved parameters" );
                return( false );
            }
        }
    }

    return( true );
}

//
// negative runs are accomplished by adding synthetic exclusions such that
// no two negative values can co-exist in one test case
//
void CGcdData::addExclusionsForNegativeRun()
{
    for( size_t param1Idx = 0; param1Idx < _modelData.Parameters.size(); ++param1Idx )
    {
        CModelParameter& param1 = _modelData.Parameters[ param1Idx ];

        for( size_t val1Idx = 0; val1Idx < param1.Values.size(); ++val1Idx )
        {
            CModelValue& val1 = param1.Values[ val1Idx ];

            if( !val1.IsPositive() )
            {
                for( size_t param2Idx = param1Idx + 1; param2Idx < _modelData.Parameters.size(); ++param2Idx )
                {
                    CModelParameter& param2 = _modelData.Parameters[ param2Idx ];

                    for( size_t val2Idx = 0; val2Idx < param2.Values.size(); ++val2Idx )
                    {
                        CModelValue& val2 = param2.Values[ val2Idx ];

                        if( !val2.IsPositive() )
                        {
                            Exclusion excl;
                            excl.insert( make_pair( Parameters[ param1Idx ], (int) val1Idx ) );
                            excl.insert( make_pair( Parameters[ param2Idx ], (int) val2Idx ) );
                            Exclusions.insert( excl );
                        }
                    }
                }
            }
        }
    }
}

}